Save JPEG With Specific Quality | OpenCV vs Pillow | Python

This tutorial will show you how to write/save images in jpg format and specify the image quality in both OpenCV (cv2) and Pillow (PIL).

Specify JPEG Quality

The recommended range for image quality is from 1 (worst) to 95 (best). Values above 95 should be avoided since 100 will disable portions of the JPEG compression algorithm, and result in large files without better image quality.

# Pillow
pil_img.save("new_image.jpg", quality=95)

# OpenCV
cv2.imwrite("new_image.jpg", cv2_img, [cv2.IMWRITE_JPEG_QUALITY, 95])

If the JPEG quality is not specified, they will save the image in the following default quality:

Pillow (PIL)OpenCV (cv2)
Default JPEG Quality7595

Full Example

You might also want to learn how to read images using cv2 and PIL.

Pillow

from PIL import Image

# read images
pil_img = Image.open("test_images/test1.jpg")

# write jpeg with quality=50
pil_img.save("test_images/pil_compressed_image.jpg", quality=50)

OpenCV

import cv2

# read images
cv2_img = cv2.imread("test_images/test1.jpg")

# write jpeg with quality=50
cv2.imwrite("test_images/cv2_compressed_image.jpg", cv2_img, [cv2.IMWRITE_JPEG_QUALITY, 50])

Syntax

Pillow

Image.save(fp, format=None, **params)

Parameters:

  • fp: A filename (string), pathlib.Path object or file object.
  • format: Optional format override. If omitted, the format to use is determined from the filename extension. This parameter should always be used if a file object is used instead of a filename.
  • params: Extra parameters to the image writer. See the documentation for available options for each writer.

Returns:

  • None

OpenCV

cv2.imwrite(filename, img[, params])

Parameters:

  • filename: Name of the file.
  • img: Image or Images to be saved (Numpy array).
  • params: Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, … .) see cv::ImwriteFlags.

Returns:

  • True if succeeded, Otherwise False.

References

Avatar photo
Steins

Developer & AI Researcher. Write about AI, web dev/hack.