1
votes

My problem is that I would like to threshold an HSV image, thanks to OpenCV inRange function. To find my range of hue, I use ImageJ. I uploaded my picture after I changed it from RGB to HSV, and threshold it manually. My HSV image, converted from RGB image is:

https://ibb.co/1RqRDSJ

I obtained these values from imageJ :

H (62;100) S (0;255) V (0;255)

And this threshold result:

https://ibb.co/2d8Dh35

But when I try to obtain the same result with a Python script using OpenCV, I obtain this:

https://ibb.co/YhLRgT4

Here is my script:

import cv2

image_color = cv2.imread(image_color)
image_hsv_convert = cv2.cvtColor(image_color, cv2.COLOR_BGR2HSV)
cv2.imwrite(folder_dest, image_hsv_convert)

H_low = (62/255)*180
H_high = (100/255)*180
HUE_MIN = (H_low,0,0)
HUE_MAX = (H_high,255,255)

frame_threshed = cv2.inRange(image_hsv_convert, HUE_MIN, HUE_MAX)
cv2.imwrite(folder_dest2, frame_threshed)

I know the H values in OpenCV go from 0 to 179, so I've converted ImageJ values into OpenCV values. What's the problem here ? Is ImageJ showing me a wrong result ? Or is my code wrong ?

2

2 Answers

1
votes

In ImageJ, HSV (threshold tool) values all range from 0 to 255. But In OpenCV, S and V range from 0 to 255, while H only ranges from 0 to 180. In ImageMagick, S and V range from 0 to 255, but H ranges from 0 to 360. In GIMP, S and V range from 0 to 100 and H ranges from 0 to 360. So one must understand which range is being used by each tool for HSV.

Thus different scaling of the ranges, especially, for H in different tools account for different threshold results.

See also https://en.wikipedia.org/wiki/HSL_and_HSV

0
votes

The OpenCV imwrite() function can only write BRG images. When you pass a matrix with an image saved in HSV format, it interprets the HSV image as a BGR image. If you convert the HSV matrices to BGR and then write the BGR ones this should work.

eg

frame_threshed_bgr = cv2.cvtColor(frame_threshed, cv2.COLOR_HSV2BGR)
cv2.imrwite(folder_dest2,frame_threshed_bgr)