简体   繁体   中英

How to find a colors “Upper” and “Lower” range of a color?

I have just started learning color filtering using opencv. I have understood most of the basics but am stuck on one thing.

import cv2
import numpy as np

img = cv2.imread("Circles.png")

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_range = np.array([169,100,100])
upper_range = np.array([189,255,255])

mask = cv2.inRange(hsv, lower_range, upper_range)

cv2.imshow("Image", img)
cv2.imshow("Mask",mask)

cv2.waitKey(0)
cv2.destroyAllWindows()

Where can I find the range of the colors which I want to filter?

Thank you

So basically, what you're trying to do is essentially filter out a color. By default the images are represented in three channels Blue, Green, and Red. But, using this mode of representation, you cannot filter colors easily as the values are split into three channels. That's where the HSV (Hue, saturation, value) mode of representation comes to play.

The line hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) converts the BGR format image to HSV format representation. Now, you can get the value of your required color and just add +-delta value to H channel and you can filter the color accordingly.

For example, if you want to filter green color The BGR representation of gree color will be (0,255,0). First, we need to find the equivalent color representation in HSV that is (60,255,255). We can add a [H-10, 100,100] and [H+10, 255, 255] as upper and lower values accordingly.

You can convert any BGR to corresponding HSV value using.

color_bgr=np.uint8([[[0,255,0]]])
color_hsv = cv2.cvtColor(color_bgr,cv2.COLOR_BGR2HSV)
print(color_hsv)

Please refer to this link for more details https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM