In this OpenCV Python article we are going to talk about Color Spaces Introduction. if you are interested in Python GUI Development, you can check the below links.
Also you can read more articles on Python GUI Development
1: PyQt5 GUI Development Tutorials
2: Pyside2 GUI Development Tutorials
3: wxPython GUI Development Tutorials
4: Kivy GUI Development Tutorials
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 ↔ Gray and BGR ↔ HSV.
For color conversion, we use the function cv.cvtColor(input_image, flag) where flag determines the type of conversion.
For BGR → Gray conversion we use the flags cv.COLOR_BGR2GRAY. Similarly for BGR → HSV, we use the flag cv.COLOR_BGR2HSV. To get other flags, just run following commands in your Python terminal :
1 2 3 |
import cv2 as cv flags = [i for i in dir(cv) if i.startswith('COLOR_')] print( flags ) |
This is the complete source code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import cv2 img1 = cv2.imread("lena.tif") bgrgray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) bgrhsv = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV) brightLAB = cv2.cvtColor(img1, cv2.COLOR_BGR2LAB) cv2.imshow("Image", img1) cv2.imshow("BGR 2 GRAY", bgrgray) cv2.imshow("BGR 2 HSV", bgrhsv) cv2.imshow("Bright 2 Lab", brightLAB) cv2.waitKey(0) cv2.destroyAllWindows() |
These lines of codes are for converting our Color Spaces.
1 2 3 |
bgrgray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) bgrhsv = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV) brightLAB = cv2.cvtColor(img1, cv2.COLOR_BGR2LAB) |
And these line of codes are for showing of our images, basically we are going to show the images in different colors.
1 2 3 4 |
cv2.imshow("Image", img1) cv2.imshow("BGR 2 GRAY", bgrgray) cv2.imshow("BGR 2 HSV", bgrhsv) cv2.imshow("Bright 2 Lab", brightLAB) |
Run the complete code and this will be the result
Also you can watch the complete video tutorial for this article
Subscribe and Get Free Video Courses & Articles in your Email