In this blog, we will see how to Read, Write and Display Images using OpenCV. I hope you have installed OpenCV, numpy, and matplotlib libraries, if not, please refer to this blog.
Read an image:
To read an image, use the function cv2.imread(filename[, flags]) where filename is the full path of image and flags specifies the way image should be read (>0 for color, =0 for greyscale, and <0 for loading image as is (with alpha channel)).
1 2 3 4 |
import numpy as np import cv2 # Load an image in grayscale img = cv2.imread('F:/downloads/Python.png',0) |
If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix, not an error.
Display an image:
To display an image in a window, use the function cv2.imshow(winname, image) where the first argument is the Name of the window and second is the Image to be shown. So, this will first create a window named as image and displays the image in that window.
Note: This function must be followed by cv2.waitkey(delay) function otherwise the image wouldn’t be displayed.
1 2 3 |
cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows() |
cv2.waitKey(delay) decides for how long the image will be displayed. Its argument delay is the time in milliseconds. If the delay is <=0, the image will be shown forever otherwise destroyed after delay milliseconds.
cv2.destroyAllWindows() simply destroys all the windows we created.
Special Case: We can create a window first and load the image to it later. Just write the below code line before the cv2.imshow() function.
1 |
cv2.namedWindow('image', cv2.WINDOW_NORMAL) |
Write an image:
To save an image, use the function cv2.imwrite(filename, image) where the first argument is the file name with which we want to save the image file, the second argument is the image you want to save.
1 |
cv2.imwrite('pythongray.jpg',img) |
This will save the image in JPEG format in the working directory.
Now, you might have got some feeling about the basic image commands in OpenCV. Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.