Image grayscale change (OpenCV)

Table of contents

1. The principle of image grayscale change

2. Python code

3. Example picture

4. The image size obtained

Five, running effect diagram


1. The principle of image grayscale change

        The color of each pixel in a color image is determined by three components R, G, and B, and the value range of each component is 0~255. The grayscale image is a special color image with the same three components of R, G, and B. There are two algorithms for it:

        1) Find the average value of the R, G, and B components of each pixel, and then assign this average value to the three components of this pixel.

        2) According to the change relationship between RGB and YUV color spaces, establish the corresponding relationship between the brightness Y and the three color components of R, G, and B: Y=0.3R+0.59G+0.11B, express the gray value of the image with this brightness value .

        OpenCV has a related function cvtColor, which can be used to directly complete the grayscale operation. Let img be the source image matrix, and myimg1 be the grayscaled target image matrix. myimg2 is the copied image.

2. Python code

import cv2
import numpy as np
fn = r"C:\Users\LIHAO\Pictures\Saved Pictures\wallhaven-1pdkkw.jpg"
if __name__ == "__main__":
    img = cv2.imread(fn)
    sp = img.shape
    print(sp)
    # 获取图像大小
    # height
    sz1 = sp[0]
    # width
    sz2 = sp[1]
    # 显示图像大小
    print('width:%d\nheight:%d'%(sz2,sz1))
    # 创建一个窗口并显示图像
    cv2.namedWindow('img')
    cv2.imshow('img', img)
    # 复制图像矩阵,生成与源图像一样的图像,并显示
    myimg2 = img.copy()
    cv2.namedWindow('myimg2')
    cv2.imshow('myimg2', myimg2)
    
    # 复制并转换为灰度图像,并显示
    myimg1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.namedWindow('myimg1')
    cv2.imshow('myimg1', myimg1)
    cv2.waitKey()
    cv2.destroyAllWindows()

3. Example picture

4. The image size obtained

(1080, 1920, 3)
width:1920
height:1080

Five, running effect diagram

 

Guess you like

Origin blog.csdn.net/weixin_51756038/article/details/130046736