写一个在jupyter notebooks上对一个具有整数像素值的彩色图像基于DWT图像压缩的代码,并能计算压缩率
时间: 2024-02-17 14:03:11 浏览: 85
以下是一个基于PyWavelets库实现DWT图像压缩的代码,可以在jupyter notebooks上运行。代码中使用了haar小波作为变换基,使用了能量阈值法进行压缩,最终输出压缩后的图像和压缩率。
```python
import pywt
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
# 加载图像
img = io.imread('image.jpg')
# 将图像拆分成RGB通道
r = img[:,:,0]
g = img[:,:,1]
b = img[:,:,2]
# 定义小波变换基
wavelet = 'haar'
# 定义能量阈值
threshold = 0.1
# 对每个通道进行小波变换
cA_r, (cH_r, cV_r, cD_r) = pywt.dwt2(r, wavelet)
cA_g, (cH_g, cV_g, cD_g) = pywt.dwt2(g, wavelet)
cA_b, (cH_b, cV_b, cD_b) = pywt.dwt2(b, wavelet)
# 对每个通道进行能量阈值压缩
cH_r[np.abs(cH_r) < threshold] = 0
cV_r[np.abs(cV_r) < threshold] = 0
cD_r[np.abs(cD_r) < threshold] = 0
cH_g[np.abs(cH_g) < threshold] = 0
cV_g[np.abs(cV_g) < threshold] = 0
cD_g[np.abs(cD_g) < threshold] = 0
cH_b[np.abs(cH_b) < threshold] = 0
cV_b[np.abs(cV_b) < threshold] = 0
cD_b[np.abs(cD_b) < threshold] = 0
# 对每个通道进行小波反变换
r_compressed = pywt.idwt2((cA_r, (cH_r, cV_r, cD_r)), wavelet)
g_compressed = pywt.idwt2((cA_g, (cH_g, cV_g, cD_g)), wavelet)
b_compressed = pywt.idwt2((cA_b, (cH_b, cV_b, cD_b)), wavelet)
# 合并三个通道
compressed_img = np.zeros(img.shape)
compressed_img[:,:,0] = r_compressed
compressed_img[:,:,1] = g_compressed
compressed_img[:,:,2] = b_compressed
# 计算压缩率
original_size = img.shape[0] * img.shape[1] * img.shape[2]
compressed_size = cA_r.size + cH_r.size + cV_r.size + cD_r.size + \
cH_g.size + cV_g.size + cD_g.size + \
cH_b.size + cV_b.size + cD_b.size
compression_ratio = compressed_size / original_size
# 显示压缩前后的图像
plt.subplot(1, 2, 1)
plt.imshow(img)
plt.title('Original image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(compressed_img.astype('uint8'))
plt.title('Compressed image')
plt.axis('off')
# 显示压缩率
plt.figure()
plt.text(0.5, 0.5, f'Compression ratio: {compression_ratio:.2%}',
fontsize=20, ha='center')
plt.axis('off')
plt.show()
```
运行代码后,将会输出压缩前后的图像,并显示压缩率。其中,原始图像和压缩后的图像都会被显示在一个子图中,而压缩率将会在另一个子图中显示。
阅读全文