![]() |
OpenCV
4.2.0
Open Source Computer Vision
|
.2.0+dfsg_doc_py_tutorials_py_imgproc_py_colorspaces_py_colorspaces
There are more than 150 color-space conversion methods available in OpenCV. But we will look into only two, which are most widely used ones: BGR \(\leftrightarrow\) Gray and BGR \(\leftrightarrow\) HSV.
For color conversion, we use the function cv.cvtColor(input_image, flag) where flag determines the type of conversion.
For BGR \(\rightarrow\) Gray conversion, we use the flag cv.COLOR_BGR2GRAY. Similarly for BGR \(\rightarrow\) HSV, we use the flag cv.COLOR_BGR2HSV. To get other flags, just run following commands in your Python terminal:
Now that we know how to convert a BGR image to HSV, we can use this to extract a colored object. In HSV, it is easier to represent a color than in BGR color-space. In our application, we will try to extract a blue colored object. So here is the method:
Below is the code which is commented in detail:
Below image shows tracking of the blue object:
This is a common question found in stackoverflow.com. It is very simple and you can use the same function, cv.cvtColor(). Instead of passing an image, you just pass the BGR values you want. For example, to find the HSV value of Green, try the following commands in a Python terminal:
Now you take [H-10, 100,100] and [H+10, 255, 255] as the lower bound and upper bound respectively. Apart from this method, you can use any image editing tools like GIMP or any online converters to find these values, but don't forget to adjust the HSV ranges.