OpenCV Tutorial
Image Processing
Feature Detection and Description
Drawing Functions
Video Processing
Applications and Projects
Writing or saving an image in OpenCV using Python is a common operation, especially after you've manipulated or processed the image in some way. The imwrite()
function is used for this purpose. Here's a step-by-step tutorial:
First, if you haven't already, ensure you have OpenCV installed:
pip install opencv-python
import cv2
This step is optional because you might have an image in memory after processing. But for demonstration purposes, we'll load an image:
image = cv2.imread('path_to_input_image.jpg')
You might have done some processing or manipulation on the image. For simplicity, we'll skip this step here, but in a real scenario, you might have operations like resizing, rotation, or any other transformations before saving the image.
Use the imwrite()
function to save the image:
cv2.imwrite('path_to_output_image.jpg', image)
Replace 'path_to_output_image.jpg'
with your desired path and filename. The image format is inferred from the file extension. For instance, you could use .png
or .bmp
as the file extension to save in those formats.
Here's a simple example that loads an image, and then immediately writes it with a new filename:
import cv2 # Load an image image = cv2.imread('path_to_input_image.jpg') # Save the image with a new filename cv2.imwrite('path_to_output_image.jpg', image)
Note: Ensure you have the appropriate permissions to read from the input path and write to the output path on your system.
That's it! The imwrite()
function is all you need to save images using OpenCV in Python. Always ensure that the path and the filename provided to the imwrite()
function are correct, and the directory exists, to avoid potential errors.
Python code for saving images in OpenCV:
import cv2 # Load an image img = cv2.imread('image.jpg') # Save the image cv2.imwrite('saved_image.jpg', img)
Saving images to different file formats with OpenCV:
import cv2 # Load an image img = cv2.imread('image.jpg') # Save the image in PNG format cv2.imwrite('saved_image.png', img)
Image encoding and compression in OpenCV:
import cv2 # Load an image img = cv2.imread('image.jpg') # Specify compression parameters (0-9, higher means smaller file size) compression_params = [cv2.IMWRITE_JPEG_QUALITY, 90] # Save the image with compression cv2.imwrite('compressed_image.jpg', img, compression_params)
Writing images with specified file names in OpenCV:
import cv2 # Load an image img = cv2.imread('image.jpg') # Specify the output file name output_file = 'output_image.jpg' # Save the image with the specified file name cv2.imwrite(output_file, img)
Real-time image saving with OpenCV:
import cv2 # Open the camera cap = cv2.VideoCapture(0) while True: # Read a frame from the camera ret, frame = cap.read() # Display and save the real-time frame cv2.imshow('Real-time Image Saving', frame) cv2.imwrite('real_time_frame.jpg', frame) # Break the loop on 'Esc' key press if cv2.waitKey(1) & 0xFF == 27: break # Release the camera and close the window cap.release() cv2.destroyAllWindows()
Saving images in different color spaces with OpenCV:
import cv2 # Load an image img = cv2.imread('image.jpg') # Convert BGR to grayscale grayscale_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Save the grayscale image cv2.imwrite('grayscale_image.jpg', grayscale_img)
Image quality parameters for saving in OpenCV:
import cv2 # Load an image img = cv2.imread('image.jpg') # Specify quality parameters for JPEG compression compression_params = [cv2.IMWRITE_JPEG_QUALITY, 90] # Save the image with specified quality cv2.imwrite('high_quality_image.jpg', img, compression_params)
Handling image file paths in OpenCV:
import cv2 import os # Load an image img = cv2.imread('image.jpg') # Specify the output directory output_dir = 'output_images' # Ensure the output directory exists os.makedirs(output_dir, exist_ok=True) # Construct the output file path output_file = os.path.join(output_dir, 'saved_image.jpg') # Save the image with the specified file path cv2.imwrite(output_file, img)
Writing images with matplotlib and OpenCV in Python:
import cv2 from matplotlib import pyplot as plt # Load an image img = cv2.imread('image.jpg') # Convert BGR to RGB for matplotlib img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Display the image using matplotlib and save it plt.imshow(img_rgb) plt.axis('off') plt.savefig('matplotlib_saved_image.jpg')
Saving images with adjustable resolution and quality in OpenCV:
import cv2 # Load an image img = cv2.imread('image.jpg') # Resize the image resized_img = cv2.resize(img, (800, 600)) # Specify compression parameters (0-9, higher means smaller file size) compression_params = [cv2.IMWRITE_JPEG_QUALITY, 90] # Save the resized and compressed image cv2.imwrite('resized_image.jpg', resized_img, compression_params)
Batch processing and saving multiple images with OpenCV:
import cv2 import os # Specify the input directory containing multiple images input_dir = 'input_images' # Specify the output directory for saving processed images output_dir = 'output_images' # Ensure the output directory exists os.makedirs(output_dir, exist_ok=True) # Process and save each image in the input directory for filename in os.listdir(input_dir): if filename.endswith('.jpg'): # Load an image img = cv2.imread(os.path.join(input_dir, filename)) # Process the image (e.g., resize, color space conversion) # Save the processed image to the output directory output_file = os.path.join(output_dir, f'processed_{filename}') cv2.imwrite(output_file, img)
Code examples for efficient image writing in OpenCV:
import cv2 import numpy as np # Create a sample image img = np.zeros((300, 400, 3), dtype=np.uint8) img[:, :, 0] = 255 # Blue channel # Specify compression parameters (0-9, higher means smaller file size) compression_params = [cv2.IMWRITE_JPEG_QUALITY, 90] # Save the image with efficient writing cv2.imencode('.jpg', img, compression_params)