Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Saving an Image
After processing an image you will often want to save the result to disk. OpenCV's cv2.imwrite() handles this for all common image formats.
cv2.imwrite()
cv2.imwrite(filename, image) saves an image to disk.
The file format is determined automatically from the file extension:
- .jpg or .jpeg — JPEG (lossy compression, smaller files)
- .png — PNG (lossless, larger files, supports transparency)
- .bmp — BMP (uncompressed, very large)
- .tiff — TIFF (lossless, used in scientific imaging)
cv2.imwrite() returns True if the save was successful, False if it failed. Always check the return value.
Machine Learning follows a structured pipeline from data to deployment
Saving with Quality Control
import cv2
import numpy as np
image = cv2.imread("photo.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Save as PNG (lossless)
success = cv2.imwrite("output.png", image)
print("PNG saved:", success)
# Save as JPEG with quality control
# Quality: 0 (worst/smallest) to 100 (best/largest), default 95
success = cv2.imwrite("output_hq.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 95])
success = cv2.imwrite("output_lq.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 50])
print("JPEG files saved")
# Save a grayscale image
cv2.imwrite("gray_output.png", gray)
print("Grayscale saved")
# Save PNG with compression level (0=no compression, 9=max compression)
cv2.imwrite("compressed.png", image, [cv2.IMWRITE_PNG_COMPRESSION, 9])
print("Compressed PNG saved")
# Verify the saved file by loading it back
loaded = cv2.imread("output.png")
print(f"Verification — saved shape: {loaded.shape}")