写一个在jupyter notebooks上的基于DWT的图像压缩代码,要求图像为彩色图像,且压缩率为43%
时间: 2024-02-17 18:00:24 浏览: 76
利用DCT以及DWT 对图像进行压缩MATLAB
好的,以下是基于DWT的彩色图像压缩代码,在Jupyter Notebooks上运行:
```python
import pywt
import numpy as np
import cv2
# 读取彩色图像
img = cv2.imread('image.jpg')
# 将图像转换为YCbCr颜色空间
img = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
# 按照YCbCr颜色空间分离出三个通道
Y, Cr, Cb = cv2.split(img)
# 对Y通道进行2级离散小波变换
Y_coeffs = pywt.wavedec2(Y, 'haar', level=2)
# 提取出Y通道的低频分量
Y_cA2, (Y_cH2, Y_cV2, Y_cD2), (Y_cH1, Y_cV1, Y_cD1) = Y_coeffs
# 对低频分量进行量化
Y_cA2_q = np.round(Y_cA2 / 10) * 10
# 将量化后的低频分量与高频分量重新组合,得到压缩后的Y通道
Y_coeffs_q = (Y_cA2_q, (Y_cH2, Y_cV2, Y_cD2), (Y_cH1, Y_cV1, Y_cD1))
Y_q = pywt.waverec2(Y_coeffs_q, 'haar')
# 对Cr和Cb通道分别进行离散小波变换和量化,并得到压缩后的Cr和Cb通道
Cr_coeffs = pywt.wavedec2(Cr, 'haar', level=2)
Cr_coeffs_q = [np.round(coeff / 10) * 10 for coeff in Cr_coeffs]
Cr_q = pywt.waverec2(Cr_coeffs_q, 'haar')
Cb_coeffs = pywt.wavedec2(Cb, 'haar', level=2)
Cb_coeffs_q = [np.round(coeff / 10) * 10 for coeff in Cb_coeffs]
Cb_q = pywt.waverec2(Cb_coeffs_q, 'haar')
# 将压缩后的Y、Cr、Cb通道重新组合为彩色图像
img_q = cv2.merge((Y_q, Cr_q, Cb_q))
# 将压缩后的彩色图像转换为BGR颜色空间
img_q = cv2.cvtColor(img_q, cv2.COLOR_YCrCb2BGR)
# 计算压缩率
size_original = img.shape[0] * img.shape[1] * img.shape[2]
size_compressed = img_q.shape[0] * img_q.shape[1] * img_q.shape[2]
compression_ratio = size_compressed / size_original
# 显示压缩前后的图像
cv2.imshow('Original Image', img)
cv2.imshow('Compressed Image', img_q)
cv2.waitKey(0)
cv2.destroyAllWindows()
print('Compression ratio:', compression_ratio)
```
其中,`image.jpg`为待压缩的彩色图像文件名,压缩率为43%时,我们可以将低频分量量化为10,即将`Y_cA2_q = np.round(Y_cA2 / 10) * 10`改为`Y_cA2_q = np.round(Y_cA2 / 43) * 43`。
阅读全文