Three methods of Python image processing

 Foreword: Recently, I am doing surface defect detection of microscopic electronic devices. I use pyqt5 to make an industrial camera interface that calls Hikvision’s gige interface. The code on the official website uses tkinter to do the interface, and tkinter modify the interface. It is a bit troublesome to modify the code. I modified the basicdemo.py provided by the official website to the pyqt interface. It is very convenient to modify it directly with qtdesigner. There is a difference between displaying photos on label_2 and saving the photos taken by tkinter and pyqt, so I learned about image composition, image reading, processing, displaying, saving, etc.

One, opencv image processing

1. Opencv reads in the BGR channel order by default, and reads the array type numpy.ndarray. It needs to be exchanged to the rgb channel order to be displayed by plt, otherwise there will be color shift due to the inconsistent channel order. Type unit8, 0-255. The image format to be read is (H, W, C).

# opencv库
import cv2 as cv
src=cv.imread('car.jpg')
print(src)
print(src.size)  # (12502500)
print(src.shape)  # (1667,2500,3)
# ship_RGB_2 = cv.cvtColor(src, cv.COLOR_BGR2RGB)
img = cv.resize(src,(800,600))  # cv库的resize
cv.imshow('input_image', img)
cv.imwrite('car_1.jpg',img)
cv.waitKey(0)
cv.destroyAllWindows()

 Two, Image processing image

2. The image is read in the PIL format by default, and the channel order RGB is read in by default. It needs to be converted to the numpy format. The converted array is unit8 , 0-255. The read shape is: (H,W,C).

# PIL库
from PIL import Image
import numpy as np
img = Image.open('car.jpg')
print(img)
print(img.size)  # (2500,1667)
c = np.array(Image.open("car.jpg"))  # 将PIL读取的图像格式转化成数组,才可对其进行操作
print(c.shape, c.dtype)  # 转为数组格式后才能使用shape参数
img = Image.fromarray(np.uint8(img)).resize((800, 600), Image.ANTIALIAS) # 将数组转为PIL格式才能显示
img.save('car_2.jpg')
img.show()

Three, Matplotlib image processing

3. Matplotlib reads in the order of RGB channels by default, and reads the array type numpy.ndarray

#Matplotlib库
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
lena = mpimg.imread('car.jpg') # 这里读入的数据是 float32 型的,范围是0-1
# 此时 lena 就已经是一个 np.array 了,可以对它进行任意处理
print(lena)
print(type(lena))
plt.imshow(lena)
plt.axis('off')  # 不显示坐标轴
plt.savefig("car_3.jpg")
plt.show()

Some parameters of the image:

type(img)  #numpy.ndarray
img.size  #2040000
img.dtype  #dtype('uint8')

 In the end, the industrial camera that reads the gige interface was successfully realized, and the interface was taken, photographed, and saved

 

 

Guess you like

Origin blog.csdn.net/m0_61456316/article/details/129771592