This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging
Color space conversion
1. Layer operation
As mentioned in Part 2, if the image is binary (black and white) or grayscale, a pixel needs an 8-bit binary to represent it. For color images, a pixel needs to be represented by three 8-bit binaries. We think of grayscale images as having only one layer, whereas normal color images have three layers.
For grayscale images, pixels emphasize the degree of white. When the pixel value is 0, the image will appear black, and when the pixel value is 255, the image will appear white. And the gray in the middle, we can understand “not white enough” color.
For color images, we usually use RGB three colors. They are red, green, and blue, and we can show all kinds of colors by mixing these three colors.
So how do you manipulate layers in OpenCV? Let’s first open a color image and check its number of channels:
import cv2
# Read image
img = cv2.imread("xyql.jpg")
View the shape of the image
print(img.shape)
Copy the code
The output is as follows:
(1079.1080.3)
Copy the code
Where 3 is the number of layers in the image. We can separate the three channels by index:
import cv2
# Read image
img = cv2.imread('test.jpg')
# Slice to extract channel B
b = img[:, :, 0]
# Slice to extract G channel
g = img[:, :, 1]
# Slice to extract R channel
r = img[:, :, 2]
Copy the code
Since the image mode in OpenCV is BGR by default, the 0th channel we separated is B, the first is G and the second is r. We can look at the images of the three channels:
Above are the original image and BGR three channel images. Since the split image has only one channel, it is displayed in black and white.
You can see that nana has a rosy complexion in the original image, so the R channel skin is lighter (white color, higher pixel value).
In addition to indexing ourselves, we can also call OpenCV’s built-in methods to separate channels as follows:
import cv2
# Read image
img = cv2.imread('test.jpg')
Call the OpenCV built-in method to separate channels
b, g, r = cv2.split(img)
Copy the code
In the code we call cv2.split(), we need to receive with three arguments if our image has three channels, and with four arguments if we have four channels.
2. Color space
We’ve already touched on hitting color Spaces before, such as RGB and GRAY. In addition to RGB and GRAY, there are XYZ, YCrCb, HSV, etc. Different color space removals deal with different problems, sometimes we will convert the image to the specified color space for processing accordingly.
RGB (we think RGB and BGR are the same color space) is a computer-friendly color space composed of three primary colors. But for people, the RGB color space is difficult to understand. We do not say that yellow is red + green, nor do we say that white is red + green + blue (for ordinary people).
HSV color space is a model conforming to human visual perception, which uses hues (also known as Hue), Saturation and Value to represent pixels. Their explanations are as follows:
From Easy Introduction to OpenCV: Python for Python by Li Lizong.
● Hue: Hue is related to the main wavelengths of light in the mixed spectrum. For example, “red, orange, yellow, green, cyan, blue and violet” indicate different hues. If you think about it in terms of wavelength, different wavelengths of light show different colors, but they actually show differences in hue.
● Saturation: Relative purity, or the amount of white light mixed with a color. Pure spectral colors are fully saturated, and colors such as deep red (red plus white) and mauve (purple plus white) are undersaturated, with saturation inversely proportional to the amount of white light added.
● Brightness: reflects the degree of light perceived by the human eye, which is related to the reflection of the object. For color, if the more white mixed in, the higher the brightness; The more black you add to it, the less bright it will be.
If we encounter a scene that needs to be saturated, we can choose to use HSV color space.
3. Conversion of color space
There are fixed formulas for color space conversion, and these formulas are very simple, so let’s look at one of them briefly. RGB to YCrCb color space conversion:
The value of δ is calculated as follows:
We don’t need to calculate it ourselves, but OpenCV provides a color space conversion function cv2.cvtcolor () with the following format:
dst = cv2.cvtColor(src, code)
Copy the code
This function takes two arguments, the image to be converted and the mode to be converted. Finally, the function will return the converted result, focusing on the code argument.
In the code argument, we just need to add some constants from OpenCV, which are easy to understand:
Because of the length of the picture, only part of it is listed here. Most of the naming rules are COLOR_XX2YY, that is, the function is to convert the picture whose color space is XX to YY color space. The most common ones we use are the following:
# Convert BGR to GRAY
cv2.COLOR_BGR2GRAY
Convert BGR to RGB
cv2.COLOR_BGR2RGB
# Convert BGR to HSV
cv2.COLOR_BGR2HSV
# Convert BGR to BGRA
cv2.COLOR_BGR2BGRA
Copy the code
To put this into practice, let’s look at a simple code:
import cv2
import numpy as np
from PIL import Image
# Read image
img = Image.open('nn.jpg')
# Transform image object into Ndarray object
img = np.array(img)
# Display images
cv2.imshow('img', img)
cv2.waitKey()
cv2.destroyAllWindows()
Copy the code
Here is the original image with the code above:
In our code we use the PIL module to read the image, because BY default PIL reads in RGB mode, so when we convert it directly to an Ndarray array, OpenCV reverses the R and B channels, so the image color is displayed abnormally.
The installation of PIL module is as follows:
pip install pillow
Copy the code
In fact, we can make a simple analysis, this time Nana is still ruddy-faced, because the effect picture on the right has reversed the R and B channels, so the red part of the display effect is close to blue, and the blue clothing effect is close to red.
To display properly we need to do some simple transformations to the color space:
import cv2
import numpy as np
from PIL import Image
img = Image.open('nn.jpg')
img = np.array(img)
# Convert RGB image to BGR
bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imshow('img', bgr)
cv2.waitKey()
cv2.destroyAllWindows()
Copy the code
You can try it yourself, and it will look exactly like the original. The same is true for other color Spaces, which I won’t show you here.
More content can follow the personal public number “new folder X”.