python cv2圖像質量壓縮的算法示例

使用opencv對圖像進行編碼,一方面是圖像二進制傳輸的需要,另一方面對圖像壓縮。以jpeg壓縮為例:

1、轉為二進制編碼

img = cv2.imread(img_path)
# 取值范圍:0~100,數值越小,壓縮比越高,圖片質量損失越嚴重
params = [cv2.IMWRITE_JPEG_QUALITY, ratio]  # ratio:0~100
msg = cv2.imencode(".jpg", img, params)[1]
msg = (np.array(msg)).tobytes()
print("msg:", len(msg))

對於png壓縮,改為:

# 取值范圍:0~9,數值越小,壓縮比越低,圖片質量越高
params = [cv2.IMWRITE_PNG_COMPRESSION, ratio]  # ratio: 0~9
msg = cv2.imencode(".png", img, params)[1]
msg = (np.array(msg)).tobytes()

對於圖像解碼,使用imdecode即可解為numpy類型圖像:

img = cv2.imdecode(np.frombuffer(msg, np.uint8), cv2.IMREAD_COLOR)
print(img.shape, type(img))

2、圖像質量壓縮

原圖(48k):

jpg壓縮:

img_path = r"E:\img.jpg"
img = cv2.imread(img_path)
cv2.imwrite(r"E:\ret_80.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 80])
cv2.imwrite(r"E:\ret_40.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 40])
cv2.imwrite(r"E:\ret_10.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 10])
cv2.imwrite(r"E:\ret_0.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 0])

結果:

壓縮後圖像大小依次為:49.6K、25.6K、11K、5.02K。jpg壓縮明顯,壓縮到極致時顏色信息損失嚴重。

png壓縮:

img_path = r"E:\img.jpg"
img = cv2.imread(img_path)
cv2.imwrite(r"E:\ret_0.png", img, [cv2.IMWRITE_PNG_COMPRESSION, 0])
cv2.imwrite(r"E:\ret_3.png", img, [cv2.IMWRITE_PNG_COMPRESSION, 3])
cv2.imwrite(r"E:\ret_6.png", img, [cv2.IMWRITE_PNG_COMPRESSION, 6])
cv2.imwrite(r"E:\ret_9.png", img, [cv2.IMWRITE_PNG_COMPRESSION, 9])

結果:

壓縮後圖像大小依次為:675K、364K、364K、360K。png格式偏大,壓縮率調到最高也還有360K,且成像上無明顯變化。

PS:也可以對圖像壓縮後保存,如:

img_path = r"E:\img.jpg"
img = cv2.imread(img_path)
params = [cv2.IMWRITE_PNG_COMPRESSION, 0]
msg = cv2.imencode(".png", img, params)[1]
msg = (np.array(msg)).tobytes()
print("msg:", len(msg))
img = cv2.imdecode(np.frombuffer(msg, np.uint8), cv2.IMREAD_COLOR)
cv2.imwrite(rr"E:\ret.jpg", img)

bug處理:

早期版本這樣寫:

msg = (np.array(msg)).tostring()
改為:
msg = (np.array(msg)).tobytes()
 
img = cv2.imdecode(np.fromstring(msg, np.uint8), cv2.IMREAD_COLOR)
改為:
img = cv2.imdecode(np.frombuffer(msg, np.uint8), cv2.IMREAD_COLOR)

到此這篇關於python cv2圖像質量壓縮的算法示例的文章就介紹到這瞭,更多相關python cv2圖像質量壓縮 內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: