python-opencv-将像素从bgr转换为hsv [英] python - opencv - convert pixel from bgr to hsv
本文介绍了python-opencv-将像素从bgr转换为hsv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
img = cv2.imread('example.jpg')
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# lower mask (0-10)
lower_red = np.array([0, 50, 50])
upper_red = np.array([10, 255, 255]
mask0 = cv2.inRange(img_hsv, lower_red, upper_red)
# upper mask (170-180)
lower_red = np.array([170, 50, 50])
upper_red = np.array([180, 255, 255])
mask1 = cv2.inRange(img_hsv, lower_red, upper_red)
# join my masks
mask = mask0 + mask1
height = mask.shape[0]
width = mask.shape[1]
# iterate over every pixel
for i in range(height):
for j in range(width):
px = mask[i,j]
print px
# check if pixel is white or black
if (px[2] >= 0 and px[2] <= 40):
在上面的示例中,"px"是BGR中的像素.我需要将该值转换为HSV,因为我想检查像素是否在某个颜色范围内.
In the above example 'px' is a pixel in BGR. I need to convert the value to HSV because I want to check if the pixel is in a certain color range.
我已经尝试过
colorsys.rgb_to_hsv(px[2], px[1], px[0})
引发错误:标量变量的索引无效
which evokes the error: invalid index to scalar variable
谢谢!
推荐答案
You can just convert your whole img
to hsv using the built in method:
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
这篇关于python-opencv-将像素从bgr转换为hsv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文