简体   繁体   English

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

[英]how to change a range of RGB color to Red with opencv python

from this stackoverflow question i found this code 这个stackoverflow问题我发现了这段代码

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)

is there any way i could change the line 有什么办法可以改变路线吗

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

or something else to make it change a range of colors? 或其他使它改变颜色范围的东西? for example: 例如:

([255, 255, 0], [255, 55, 10])

Yes you can. 是的你可以。

First, you must create a mask of the color range to change, and the answer for that is the inRange function of OpenCV . 首先,必须创建要更改颜色范围的遮罩,答案是OpenCVinRange函数

Then, via numpy, you can say where the mask is not 0 paint them in my image red. 然后,通过numpy,您可以说蒙版不为0的地方在我的图像中将它们涂成红色。 This is the code for that: 这是该代码:

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)

If you want actually to get a range of colors (eg all blue colors) it is better to use HLS or HSV color spaces. 如果您实际上希望获得多种颜色(例如,所有蓝色),则最好使用HLS或HSV颜色空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM