使用opencv對圖像進(jìn)行編碼,一方面是圖像二進(jìn)制傳輸?shù)男枰?,另一方面對圖像壓縮。以jpeg壓縮為例:
1、轉(zhuǎn)為二進(jìn)制編碼
img = cv2.imread(img_path)
# 取值范圍:0~100,數(shù)值越小,壓縮比越高,圖片質(zhì)量損失越嚴(yán)重
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,數(shù)值越小,壓縮比越低,圖片質(zhì)量越高
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、圖像質(zhì)量壓縮
原圖(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])
結(jié)果:
壓縮后圖像大小依次為:49.6K、25.6K、11K、5.02K。jpg壓縮明顯,壓縮到極致時顏色信息損失嚴(yán)重。
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])
結(jié)果:
壓縮后圖像大小依次為:675K、364K、364K、360K。png格式偏大,壓縮率調(diào)到最高也還有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)
到此這篇關(guān)于python cv2圖像質(zhì)量壓縮的算法示例的文章就介紹到這了,更多相關(guān)python cv2圖像質(zhì)量壓縮 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 在Python中使用K-Means聚類和PCA主成分分析進(jìn)行圖像壓縮
- python SVD壓縮圖像的實現(xiàn)代碼
- Python基于opencv的圖像壓縮算法實例分析
- python使用pil進(jìn)行圖像處理(等比例壓縮、裁剪)實例代碼