Programming
python opencv image-processing colors hsv
Updated Mon, 15 Aug 2022 09:57:56 GMT

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.

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.

I use this image (sorry for the poor quality of my webcam):

Sample

In order to detect the red object, I recovered the HSV color data:

Color data

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:

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 Image

Do you see what am I doing wrong, please?




Solution

You are doing everything right, the only problem is that you apply your threshold on the BGR image instead of the 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.





Comments (1)

  • +1 – I am using HSV image but getting strange result. If you have some time, can you look at it here? — Dec 09, 2015 at 04:48