OpenCV
4.2.0
Open Source Computer Vision
|
Use the function cv.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.
See the code below:
warning
Even if the image path is wrong, it won't throw any error, but print img
will give you None
Use the function cv.imshow() to display an image in a window. The window automatically fits to the image size.
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.
A screenshot of the window will look like this (in Fedora-Gnome machine):
cv.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.
cv.destroyAllWindows() simply destroys all the windows we created. If you want to destroy any specific window, use the function cv.destroyWindow() where you pass the exact window name as the argument.
See the code below:
Use the function cv.imwrite() to save an image.
First argument is the file name, second argument is the image you want to save.
This will save the image in PNG format in the working directory.
Below program loads an image in grayscale, displays it, saves the image if you press 's' and exit, or simply exits without saving if you press ESC key.
warning
If you are using a 64-bit machine, you will have to modify k = cv.waitKey(0)
line as follows : k = cv.waitKey(0) & 0xFF
Matplotlib is a plotting library for Python which gives you wide variety of plotting methods. You will see them in coming articles. Here, you will learn how to display image with Matplotlib. You can zoom images, save them, etc, using Matplotlib.
A screen-shot of the window will look like this :
warning
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.