2017-02-13 176 views
0
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,因为我想检查像素是否在某个颜色范围内。python - opencv - 将像素从bgr转换为hsv

我已经尝试过

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

这唤起了错误:无效的指数标量

谢谢!

回答

2

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) 
+0

感谢您的回答! 我该如何检查一个像素是否在蓝色范围内? – cmplx96

+0

它在我从文档提供的代码中这样说。只需从'mask'中获得'px'并检查它是白色还是黑色。 –

+0

px = img [i,j]现在返回0而不是三个值的数组。 你知道这是为什么吗? – cmplx96