Splitting RGB and HSV values in an Image using OpenCV in Python
Fellow coders, In this tutorial we are going to learn to split RGB and HSV values in an image and display them separately using OpenCV in Python. We will also learn how we can convert RGB to HSV.
When we talk about RGB in an image, we talk about Red, Green, and Blue intensity values at each and every pixel inside the image. In a colorful image, each pixel holds the information of Red, Green and Blue intensity at that pixel and the number of channels. We can separate these channels and view them with the help of OpenCV. The same can be done with HSV values. HSV has three components which include: Hue, Saturation, and Value (or Brightness). Hue defines the color properties of the model, Saturation is the amount of gray in a color, and Value is the brightness of the intensity of the color.
Hue represents the color and in this model, Hue is an angle from 0 to 360 degrees. Colors are as follows:
- Red (0-60)
- Yellow (60-120)
- Green (120-180)
- Cyan (180-240)
- Blue (240-300)
- Magenta (300-360)
Saturation which is the amount of grey in color space ranges from 0-100%. In the case of Value, when we set it to ‘0’ then the color space will be totally black with no brightness and as we increase the Value, the brightness increases and we can see colors.
Python program to Split RGB and HSV values in an Image using OpenCV
I want to mention that, you should activate your python environment before running the file. In this code, we will be using two libraries: NumPy and OpenCV. Please note that in OpenCV BGR format is used instead of RGB.
import numpy as np import cv2 color = cv2.imread("butterfly.jpg", 1) cv2.imshow("Image",color) cv2.moveWindow("Image",0,0) print(color.shape) height,width,channels = color.shape b,g,r = cv2.split(color) rgb_split = np.empty([height,width*3,3],'uint8') rgb_split[:, 0:width] = cv2.merge([b,b,b]) rgb_split[:, width:width*2] = cv2.merge([g,g,g]) rgb_split[:, width*2:width*3] = cv2.merge([r,r,r]) cv2.imshow("Channels",rgb_split) cv2.moveWindow("Channels",0,height) hsv = cv2.cvtColor(color, cv2.COLOR_BGR2HSV) h,s,v = cv2.split(hsv) hsv_split = np.concatenate((h,s,v),axis=1) cv2.imshow("Split HSV",hsv_split) cv2.waitKey(0) cv2.destroyAllWindows()
(356, 493, 3)
Also read: Normalizing an image in OpenCV Python