简体   繁体   中英

OpenCV: Image size increases after compressed

I am trying to compare the size of a bunch of images before and after compression using the quality=90 argument of OpenCV. But before compression, I want to crop all of them to a fixed size. I don't understand, however, why the average size of images after crop is smaller than after crop+compression?

Here is what I'm doing:

import cv2
import PIL
from pathlib import Path

image_paths = [...]

cropped_imgs_size = 0
compressed_imgs_size = 0

# crop images
for orig_img_path in image_paths:
    cropped_img_path = "cropped_" + orig_img_path
    PIL.Image.open(orig_img_path).crop((0,0,256,256)).convert('RGB').save(cropped_img_path)
    cropped_imgs_size += Path(cropped_img_path).stat().st_size

    # compress cropped image
    dest_path = "q90_" + cropped_img_path
    cv2.imwrite(dest_path, cv2.imread(cropped_img_path), [int(cv2.IMWRITE_JPEG_QUALITY), 90])
    compressed_imgs_size += Path(dest_path).stat().st_size
  • Expected: compressed_imgs_size < copped_imgs_size
  • Actual: compressed_imgs_size > copped_imgs_size

What am I missing?

First, you are saving the crop using PIL.save() . As you can see on the documentation , the default quality=75 :

The save() method supports the following options:

  • quality : the image quality, on a scale from 1 (worst) to 95 (best). The default is 75 . Values above 95 should be avoided; 100 disables portions of the JPEG compression algorithm, and results in large files with hardly any gain in image quality.

  • ...

Then, you use cv2.imwrite() passing quality=90 . Therefore, what you get is the expected behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM