Python OpenCV cv2.imwrite() – Save Image

Python OpenCV cv2.imwrite()

In our previous tutorial – cv2 imread(), we learned to read an image into a matrix. You may transform this matrix by using some algorithms. Then it may be required to save this matrix as an image.

In this tutorial, we will learn how to save an array as image in file system.

To save image to local storage using Python, use cv2.imwrite() function on OpenCV library.

Syntax of cv2 imwrite()

The syntax of imwrite() function is:

cv2.imwrite(path, image)

where path is the complete path of the output file to which you would like to write the image numpy array.

cv2.imwrite() returns a boolean value. True if the image is successfully written and False if the image is not written successfully to the local path specified.

Example 1: Save Matrix as Image – cv2 imwrite()

In this example, we will read an image, transform it and then save the image to persistent file storage using imwrite() method.

Python Program

import cv2

#read image as grey scale
img = cv2.imread('D:/image-1.png')

#do some transformations on img

#save matrix/array as image file
isWritten = cv2.imwrite('D:/image-2.png', img)

if isWritten:
	print('Image is successfully saved as file.')

Output

Image is successfully saved as file.

Example 2: Save Image using cv2 imwrite() – with Random Values

In this example, we will write a numpy array as image using cv2.imwrite() function. For that, we will create a numpy array with three channels for Red, Green and Blue containing random values. In general cases, we read image using cv2.imread(), apply some transformations on the array and then write the image to the local storage. But in this example, we will stick to the array with random values.

Python Program

import cv2
import numpy as np

img = np.random.randint(255, size=(300, 600, 3))

isWritten = cv2.imwrite('D:/image-2.png', img)

if isWritten:
	print('The image is successfully saved.')

Output

The image is successfully saved.

Following is the image that is generated with the random values.

Python OpenCV cv2 imwrite() Example

Summary

In this tutorial of Python Examples, we learned how to use cv2.imwrite() to save numpy array as an image.