Install OpenCV
pip install opencv-python
pip install opencv-contrib-python
I installed opencv-python on the command line, but every time I can't find cv2 in pycharm, I finally add dependencies to the project. The specific operations are as follows:
PyCharm->Settings->Project: Project Name->Python Interpreter -> Click + select version import (opencv-python:4.5.5.64 numpy:1.24.2)
read image
retval = cv2.imread("image file path"[,flags])
retval : read the return value of the picture, essentially an image array class
filename : the full filename of the read file
flags: read the logo, the details are as follows, the first line and the third line are equivalent, you can leave it blank, it is the original image
value |
meaning |
value |
cv2.IMREAD_UNCHANGED |
Keep the original format unchanged |
-1 |
cv2.IMREAD_GRAYSCALE |
Adjust the image to a single-channel grayscale image |
0 |
cv2.IMREAD_COLOR |
Adjust the image to a three-channel BGR image, this is the default value |
1 |
display image
cv2.imshow(window_name,mat)
window_name: the displayed window name
mat is the read or processed image data
save Picture
vetval = cv2.imwrite( filename , img [,flag] )
vetval : save the result, success is True, failure is False
filename : the full path and name of the saved file, including the extension
img : the image to keep
flag: the format of the picture to be saved, can be filled, generally not filled
wait for key
retval = cv2.waitKey( [delay] )
retval: the return value of the button during the waiting time, specifically the ASC code of the button, if there is no button during the waiting time, return -1
delay: A parameter that can be filled in, indicating the waiting time for keyboard operations, in ms, when it is not filled or is 0 or a negative number, it means infinite waiting
After executing this method, the window displaying the picture has been displayed
destroy window
cv2.destroyAllWindows()
After judging the value of the button, judge whether to close and destroy all windows according to the selection (of course, you can not judge, and close the window directly after receiving the button)
Full code:
import cv2 as cv
# 读取图片 可不传图片格式参数,默认为原图 -1和1为原图 0为灰度图
lena = cv.imread("lena.jpg", -1)
# 显示图片 窗口名
cv.imshow("lena's face", lena)
# 保存图片
cv.imwrite("1_other_lena.jpg", lena)
# 窗口显示时间,单位为ms 0/-1为一直显示
cv.waitKey(0)
# 销毁窗口
cv.destroyAllWindows()