2

For some reason, on my Ubuntu 20.04 machine when I use OpenCV in Python like:

cv2.imwrite("myfile.webp", cv2image)

in my code, the file of 800x600 px has about 300 KiB while if I do:

cv2.imwrite("myfile.jpg", cv2image)

the output file of the same pixel size has about 100 KiB.

Why is that, if webp should have 25% less in size than jpg?

Or do I have to set some options first?

P.S. for png:

cv2.imwrite("myfile.png", cv2image)

the size is about 500 KiB.

kipkipe
  • 121
  • 2
  • 4

2 Answers2

2

Webp has 2 forms of saving data. Lossy (what JPEG does) where information get lost to reduce data, and lossless (what png does) with no data loss.

By default opencv uses its cv2.IMWRITE_WEBP_QUALITY to determin the quality. If this is set at 100 it means no compression (lossless)

https://docs.opencv.org/master/d8/d6a/group__imgcodecs__flags.html#gga292d81be8d76901bff7988d18d2b42aca7d3f848cc45d3138de0a2053d213a54a

Tom Nijhof
  • 542
  • 4
  • 11
  • Thanks, any idea how to change it in Python? – kipkipe Aug 13 '21 at 07:43
  • You can just overwrite it by cv2.IMWRITE_WEBP_QUALITY=80 This overwrites the it for all webp operations – Tom Nijhof Aug 13 '21 at 07:51
  • 1
    Hmm, no effect at all, It's still around 300 kB no matter if it is 80 or 20. I put the line before the imwrite line and it is not working. – kipkipe Aug 13 '21 at 07:55
  • I don't know if opencv is a requirement for you, but pillow has also the function: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#webp – Tom Nijhof Aug 13 '21 at 07:58
  • 1
    SOLVED! It should be like this to work: `cv2.imwrite("myfile.webp", cv2image, [int(cv2.IMWRITE_WEBP_QUALITY), 20])` Now, the file has 4 kB ;D – kipkipe Aug 13 '21 at 07:58
2

SOLVED! It should be like this to work:

cv2.imwrite("myfile.webp", cv2image, [int(cv2.IMWRITE_WEBP_QUALITY), 20])

Now, the file has 4 kB ;D

kipkipe
  • 121
  • 2
  • 4