如何使用opencv python将RGB颜色范围更改为红色

时间:2018-08-05 23:33:56

标签: python opencv image-editing python-3.7

我从this stackoverflow question找到了这段代码

import pandas
from itertools import chain
import numpy

df = pandas.DataFrame(t)
df['stage.value'] = df['stage'].apply(lambda cell: cell['value'])
df['stage.name'] = df['stage'].apply(lambda cell: cell['Name'])
df['q_']= df['quality'].apply(lambda cell: [(m['type']['Name'], m['value'] if 'value' in m.keys() else 1) for m in cell])
df['q_'] = df['q_'].apply(lambda cell: dict((k, v) for k, v in cell))
keys = set(chain(*df['q_'].apply(lambda column: column.keys())))
for key in keys:
    column_name = 'q_{}'.format(key).lower()
    df[column_name] = df['q_'].apply(lambda cell: cell[key] if key in cell.keys() else numpy.NaN) 
df.drop(['stage', 'quality', 'q_'], axis=1, inplace=True)

有什么办法可以改变线路

import numpy as np
import imutils
import cv2
img_rgb = cv2.imread('black.png')
Conv_hsv_Gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(Conv_hsv_Gray, 0, 255,cv2.THRESH_BINARY_INV |cv2.THRESH_OTSU)
img_rgb[mask == 255] = [0, 0, 255]
cv2.imshow("imgOriginal", img_rgb)  # show windows
cv2.imshow("mask", mask)  # show windows
cv2.waitKey(0)

还是其他可以改变颜色范围的东西? 例如:

img_rgb[mask == 255] = [0, 0, 255]

1 个答案:

答案 0 :(得分:2)

是的。

首先,您必须创建要更改颜色范围的遮罩,答案是inRange function of OpenCV

然后,通过numpy,您可以说蒙版不为0的地方在我的图像中将它们涂成红色。这是该代码:

import numpy as np
import cv2

# load image and set the bounds
img = cv2.imread("D:\\debug\\HLS.png")
lower =(255, 55, 0) # lower bound for each channel
upper = (255, 255, 10) # upper bound for each channel

# create the mask and use it to change the colors
mask = cv2.inRange(img, lower, upper)
img[mask != 0] = [0,0,255]

# display it
cv2.imshow("frame", img)
cv2.waitKey(0)

如果您想实际获得一定范围的颜色(例如所有蓝色),则最好使用HLS或HSV颜色空间。