What is the "cv2.imwrite()" function?

cv.imwrite() is a function provided by the OpenCV library and is used for saving an image to a file in various formats, such as .jpg, .png, .bpm, etc.

Syntax

The syntax for this function is as follows:

cv2.imwrite(filename, image)

Parameters

  • filename: It specifies the file name to which the image will be saved. The file extension determines the format of the image. For example, if the filename is output.jpg, it will keep the image in jpeg format. The file path can also be included here if you do not want to save it in the current directory.

  • image is a numpy array of the image data that you want to save.

Return value

cv2.imwrite() returns True if the image is successfully saved. Otherwise, it returns False.

Example

import cv2

# Read an image from file
my_image = cv2.imread('image.jpg')

# Convert the image to grayscale
gray_image = cv2.cvtColor(my_image, cv2.COLOR_BGR2GRAY)

#Saving the image
save_image = cv2.imwrite('gray.jpg',gray_image)

# Save the grayscale image
if (save_image):
    print("Image saved successfully")
else:
    print("Image is not saved")

# Displaying both image
cv2.imshow('Original Image', my_image)
cv2.imshow('Gray Image',gray_image)
cv2.waitKey(0)
Pyhton code to save a grayscaled version of a colored image

Note: You can drag the image windows in the output section to have a better comparison.

Code explanation

  • Line 1: Imports cv2 library.

  • Line 4: Loads the colored image named image.jpg and stores it in my_image variable.

  • Line 7: Graycales the image and saves it in the gray_image variable.

  • Line 10: Uses cv2.imwrite() function to save the grayscaled image with the name gray.jpg in the current directory. You can also provide a path to another directory to save the image elsewhere. If the image saves successfully, then the save_image variable will have True in it. Otherwise, it will have False.

  • Lines 13–16: Depending upon the boolean value in save_image, the relevant message gets printed on the screen.

  • Lines 19–20: Displaying both images for your reference.

  • Line 21: Waits for the user to press any key if they want to close the windows.

Note: If the file with the given name already exits, cv2.imwrite() will overwrite that existing file.

Continue reading

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved