Instagram
youtube
Facebook
Twitter

Read and Save Images

With the help of OpenCV, we can perform various operations on images. But, the most important operations are reading and saving images. In this tutorial, we will learn how to read and save images with OpenCV in python.

Reading an image with OpenCV

To read an image with OpenCV in Python, you can use the cv2.imread() function. This function takes a string specifying the file path of the image and returns an image.

The image file should be in the same directory as your Python script, or you should specify the full path to the file.

import cv2
image = cv2.imread(r'C:\Users\rohit\OneDrive\Pictures\Saved Pictures\header-background.png',1)
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, first we imported cv2 and then we used cv2.imread to read the image of the given path. Then we used  cv2.imshow to display the image. After this, we used cv2.waitkey(0) to wait for a keypress to close the image. At last, we used cv2.destroyAllWindows() to destroy all windows.

Output:


Saving an image with OpenCV

To save an image with OpenCV in Python, you can use the cv2.imwrite() function. This function takes a file path and an image and saves the image to the desktop.

import cv2
image = cv2.imread(r'C:\Users\rohit\OneDrive\Pictures\Saved Pictures\header-background.png',1)

img_status = cv2.imwrite('opencv.jpg', image)
print("Image is successfully saved: ", img_status)

Here, first we imported cv2 and then we used cv2.imread to read the image of the given path. Then we used cv2.imwrite to save the image as ‘opencv.jpg and declared it as img_status. At last, we printed the img_status as a boolean. 

Output:

Image is successfully saved:  True