14

I tried this code:

compression_params = [cv2.CV_IMWRITE_PNG_COMPRESSION, 9] 
img = cv2.imread('img1.png', cv2.IMREAD_UNCHANGED) 
cv2.imwrite('compress_img1.png', img, compression_params)

But I obtain this error:

AttributeError: module 'cv2' has no attribute 'CV_IMWRITE_PNG_COMPRESSION'

I'm working with python 3.5 and opencv 3.0

Miki
  • 40,887
  • 13
  • 123
  • 202
A. Sarmiento
  • 145
  • 1
  • 1
  • 5

1 Answers1

43

The name in OpenCV 3.0 is IMWRITE_PNG_COMPRESSION (without the CV_ prefix).

So try:

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

This post mentions also to cast to int. I'm not sure if this is still needed:

cv2.imwrite('compress_img1.png', img,  [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
Community
  • 1
  • 1
Miki
  • 40,887
  • 13
  • 123
  • 202
  • Both ones worked, didn't see any difference. Maybe on some systems the IMWRITE_PNG_COMPRESSION would be a float, then the int() would be needed – WoodyDRN Mar 09 '18 at 18:07
  • 1
    @WoodyDRN The PNG format is lossless so the resulting image is always exactly the same. The only difference is processing speed (0 being the fastest). – RobbertC5 Nov 15 '19 at 09:31
  • WARNING! Do not use option 9! It was almost 20x slower for me in HR images, it took me a while to figure out there were other faster settings. Check level "0". – Rafael Toledo May 18 '23 at 21:16