In this blog, we will see how to convert images from one color model to another and how different colors can be obtained from these color models.
In OpenCV, the command for converting an image to another color-space is
cv2.cvtColor(input_image, conversion_method)
for example, BGR to HSV conversion can be done by using cv2.COLOR_BGR2HSV method
1 |
out_img = cv2.cvtColor(input_img, cv2.COLOR_BGR2HSV) |
In OpenCV, more than 150 color-space conversion methods are available. To get the other conversion methods, type the following commands
1 2 3 |
>>> import cv2 >>> conver_method = [i for i in dir(cv2) if i.startswith('COLOR_')] >>> print (conver_method) |
In the previous blog, we learned how we can construct all colors from each model. Now, let’s get the feeling of this with OpenCV.
Here, I will create three trackbars to specify each of B, G, R colors and a window which shows the color obtained by combining different proportions of B, G, R. Similarly for HSI and CMYK models.
In OpenCV, Trackbar can be created using the cv2.createTrackbar() and its position at any moment can be found using cv2.getTrackbarPos().
RGB Trackbar
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 27 28 29 |
import cv2 import numpy as np def nothing(x): pass # Create a black image, a window img = np.zeros((512,512,3), np.uint8) cv2.namedWindow('image',cv2.WINDOW_NORMAl) # create trackbars for color change cv2.createTrackbar('R','image',0,255,nothing) cv2.createTrackbar('G','image',0,255,nothing) cv2.createTrackbar('B','image',0,255,nothing) while True: cv2.imshow('image',img) if cv2.waitKey(1) & 0xFF == ord('q'): break # get current positions of three trackbars r = cv2.getTrackbarPos('R','image') g = cv2.getTrackbarPos('G','image') b = cv2.getTrackbarPos('B','image') img[:] = [b,g,r] cv2.destroyAllWindows() |
You can move these trackbars to obtain different colors. A snapshot of output is shown below
HSI Trackbar
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 27 28 29 |
import cv2 import numpy as np def nothing(x): pass # Create a black image, a window img = np.zeros((512,512,3), np.uint8) cv2.namedWindow('image',cv2.WINDOW_NORMAL) # create trackbars for color change cv2.createTrackbar('H','image',0,180,nothing) cv2.createTrackbar('S','image',0,255,nothing) cv2.createTrackbar('I','image',0,255,nothing) while(True): cv2.imshow('image',img) if cv2.waitKey(1) & 0xFF == ord('q'): break # get current positions of four trackbars r = cv2.getTrackbarPos('H','image') g = cv2.getTrackbarPos('S','image') b = cv2.getTrackbarPos('I','image') img[:,:] = [r,g,b] img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR) cv2.destroyAllWindows() |
We get the following output as
Similarly, you can create trackbar for any color model. Play with these trackbars to get intuition about color models. Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.