[英]Trouble with detecting color from HSV image using OpenCV and Python
I am trying to perform a simple colored object detection using OpenCV and Python. 我正在尝试使用OpenCV和Python执行简单的彩色对象检测。
I have read several tutorials but I encounter a confusing problem that prevents me to progress. 我已阅读了几个教程,但遇到一个让我无法进步的令人困惑的问题。 Although I provide correct data HSV, my program does not seem to detect objects of that color. 虽然我提供了正确的数据HSV,但我的程序似乎没有检测到那种颜色的对象。
I use this image (sorry for the poor quality of my webcam): 我使用这张图片(抱歉我的网络摄像头质量很差):
In order to detect the red object, I recovered the HSV color data: 为了检测红色物体,我恢复了HSV颜色数据:
And here is my code: 这是我的代码:
YELLOW = 30
BLUE = 210
GREEN = 145
RED = 320
color = RED
img = cv2.imread("sample.png")
hue = color // 2
lower_range = np.array([max(0, hue - 10), 0, 0], dtype=np.uint8)
upper_range = np.array([min(180, hue + 10), 255, 255], dtype=np.uint8)
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(img, lower_range, upper_range)
binary_img = cv2.bitwise_and(img_hsv, img_hsv, mask=mask)
binary_img = cv2.cvtColor(binary_img, cv2.COLOR_BGR2GRAY)
_, binary_img = cv2.threshold(binary_img, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('sample', binary_img)
cv2.waitKey(0)
Result: 结果:
The result for others colors is correct (not perfect because of the poor quality I guess), but I can not get something for the red. 其他颜色的结果是正确的(不完美,因为我猜的质量很差),但我不能得到红色的东西。 Yet, the HSV converted image is quite explicit: 然而,HSV转换的图像非常明确:
Do you see what am I doing wrong, please? 你知道我做错了什么吗?
You are doing everything right, the only problem is that you apply your threshold on the BGR image instead of the HSV. 您正在做的一切正确,唯一的问题是您在BGR图像而不是HSV上应用阈值。
Change: 更改:
mask = cv2.inRange(img, lower_range, upper_range)
To 至
mask = cv2.inRange(img_hsv, lower_range, upper_range)
I tested it and it looks just fine. 我测试了它看起来很好。 I guess you'll need some morphological operations to get to your final result. 我想你需要一些形态学操作来得到你的最终结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.