【Opencv中的Jpeg有损压缩】
Opencv中的Jpeg有损压缩
import cv2
import numpy as np
def compress_and_decompress_image(image_path, quality=75):
# 读取图像
image = cv2.imread(image_path)
if image is None:
print("图像读取失败!")
return None
# 使用 imencode 函数进行 JPEG 编码
success, encoded_image = cv2.imencode('.jpg', image, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
if not success:
print("图像编码失败!")
return None
print(f"图像已成功编码为 JPEG 格式,压缩后的数据大小为: {len(encoded_image)} 字节")
# 使用 imdecode 函数将编码后的数据解码为图像
decoded_image = cv2.imdecode(encoded_image, cv2.IMREAD_COLOR)
if decoded_image is None:
print("图像解码失败!")
return None
print("图像已成功解码为正常格式。")
return decoded_image
# 示例用法
image_path = 'test3.png' # 替换为你的图像路径
decompressed_image = compress_and_decompress_image(image_path, quality=55)
# 显示原始图像和解码后的图像(仅作为示例)
if decompressed_image is not None:
original_image = cv2.imread(image_path) # 重新读取原始图像以进行比较
cv2.imshow('Original Image', original_image)
cv2.imshow('Decompressed Image', decompressed_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# # 如果需要,可以将压缩后的数据写入到文件(仅作为示例,实际不需要保存)
# if compressed_data is not None:
# with open('compressed_image.jpg', 'wb') as f:
# f.write(compressed_data.tobytes()) # 实际上不需要这一步,仅用于演示