In this OpenCV tutorial, we will learn how to save an image object to a file in Python using imwrite() function. We go through an example of applying transformations to an image object, and saving the image.

OpenCV Python – Save Image

While working with images in Image Processing applications, quite often, you may need to store intermediate results of image transformations or save the final resulting image. When working with OpenCV Python, images are stored in NumPy ndarray.

To save an image to the local file system, use cv2.imwrite() function of OpenCV python library.

Syntax of cv2.imwrite()

The syntax of cv2.imwrite() function is

cv2.imwrite('/path/to/destination/image.png',image)

where

  • First Argument is Path to the destination on file system, where image is ought to be saved.
  • Second Argument is ndarray containing image
  • Returns True is returned if the image is written to file system, else False.
ADVERTISEMENT

Example

In this example, we will read an image, then transform it to grey image and save this image data to local file.

write-image.py

import cv2

# read image as grey scale
grey_img = cv2.imread('/home/img/python.png', cv2.IMREAD_GRAYSCALE)

# save image
status = cv2.imwrite('/home/img/python_grey.png',grey_img)

print("Image written to file-system : ",status)

Run the above python script.

Image written to file-system :  True

cv2.imwrite() returned true which means the file has been successfully written to the path specified. Reading the return value of imwrite() is very important as sometimes there could be multiple reasons that fail the disk write operation and resulting in the image not written to disk.

Let us manually check if the image is saved.

arjun@localhost:/home/img$ ls python*
python_grey.png  python.png

Conclusion

Concluding this OpenCV Python Tutorial, we have successfully saved the image with specified name using cv2.imwrite() function.