如何在 python 中使用 opencv 压缩 png 文件?

How to compress png file with opencv in python?

我试过这段代码:

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

但是我得到这个错误:

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

我正在使用 python 3.5 和 opencv 3.0

OpenCV 3.0 中的名称是 IMWRITE_PNG_COMPRESSION(没有 CV_ 前缀)。

所以尝试:

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

This post提到也投到int。我不确定这是否仍然需要:

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