import cv2
import pywt
import numpy as np
def wavelet_denoise(image, wavelet='db4', level=1, mode='soft'):
# 将图像转换为灰度图
if len(image.shape) == 3:
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 进行小波分解
coeffs = pywt.wavedec2(image, wavelet, level=level)
# 对每个细节系数应用阈值处理
threshold = np.std(coeffs[-1]) * np.sqrt(2 * np.log2(image.size))
new_coeffs = [coeffs[0]]
for detail_coeffs in coeffs[1:]:
new_detail_coeffs = [pywt.threshold(d, threshold, mode=mode) for d in detail_coeffs]
new_coeffs.append(new_detail_coeffs)
# 进行小波重构
denoised_image = pywt.waverec2(new_coeffs, wavelet)
# 将像素值限制在 0 到 255 之间
denoised_image = np.clip(denoised_image, 0, 255).astype(np.uint8)
return denoised_image
# 读取图像
image = cv2.imread('2.png')
# 进行小波去噪
denoised_image = wavelet_denoise(image)
cv2.imwrite('3.png', denoised_image)
# 显示原始图像和去噪后的图像
cv2.imshow('Original Image', image)
cv2.imshow('Denoised Image', denoised_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
