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 thefilenameisoutput.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.imageis 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)Note: You can drag the image windows in the output section to have a better comparison.
Code explanation
Line 1: Imports
cv2library.Line 4: Loads the colored image named
image.jpgand stores it inmy_imagevariable.Line 7: Graycales the image and saves it in the
gray_imagevariable.Line 10: Uses
cv2.imwrite()function to save the grayscaled image with the namegray.jpgin the current directory. You can also provide a path to another directory to save the image elsewhere. If the image saves successfully, then thesave_imagevariable will haveTruein it. Otherwise, it will haveFalse.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