Denis
Denis

Reputation: 261

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

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?

Upvotes: 1

Views: 2186

Answers (2)

zeFrenchy
zeFrenchy

Reputation: 6591

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])

Upvotes: 4

Piglet
Piglet

Reputation: 28950

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.

Upvotes: 0

Related Questions