Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress png file with opencv in python?

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

like image 655
A. Sarmiento Avatar asked Oct 13 '16 17:10

A. Sarmiento


1 Answers

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])
like image 166
Miki Avatar answered Oct 13 '22 04:10

Miki