Thursday, 21 December 2017

opencv - python - confused when using HSV color in cv2.inRange

I am trying to perform object detection based on the color
with cv2.inRange (python 2.7). Everything seems to work fine when using BGR color.
However, when I map the BGR color to HSV, I can't get a correct mask. See the example
below:



1) threshold in
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')


href="https://i.stack.imgur.com/8KxMb.png" rel="nofollow
noreferrer">mario_bgr



2) threshold
(not working properly) in 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')


href="https://i.stack.imgur.com/yZQr2.png" rel="nofollow
noreferrer">mario_hsv



...which is
clearly not correct. I can't figure out what is wrong in the code, any help will be much
appreciated!

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...