Why does openCV store a file larger(kB) than the original?

元气小坏坏 提交于 2021-02-10 14:13:13

问题


I have code that loads and saves the image in two different ways - first using openCV, the second using PIL.

import cv2
from PIL import Image

img = cv2.imread("/home/myname/png/image.png")
cv2.imwrite("/home/myname/png/image_save.png", img)

img = Image.open("/home/myname/png/image.png")
img.save("/home/myname/png/image_save_pil.png")

The original image is 204.6 kB in size. The result obtained with openCV is 245.0 kB, the result of PIL is 204.6 kB.

Why does the image saved with openCV have a larger size?


回答1:


The size difference has to do with the ZLIB compression settings.

  • By default PIL uses the maximum 9 (see here)
  • By default OpenCV only uses 3 (see here)

Using OpenCV you can set compression to 9 using this code (from this answer)

cv2.imwrite('image.png', img,  [int(cv2.IMWRITE_PNG_COMPRESSION), 9])



回答2:


You cannot expect two PNGs to have the same size if they were produced by different libraries.

File specifications define the structure of a file so everyone knows where to write information and where to find it. How to encode and how to decode data...

Many things are optional, like metadata, compression rates, ...

It's like raising identical twins in two different families.

You can try to set the same parameters to image writing functions, but even then it is unlikely that you get exact same file size.



来源:https://stackoverflow.com/questions/47327641/why-does-opencv-store-a-file-largerkb-than-the-original

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!