OpenCv color space

Table of contents

1. RGB

2. Introduction to image processing

3. Color space conversion

1. RGB

There are many different color models when representing images, but the most common is the red, green, blue (RGB) model. The RGB model is an additive color model in which the primary colors (in the RGB model, the primary colors are red, R, green G and blue B) mixed together can be used to represent a wide range of colors.
Each primary color (R, G, B) usually represents a channel, and its value range is an integer value within the range 0, 255]. Therefore, there are a total of 256 possible discrete values ​​for each channel, which corresponds to the total number of bits used to represent the color channel value (28=256). Additionally, images represented using the RGB model are called 24-bit color depth images because there are three different channels:

The most common color space is RGB, and the human eye also distinguishes colors based on the RGB color space.

OpenCv uses BGR by default. The difference between BGR and RGB color spaces is that the order of pictures on the color channels is different.

2. Introduction to image processing

First of all, the first concept engraved in our minds is:

Pictures are made up of pixels! ! !

The above image perfectly shows the composition of the picture. 

Images are generally divided into three categories:

1.Binary image:

The meaning of binary image representation is that each pixel is only composed of 0 and 1, 0 represents black, 1 represents white, and the black and white here are pure black and pure white. Let’s take the official website as an example.

2. Grayscale image

A grayscale image is an 8-bit bitmap. What does that mean? That is to say, 00000001 all the way to 11111111, this is the binary representation. If expressed in our commonly used decimal system, it is 0-255. Among them, 0 means pure black, 255 means pure white, and the middle is the related color from pure black to pure white. Let’s still take Lina as an example.

3. Color images 

All colors in the computer can be composed of R (red channel), G (green channel), and B (blue channel), each of which has 0-255 pixel colors. For example, R=234, G=252, and B=4 represent yellow. It is also shown in yellow. So the color image is composed of three faces, corresponding to R, G, and B respectively. Let’s take Lina as an example.


3. Color space conversion

 code show as below:

import cv2

def callback(value):

# 创建窗口

# 读取图片,OpenCv默认读进来的图片为BGR的色彩空间
img = cv2.imread('6.jpg')

# 常见的颜色空间转换
colorspaces = [cv2.COLOR_BGR2RGBA,cv2.COLOR_BGR2BGRA,
# 创建trackbar

while True:
    index = cv2.getTrackbarPos('trackbar','color')

    # 颜色空间的转换API
    cvt_img = cv2.cvtColor(img,colorspaces[index])

    key = cv2.waitKey(10)
    if key == ord('q'):

# 释放资源

The running results are as follows:




Guess you like