#主要内容
介绍对图像的基本操作,imread(),imwrite(),imshow()的用法,并结合Matplotlib显示图像。
#总结
#imread()
|
|
Use the function cv2.imread() to read an image. The image should be in the working directory or a full path of image should be given.
Second argument is a flag which specifies the way image should be read.
cv2.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the default flag.
cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode
cv2.IMREAD_UNCHANGED : Loads image as such including alpha channelInstead of these three flags, you can simply pass integers 1, 0 or -1 respectively.
#imshow()
First argument is a window name which is a string. second argument is our image. You can create as many windows as you wish, but with different window names
#imwrite()
First argument is the file name, second argument is the image you want to save.
#waitKey()
cv2.waitKey() is a keyboard binding function. Its argument is the time in milliseconds. The function waits for specified milliseconds for any keyboard event. If you press any key in that time, the program continues. If 0 is passed, it waits indefinitely for a key stroke. It can also be set to detect specific key strokes like, if key a is pressed etc which we will discuss below.
waitKey()可以返回按键键值。
警告 If you are using a 64-bit machine, you will have to modify k = cv2.waitKey(0) line as follows : k = cv2.waitKey(0) & 0xFF
#destroyAllWindows()
cv2.destroyAllWindows() simply destroys all the windows we created. If you want to destroy any specific window, use the function cv2.destroyWindow() where you pass the exact window name as the argument.
#窗口尺寸调整
There is a special case where you can already create a window and load image to it later. In that case, you can specify whether window is resizable or not. It is done with the function cv2.namedWindow(). By default, the flag is cv2.WINDOW_AUTOSIZE. But if you specify flag to be cv2.WINDOW_NORMAL, you can resize window. It will be helpful when image is too large in dimension and adding track bar to windows.
see the code below
#Using Matplotlib
安装matplotlibpip install matplotlib
示例代码如下
警告 Color image loaded by OpenCV is in BGR mode. But Matplotlib displays in RGB mode. So color images will not be displayed correctly in Matplotlib if image is read with OpenCV. Please see the exercises for more details.
使用Matplotlib显示OpenCV彩色图片可能会遇到一些潜在问题
There is some problem when you try to load color image in OpenCV and display it in Matplotlib. Read this discussion and understand it.
解决方法是一个小技巧调换三个通道的顺序img2 = img[:,:,::-1]
#参考资料
[1] OpenCV-Python Tutorial:Getting Started with Images
[2] Matplotlib pyplot doc
[3] 关于Matplotlib显示OpenCV图像的stackoverflow的讨论