OpenCV (Open Source Computer Vision Library) is a popular library for image processing and computer vision tasks.
Writing images to files is one of the fundamental operations provided by OpenCV.
In this tutorial, we’ll explore how to write images to files using OpenCV.
What You’ll Learn
- Introduction to Writing Images
- Basic Image Writing with cv2.imwrite()
- Writing Images with Different Formats
- Adjusting Image Quality
- Writing Grayscale Images
- Practical Examples
1. Introduction to Writing Images
The function cv2.imwrite() is used to write an image to a file. The syntax is as follows:
cv2.imwrite(filename, image)
- filename: The name of the file where the image will be saved. The format is inferred from the file extension (e.g., .jpg, .png).
- image: The image array to be written.
2. Basic Image Writing with cv2.imwrite()
Example: Writing an Image
import cv2 # Read an image image = cv2.imread("input.jpg") # Write the image to a new file cv2.imwrite("output.jpg", image) print("Image saved successfully!")
3. Writing Images with Different Formats
OpenCV supports several image formats. The format is determined by the file extension in the filename parameter.
Example: Saving as PNG
import cv2 # Read an image image = cv2.imread("input.jpg") # Save as PNG cv2.imwrite("output.png", image) print("Image saved as PNG!")
Example: Saving as BMP
import cv2 # Read an image image = cv2.imread("input.jpg") # Save as BMP cv2.imwrite("output.bmp", image) print("Image saved as BMP!")
4. Adjusting Image Quality
OpenCV allows adjusting image quality when saving images in formats like JPEG and PNG by using optional parameters.
JPEG Quality
The quality of a JPEG image can be set using the [int(cv2.IMWRITE_JPEG_QUALITY), quality] parameter, where quality is a value between 0 and 100 (higher is better).
import cv2 # Read an image image = cv2.imread("input.jpg") # Save with reduced JPEG quality cv2.imwrite("low_quality.jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), 50]) # Save with high JPEG quality cv2.imwrite("high_quality.jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), 95]) print("Images saved with different JPEG quality!")
PNG Compression
The compression level for PNG images can be set using [int(cv2.IMWRITE_PNG_COMPRESSION), compression], where compression ranges from 0 to 9 (lower is better).
import cv2 # Read an image image = cv2.imread("input.jpg") # Save with low compression cv2.imwrite("low_compression.png", image, [int(cv2.IMWRITE_PNG_COMPRESSION), 0]) # Save with high compression cv2.imwrite("high_compression.png", image, [int(cv2.IMWRITE_PNG_COMPRESSION), 9]) print("Images saved with different PNG compression levels!")
5. Writing Grayscale Images
If you want to save a grayscale version of an image, you need to convert the image to grayscale before writing it.
Example: Save Grayscale Image
import cv2 # Read an image image = cv2.imread("input.jpg") # Convert to grayscale gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Save the grayscale image cv2.imwrite("grayscale.jpg", gray_image) print("Grayscale image saved!")
6. Practical Examples
6.1 Save Images from Video Frames
This example demonstrates extracting and saving frames from a video.
import cv2 # Open a video file video = cv2.VideoCapture("video.mp4") frame_count = 0 while True: ret, frame = video.read() if not ret: break # Save every 10th frame if frame_count % 10 == 0: cv2.imwrite(f"frame_{frame_count}.jpg", frame) frame_count += 1 video.release() print("Frames saved successfully!")
6.2 Save an Image with Drawing
This example demonstrates saving an image after adding custom drawings.
import cv2 # Create a blank image image = cv2.imread("input.jpg") # Draw a red rectangle cv2.rectangle(image, (50, 50), (200, 200), (0, 0, 255), 5) # Save the modified image cv2.imwrite("output_with_rectangle.jpg", image) print("Image with drawing saved!")
6.3 Batch Save Images
This example demonstrates saving multiple images in a batch process.
import cv2 import os # Create a list of image filenames image_files = ["image1.jpg", "image2.jpg", "image3.jpg"] # Create an output directory output_dir = "output_images" os.makedirs(output_dir, exist_ok=True) # Process and save each image for image_file in image_files: image = cv2.imread(image_file) output_path = os.path.join(output_dir, os.path.basename(image_file)) cv2.imwrite(output_path, image) print("Batch images saved!")
7. Summary
- Use cv2.imwrite() to save images in various formats.
- Adjust image quality using format-specific parameters (IMWRITE_JPEG_QUALITY, IMWRITE_PNG_COMPRESSION).
- Convert images to grayscale or modify them before saving.
- Combine OpenCV’s functionality to save images from videos or batch process images.
Key Functions Used
- cv2.imread(): Reads an image.
- cv2.imwrite(): Writes an image to a file.
- cv2.cvtColor(): Converts image color spaces (e.g., to grayscale).
By mastering these techniques, you can efficiently handle and save images for a variety of use cases!