python - OpenCV:压缩后图像大小增加

标签 python opencv python-imaging-library image-compression

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

这是我正在做的:

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
  • 预计:compressed_imgs_size < copped_imgs_size
  • 实际:compressed_imgs_size > copped_imgs_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。因此,您得到的是预期的行为。

关于python - OpenCV:压缩后图像大小增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57158279/

相关文章:

ajax - 在 Django 中使用 fileReader.readAsDataURL 通过 Ajax 传输图像并在 PIL 中打开

python - 如何在 Eclipse for Python 中设置远程开发? ( "remote"部分)

python - Spark MLLIB LDA 主题矩阵的输出是什么?

python - 在 Python 中延迟转置列表

java - OpenCV - 安卓 : java. lang.IllegalArgumentException: bmp == null

c++ - Opencv cv::waitKey() 返回值

python - 我如何要求此 Django View 使用 HTTPS?

android - 在 Android OpenCV 中设置关键点数

python - Django - 如何安装 Python 图像库 (PIL)

python - 如何根据背景图片规范添加水印对角限制高度和宽度而不损失标志质量?