OpenCV Tutorial
Image Processing
Feature Detection and Description
Drawing Functions
Video Processing
Applications and Projects
Saving or writing an image to a file is a basic operation in OpenCV. You might want to save the output after performing some operation on an image, or simply save the frame captured from a webcam. Here's a simple tutorial on how to save an image using OpenCV.
pip install opencv-python
import cv2
image = cv2.imread('path_to_input_image.jpg')
imwrite
function. The function requires two arguments: the filename (including the desired file extension) and the image object.cv2.imwrite('path_to_output_image.jpg', image)
File Format: OpenCV supports various file formats including .jpg
, .png
, .bmp
, etc. The format is inferred from the file extension you provide. For instance, if you want to save as a PNG, you'd use 'output_image.png' as the filename.
JPEG Quality: For JPEG images, you can specify the quality of the output image by adding an additional argument:
cv2.imwrite('path_to_output_image.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 90])
Here, 90
is the quality level, which can range from 0 to 100 (default is 95). Lower numbers will result in higher compression and lower file sizes, but with a potential reduction in image quality.
cv2.imwrite('path_to_output_image.png', image, [cv2.IMWRITE_PNG_COMPRESSION, 4])
Here, 4
is the compression level which can range from 0 (no compression) to 9. Higher values will produce smaller files but will take more time to write.
Saving an image in OpenCV is straightforward using the imwrite
function. By understanding the additional parameters, you can optimize the balance between output image quality and file size according to your needs.
Save image with OpenCV in Python:
imwrite
function.import cv2 # Read an image image = cv2.imread('input_image.jpg') # Save the image cv2.imwrite('output_image.jpg', image)
Save image in different formats with OpenCV:
# Save as JPEG cv2.imwrite('output_image.jpg', image, [int(cv2.IMWRITE_JPEG_QUALITY), 90]) # Save as PNG cv2.imwrite('output_image.png', image, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
OpenCV save image to specific directory:
import os output_dir = 'output_images' # Create the directory if it doesn't exist os.makedirs(output_dir, exist_ok=True) # Save the image to the specified directory cv2.imwrite(os.path.join(output_dir, 'output_image.jpg'), image)
OpenCV save image with custom filename:
custom_filename = 'custom_output.jpg' cv2.imwrite(custom_filename, image)
Save image with OpenCV and matplotlib:
import matplotlib.pyplot as plt # Display the image using matplotlib plt.imshow(image) plt.savefig('matplotlib_output.png')