Reputation: 51
I'm trying to create a mask for a color range. I know that I need to convert the image to HSV before passing that into inRange. The next two arguments for inRange are the lower value and upper value for the color we're creating a mask for.
What color space are the lower and upper in?
I've seen HSV and BGR according to answers on here. The documentation does not call out the specific color space to use. For example, this answer (How to define a threshold value to detect only green colour objects in an image :Opencv) says the values should be in HSV but passes in values that seem like BGR (e.g. 255). PS - any tips on tools/tricks to pick a specific range? I've been using Google's color picker
Upvotes: 1
Views: 1917
Reputation: 129
The cv2.inRange()
function only checks if array elements lie between the elements of two other arrays.
So if your src
array is shaped as BGR or RGB or HSV your Upper and Lower boundaries should be in the same colorspace. Usually for color segmentation the HSV colorspace is more used, but you can try other colorspaces too.
Upvotes: 3
Reputation: 1045
use the following code to find a specific object HSV color value. And set this HSV value in cv2.inRange lower and upper value. It is a opencv program using your device camera and track-bar you can find HSV upper and lower value:
import cv2
import numpy as np
def nothing(x):
pass
cap = cv2.VideoCapture(0)
cv2.namedWindow("Trackbars")
cv2.createTrackbar("L - H", "Trackbars", 0, 255, nothing)
cv2.createTrackbar("L - S", "Trackbars", 0, 255, nothing)
cv2.createTrackbar("L - V", "Trackbars", 0, 255, nothing)
cv2.createTrackbar("U - H", "Trackbars", 255, 255, nothing)
cv2.createTrackbar("U - S", "Trackbars", 255, 255, nothing)
cv2.createTrackbar("U - V", "Trackbars", 255, 255, nothing)
while True:
_, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
l_h = cv2.getTrackbarPos("L - H", "Trackbars")
l_s = cv2.getTrackbarPos("L - S", "Trackbars")
l_v = cv2.getTrackbarPos("L - V", "Trackbars")
u_h = cv2.getTrackbarPos("U - H", "Trackbars")
u_s = cv2.getTrackbarPos("U - S", "Trackbars")
u_v = cv2.getTrackbarPos("U - V", "Trackbars")
lower_blue = np.array([l_h, l_s, l_v])
upper_blue = np.array([u_h, u_s, u_v])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
mask2 = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
result = cv2.bitwise_and(frame, frame, mask=mask)
cv2.imshow("frame", frame)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
key = cv2.waitKey(1)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
Output: for my object red HSV upper value-[193,188,186], lower value-[135,127,95]
Upvotes: 3