python cv2图像质量压缩

目录

1、转为二进制编码

2、图像质量压缩


        使用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):

python cv2图像质量压缩_第1张图片

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])

结果:

python cv2图像质量压缩_第2张图片

        压缩后图像大小依次为: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])

结果:

python cv2图像质量压缩_第3张图片

        压缩后图像大小依次为: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,图像识别,opencv,计算机视觉,图像压缩,图像编码)