import numpy as np import matplotlib.pyplot as plt import pywt from skimage import io, color # 读取灰度图像并转换为RGB图像 img_gray = io.imread('lena.png', as_gray=True) img = color.gray2rgb(img_gray) # 对图像的三个通道进行DWT变换 coeffs_r = pywt.dwt2(img[:, :, 0], 'haar') coeffs_g = pywt.dwt2(img[:, :, 1], 'haar') coeffs_b = pywt.dwt2(img[:, :, 2], 'haar') # 设置压缩比率 compress_ratio = 0.5 # 计算阈值 threshold_r = np.sort(np.abs(coeffs_r[1].ravel()))[::-1][int(compress_ratio * len(coeffs_r[1].ravel()))] threshold_g = np.sort(np.abs(coeffs_g[1].ravel()))[::-1][int(compress_ratio * len(coeffs_g[1].ravel()))] threshold_b = np.sort(np.abs(coeffs_b[1].ravel()))[::-1][int(compress_ratio * len(coeffs_b[1].ravel()))] # 对小于阈值的系数进行置零 coeffs_r = list(coeffs_r) coeffs_r[0] = np.round(coeffs_r[0]) coeffs_r[1] = np.where(np.abs(coeffs_r[1]) < threshold_r, 0, coeffs_r[1]) coeffs_r[2] = np.where(np.abs(coeffs_r[2]) < threshold_r, 0, coeffs_r[2]) coeffs_g = list(coeffs_g) coeffs_g[0] = np.round(coeffs_g[0]) coeffs_g[1] = np.where(np.abs(coeffs_g[1]) < threshold_g, 0, coeffs_g[1]) coeffs_g[2] = np.where(np.abs(coeffs_g[2]) < threshold_g, 0, coeffs_g[2]) coeffs_b = list(coeffs_b) coeffs_b[0] = np.round(coeffs_b[0]) coeffs_b[1] = np.where(np.abs(coeffs_b[1]) < threshold_b, 0, coeffs_b[1]) coeffs_b[2] = np.where(np.abs(coeffs_b[2]) < threshold_b, 0, coeffs_b[2]) # 合并三个通道的系数 coeffs = [np.stack([coeffs_r[i], coeffs_g[i], coeffs_b[i]], axis=-1) for i in range(len(coeffs_r))] # 对图像进行IDWT反变换 img_dwt = pywt.idwt2(coeffs, 'haar') # 显示原始图像和压缩后的图像 fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 4)) ax = axes.ravel() ax[0].imshow(img) ax[0].set_title("Original image") ax[1].imshow(img_dwt) ax[1].set_title("Compressed image (DWT)") ax[1].set_xlabel("Compression ratio: {:.2f}".format(compress_ratio)) plt.tight_layout() plt.show()
时间: 2024-02-20 08:58:15 浏览: 135
import numpy as np import matplotlib.pyplot as plt import math
这段代码缺少了两行,分别是导入numpy和matplotlib.pyplot两个模块的语句。请在代码的开头添加以下两行语句:
```
import numpy as np
import matplotlib.pyplot as plt
```
这样就可以解决代码中的报错。
阅读全文