import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from skimage.restoration import estimate_sigma
from skimage import measure, util
from skimage.io import imread, imsave
import cv2 as cv
img = cv.imread("C:/Users/W1998/Desktop/photo/10m_plasticbag_1583.jpg", 0)
img_noisy = cv.imread("C:/Users/W1998/Desktop/photo/noisy.jpg", 0)
#导入的两张图片的大小必须一致
#print(img_noisy.shape) #查看原图的尺寸大小
#print(img.shape) #查看加噪图像的尺寸大小(我用的是高斯噪声)
#img_n = cv.resize(img_noisy, (850,491), interpolation=cv.INTER_CUBIC)#将上面两个图像尺寸大小缩放一致
def clip(im):
return np.maximum(0.,np.minimum(1.,im))
from os.path import normpath as fn # Fixes window/linux path conventions
import warnings
warnings.filterwarnings('ignore')
lena = np.float32(img)/255.
noisy_lena = np.float32(img_n)/255.
# Gaussian Filtering高斯滤波去噪
def gaussian(X,K):
x, y = np.mgrid[-K:K + 1, -K:K + 1]
g = np.exp(-(x ** 2 / float(K) + y ** 2 / float(K)))
kern = g / g.sum()
new_im = signal.convolve2d(X,kern,mode='same')
return new_im
def wavelet(X,levels, lmain):
def im2wv(img, nLev):
# pyr array
pyr = []
h_mat = np.array([[1, 1, 1, 1],
[-1, 1, -1, 1],
[-1, -1, 1, 1],
[1, -1, -1, 1]])
for i in range(nLev):
n, mid = len(img), len(img) // 2
# split image up for HWT
a = img[:n:2, :n:2]
b = img[1:n:2, :n:2]
c = img[:n:2, 1:n:2]
d = img[1:n:2, 1:n:2]
vec = np.array([a, b, c, d])
# reshape vector to perform mat mult
D = 1 / 2 * np.dot(h_mat, vec.reshape(4, mid * mid))
L, H1, H2, H3 = D.reshape([4, mid, mid])
pyr.append([H1, H2, H3])
img = L
pyr.append(L)
return pyr
def wv2im(pyr):
# need inverse of unitary matrix
h_mat = np.array([[1, 1, 1, 1],
[-1, 1, -1, 1],
[-1, -1, 1, 1],
[1, -1, -1, 1]])
h_mat_inv = np.linalg.inv(h_mat)
# last spot in pyramid is small img
# iterate in reverse to reconstruct
L = pyr[-1]
for [H1, H2, H3] in reversed(pyr[:-1]):
n, n2 = len(L), len(L) * 2
vec = np.array([L, H1, H2, H3])
# reshape vector to perform mat mult
D = 2 * np.dot(h_mat_inv, vec.reshape(4, n * n))
a, b, c, d = D.reshape([4, n, n])
# assign pixels to correct spots in img
img = np.empty((n2, n2))
img[:n2:2, :n2:2] = a
img[1:n2:2, :n2:2] = b
img[:n2:2, 1:n2:2] = c
img[1:n2:2, 1:n2:2] = d
L = img
return L
# Return corresponding coefficients x (same shape/size)
# that minimizes (x - y)^2 + lmbda * abs(x)
def denoise_coeff(y, lmbda):
x = np.copy(y)
x[np.where(y > lmbda / 2.0)] -= lmbda / 2.0
x[np.where(y < -lmbda / 2.0)] += lmbda / 2.0
x[np.where(np.logical_and(y>-lmbda/2.0,y