0
0
Computer-visionHow-ToBeginner ยท 3 min read

How to Save Image Using OpenCV in Computer Vision

To save an image using OpenCV, use the function cv2.imwrite(filename, image), where filename is the path to save the image and image is the image data. This function writes the image to disk in the specified format based on the file extension.
๐Ÿ“

Syntax

The basic syntax to save an image with OpenCV is:

  • cv2.imwrite(filename, image)

Here:

  • filename: A string specifying the path and name of the file to save (e.g., 'output.jpg'). The file extension determines the image format.
  • image: The image data (usually a NumPy array) you want to save.
python
cv2.imwrite(filename, image)
๐Ÿ’ป

Example

This example loads an image, converts it to grayscale, and saves the new image to disk.

python
import cv2

# Load an image from file
image = cv2.imread('input.jpg')

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

# Save the grayscale image
success = cv2.imwrite('output_gray.jpg', gray_image)

print('Image saved:', success)
Output
Image saved: True
โš ๏ธ

Common Pitfalls

Common mistakes when saving images with OpenCV include:

  • Using an incorrect file path or filename, causing the save to fail silently.
  • Passing an empty or invalid image array to cv2.imwrite.
  • Not checking the return value of cv2.imwrite, which indicates if saving succeeded.
  • Using unsupported file extensions or formats.

Always verify the image is loaded or processed correctly before saving.

python
import cv2

# Wrong: Saving without checking if image loaded
image = cv2.imread('nonexistent.jpg')  # This returns None if file not found
cv2.imwrite('output.jpg', image)  # This will fail silently

# Right: Check if image is loaded before saving
if image is not None:
    saved = cv2.imwrite('output.jpg', image)
    print('Saved:', saved)
else:
    print('Image not loaded, cannot save.')
Output
Image not loaded, cannot save.
๐Ÿ“Š

Quick Reference

FunctionDescription
cv2.imwrite(filename, image)Save image to disk with given filename and format
cv2.imread(filename)Load image from disk
cv2.cvtColor(image, flag)Convert image color space (e.g., BGR to grayscale)
โœ…

Key Takeaways

Use cv2.imwrite(filename, image) to save images in OpenCV.
The file extension in filename decides the image format saved.
Always check if the image is valid before saving to avoid errors.
Check the return value of cv2.imwrite to confirm the save was successful.
Use supported image formats like .jpg, .png, or .bmp for saving.