OpenCV Python – Save Image

In this tutorial, we will learn how to save image data from ndarray to a file, in OpenCV Python using imwrite() function, with an example.

While working with images in Image Processing applications, it is quite often that you 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 – 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.

Example 1 – OpenCV cv2.imwrite()

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.