Article Directory
1. Read the picture
cv2.imread(filename, flags)
:
-filename: 文件名称
-flags: 0 读入灰度图片,1 读入彩色图片
cv2.imshow(winname, mat)
:
-winname: 窗口名字
-mat: 要展示的图片矩阵
cv2.waitKey(0)
: Pause the program so that the picture can be displayed
import cv2
img = cv2.imread("img.jpg", 1)
cv2.imshow('img', img)
cv2.waitKey(0)
2. Picture writing
There are four steps to read pictures:
1.文件的读取
2.封装格式解析(jpg,png等格式)
3.数据解码
4.数据加载
The picture read in this way is the original data of the picture
cv2.imwrite(filename, img)
:
-filename: 图片名称
-img: 图片数据
import cv2
img = cv2.imread("img.jpg", 1)
cv2.imwrite('img1.jpg', img)
True
2.1 Image quality
1. jpg
Picture files are compressed at the expense of picture quality, which belongs to lossy compression
cv2.IMWRITE_JPEG_QUALITY:
Indicates the current image quality, the compression range is 0-100, and different compression ratios correspond to different image sizes. Let's experience it below:
import cv2
img = cv2.imread("img.jpg", 1)
cv2.imwrite('imgTest.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 0])
True
The original image is as follows:
Image size is 400kb
The compressed picture is:
The image size is 40kb, and there is a serious mosaic phenomenon
import cv2
img = cv2.imread("img.jpg", 1)
cv2.imwrite('imgTest2.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 50])
True
The compressed picture is:
The picture size is 200kb, the mosaic phenomenon is not so serious
2. png
The compression of the image format is lossless, and the transparency can be set
import cv2
img = cv2.imread("img.jpg", 1)
cv2.imwrite('imgTest1.png', img)
True
import cv2
img = cv2.imread("img.jpg", 1)
cv2.imwrite('imgTest2.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 0])
True
The compressed image is:
The picture size is: 5.92MB
import cv2
img = cv2.imread("img.jpg", 1)
cv2.imwrite('imgTest3.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 50])
True
The image size becomes 2.34MB
It can be seen that jpg
the lower the value of the png
image file image quality, the higher the compression ratio, the lower the value of the image file image quality, the lower the compression ratio
3. Pixel
像素
: Refers to the small squares that make up the image
RGB
: Each color is a combination of RGB (red, green, blue) three colors
颜色深度
: For example, 8bit means that the range of each color is 0~255, so there are 256^3 colors in total
图像宽高
: Indicates the number of pixels in the horizontal and vertical directions
Calculation method for uncompressed pictures: w * h * 颜色通道(3) * 8 bit / 8(B)
3.1 Pixel reading and writing
Each pixel is composed of 3 parts. Generally, the format of image storage is RGB, but the image read by opecv is in BGR format
We turn the column in the upper left corner of the picture blue
import cv2
img = cv2.imread('img.jpg', 1)
(b, g, r) = img[100, 100] # 读取像素值
print(b, g, r)
#10,100 --- 110, 100
for i in range(1, 1000):
img[10 + i][100] = (255, 0, 0)
cv2.imshow('imageBlue.png', img)
cv2.waitKey(0)
59 54 129
True