OpenCV:压缩后图像大小增加

OpenCV: Image size increases after compressed

我正在尝试使用 OpenCV 的 quality=90 参数比较压缩前后一堆图像的大小。但在压缩之前,我想将它们全部裁剪成固定大小。但是,我不明白为什么裁剪后的图像平均尺寸比裁剪+压缩后的小?

这是我正在做的事情:

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

我错过了什么?

首先,您正在使用 PIL.save() 保存作物。正如您在 documentation 上看到的,默认 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.

  • ...

然后,你用cv2.imwrite()传递quality=90。因此,您得到的是预期的行为。