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,因为我想检查像素是否在某个颜色范围内.

我已经试过了

colorsys.rgb_to_hsv(px[2], px[1], px[0})

这会引起错误:标量变量的索引无效

谢谢!

最佳答案 从
docs

# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)

您可以使用内置方法将整个img转换为hsv:

hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
点赞