我正在尝试使用 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/