Last modified: Jan 15, 2025 By Alexander Williams

Python OpenCV cv2.imwrite() Guide

The cv2.imwrite() function in OpenCV is used to save images to your local storage. It is a crucial tool for image processing tasks. This guide will explain how to use it effectively.

What is cv2.imwrite()?

The cv2.imwrite() function saves an image to a specified file. It takes two main arguments: the file path and the image data. The file format is determined by the file extension.

For example, if you save an image as output.jpg, OpenCV will save it in JPEG format. Similarly, output.png will save it in PNG format.

Syntax of cv2.imwrite()

The syntax of cv2.imwrite() is straightforward. Here is the basic structure:


cv2.imwrite(filename, img)

filename: The path where the image will be saved. Include the file extension.

img: The image data you want to save. This is usually a NumPy array.

Example: Saving an Image with cv2.imwrite()

Let's look at a simple example. First, we read an image using cv2.imread(). Then, we save it using cv2.imwrite().


import cv2

# Read an image
image = cv2.imread('input.jpg')

# Save the image
cv2.imwrite('output.jpg', image)

In this example, the image is read from input.jpg and saved as output.jpg.

Common Use Cases

cv2.imwrite() is often used after processing an image. For example, you might crop an image using Python OpenCV: Crop Image by Coordinates and then save the result.

Another common use case is saving frames from a video. You can capture frames using cv2.VideoCapture() and save them as images.

Handling Errors

If the file path is invalid or the image data is corrupted, cv2.imwrite() will return False. Always check the return value to ensure the image was saved successfully.


success = cv2.imwrite('output.jpg', image)
if not success:
    print("Failed to save image.")

Supported File Formats

OpenCV supports various image formats, including JPEG, PNG, BMP, and TIFF. The format is determined by the file extension. For example, output.png saves the image in PNG format.

If you need to install OpenCV, check out our guide on How to Install OpenCV Python.

Conclusion

The cv2.imwrite() function is essential for saving images in OpenCV. It is simple to use and supports multiple file formats. Whether you're processing images or capturing frames, this function will help you save your work efficiently.

For more information on related functions, check out our guides on Python OpenCV cv2.imread() and Python OpenCV cv2.imshow().