opencv-python-在cv2.inRange中使用HSV颜色时感到困惑
我正在尝试使用cv2.inRange(python 2.7)基于颜色执行对象检测。使用BGR颜色时,一切似乎都正常。但是,当我将BGR颜色映射到HSV时,我无法获得正确的遮罩。请参见下面的示例: 1) bgr中的阈值opencv-python-在cv2.inRange中使用HSV颜色时感到困惑,python,opencv,hsv,bgr,Python,Opencv,Hsv,Bgr,我正在尝试使用cv2.inRange(python 2.7)基于颜色执行对象检测。使用BGR颜色时,一切似乎都正常。但是,当我将BGR颜色映射到HSV时,我无法获得正确的遮罩。请参见下面的示例: 1) bgr中的阈值 img_test = cv2.imread("test_img/mario.jpeg") #define color range for object detection step = 10 r,g,b = 203, 31, 25 #red lower_bgr = np.uint8
img_test = cv2.imread("test_img/mario.jpeg")
#define color range for object detection
step = 10
r,g,b = 203, 31, 25 #red
lower_bgr = np.uint8([b-step, g-step, r-step])
upper_bgr = np.uint8([b + step, g + step, r + step])
# plot mario in BGR and corresponding mask
plt.figure(figsize=(20,10))
plt.subplot(1,2,1)
plt.imshow(cv2.cvtColor(img_test, cv2.COLOR_BGR2RGB))
mask = cv2.inRange(img_test, lower_bgr, upper_bgr)
plt.subplot(1,2,2)
plt.imshow(mask, cmap='gray')
2) hsv中的阈值(工作不正常)
…这显然是不正确的。我无法找出代码中的错误,任何帮助都将不胜感激 似乎意外行为来自uint8数组格式。我没有弄清楚确切的原因,但是您应该仔细使用无符号整数(例如:0-1=255)的运算 最后,我想我设法得到了你可能想要的结果:
# first convert the img to HSV
img_test_hsv = cv2.cvtColor(img_test, cv2.COLOR_BGR2HSV)
# convert the target color to HSV
target_color = np.uint8([[[b, g, r]]])
target_color_hsv = cv2.cvtColor(target_color, cv2.COLOR_BGR2HSV)
# boundaries for Hue define the proper color boundaries, saturation and values can vary a lot
target_color_h = target_color_hsv[0,0,0]
tolerance = 2
lower_hsv = np.array([max(0, target_color_h - tolerance), 10, 10])
upper_hsv = np.array([min(179, target_color_h + tolerance), 250, 250])
plt.figure(figsize=(20,10))
plt.subplot(1,2,1)
plt.imshow(cv2.cvtColor(img_test_hsv, cv2.COLOR_HSV2RGB));
# apply threshold on hsv image
mask = cv2.inRange(img_test_hsv, lower_hsv, upper_hsv)
plt.subplot(1,2,2)
plt.imshow(mask, cmap='gray');
需要考虑的另一点是不同颜色空间RGB和HSV的拓扑结构的差异。RGB空间中的长方体不会转换为HSV坐标中的长方体。请参阅以下维基百科文章:
如果
target\u color\u h
是有符号类型,则此操作有效。为了便于保存,可以使用max(公差,目标颜色)-公差
# first convert the img to HSV
img_test_hsv = cv2.cvtColor(img_test, cv2.COLOR_BGR2HSV)
# convert the target color to HSV
target_color = np.uint8([[[b, g, r]]])
target_color_hsv = cv2.cvtColor(target_color, cv2.COLOR_BGR2HSV)
# boundaries for Hue define the proper color boundaries, saturation and values can vary a lot
target_color_h = target_color_hsv[0,0,0]
tolerance = 2
lower_hsv = np.array([max(0, target_color_h - tolerance), 10, 10])
upper_hsv = np.array([min(179, target_color_h + tolerance), 250, 250])
plt.figure(figsize=(20,10))
plt.subplot(1,2,1)
plt.imshow(cv2.cvtColor(img_test_hsv, cv2.COLOR_HSV2RGB));
# apply threshold on hsv image
mask = cv2.inRange(img_test_hsv, lower_hsv, upper_hsv)
plt.subplot(1,2,2)
plt.imshow(mask, cmap='gray');