gpt4 book ai didi

python - opencv - python - 在 cv2.inRange 中使用 HSV 颜色时感到困惑

转载 作者:太空宇宙 更新时间:2023-11-03 22:48:41 24 4
gpt4 key购买 nike

我正在尝试使用 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([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')

mario_bgr

2) hsv 中的阈值(不能正常工作)

# first convert the img, and the associated lower and upper bound to HSV
hsv_img_test = cv2.cvtColor(img_test, cv2.COLOR_BGR2HSV)
lower_hsv = cv2.cvtColor(np.uint8([[[b-step,g-step,r-step]]]), cv2.COLOR_BGR2HSV)
upper_hsv = cv2.cvtColor(np.uint8([[[b+step,g+step,r+step]]]), cv2.COLOR_BGR2HSV)


plt.figure(figsize=(20,10))
plt.subplot(1,2,1)
plt.imshow(cv2.cvtColor(hsv_img_test, cv2.COLOR_BGR2RGB))

# apply threshold on hsv image
mask = cv2.inRange(hsv_img_test, lower_hsv, upper_hsv)
plt.subplot(1,2,2)
plt.imshow(mask, cmap='gray')

mario_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 坐标中的框。引用下面的维基百科文章: HSL ans HSV Color Spaces

关于python - opencv - python - 在 cv2.inRange 中使用 HSV 颜色时感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43305234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com