im_salt = Image.fromarray(img1)
im_salt = img1.convert('RGB')
引用
from PIL import Image
import numpy as np
from numpy import*
from pylab import *
import random
import imageio
添加高斯噪声
def noise_Gaussian(im,mean,variance):
img = np.asarray(im)
img1 = img.copy()
img1 = np.array(img1/255, dtype=float)
noise = np.random.normal(0, 0.05, img1.shape)
out = img1 + noise
out = np.uint8(out*255)
# im_Gaussian = Image.fromarray(out)
return out
添加椒盐噪声
def noise_salt(im,persentage):
img = np.asarray(im)
img1 = img.copy()
noiseNum=int(persentage*img1.shape[0]*img1.shape[1])
for i in range(noiseNum):
w = random.randint(0,img1.shape[0]-1)
h = random.randint(0,img1.shape[1]-1)
if random.randint(0,1) ==0:
img1[h,w] =0
else:
img1[h,w] = 255
im_salt = Image.fromarray(img1)
# im_salt = img1.convert('RGB')
return im_salt
添加脉冲噪声
def noise_pulse(im,persentage):
img = np.asarray(im)
img2 = img.copy()
noiseNum=int(persentage*img2.shape[0]*img2.shape[1])
for i in range(noiseNum):
w = random.randint(0,img2.shape[0]-1)
h = random.randint(0,img2.shape[1]-1)
img2[h,w] = 255
im_pulse = Image.fromarray(img2)
im_pulse = im_pulse.convert('RGB')
return im_pulse
高斯滤波器
def gaussian_filter(im, K_size=3, sigma=1.3):
img = np.asarray(np.uint8(im))
if len(img.shape) == 3:
H, W, C = img.shape
else:
img = np.expand_dims(img, axis=-1)
H, W, C = img.shape
## Zero padding
pad = K_size // 2
out = np.zeros((H + pad * 2, W + pad * 2, C), dtype=np.float)
out[pad: pad + H, pad: pad + W] = img.copy().astype(np.float)
## prepare Kernel
K = np.zeros((K_size, K_size), dtype=np.float)
for x in range(-pad, -pad + K_size):
for y in range(-pad, -pad + K_size):
K[y + pad, x + pad] = np.exp( -(x ** 2 + y ** 2) / (2 * (sigma ** 2)))
K /= (2 * np.pi * sigma * sigma)
K /= K.sum()
tmp = out.copy()
# filtering
for y in range(H):
for x in range(W):
for c in range(C):
out[pad + y, pad + x, c] = np.sum(K * tmp[y: y + K_size, x: x + K_size, c])
out = np.clip(out, 0, 255)
out = out[pad: pad + H, pad: pad + W].astype(np.uint8)
return out
main() 添加高斯噪声,并高斯滤波去噪
# 读入图片
img = Image.open("./lena.jpg")
im_Gaussian = noise_Gaussian(im,0,0.05)
imageio.imwrite("im_Gaussian.jpg",im_Gaussian)
im_Gaussian_gaussian = gaussian_filter(im_Gaussian,sigma=1.3)
imageio.imwrite("im_Gaussian_gaussian_sigma1.3.jpg",im_Gaussian_gaussian)
添加椒盐噪声,并高斯去噪
im_pulse = noise_pulse(im,0.005)
im_pulse = np.asarray(im_pulse)
imageio.imwrite("im_pulse.jpg",im_pulse)
im_pulse_gaussian = gaussian_filter(im_pulse,sigma=10.3)
imageio.imwrite("im_pulse_gaussian_sigma10.3.jpg",im_pulse_gaussian)
添加脉冲噪声,并高斯去噪
im_pulse = noise_pulse(im,0.005)
im_pulse = np.asarray(im_pulse)
imageio.imwrite("im_pulse.jpg",im_pulse)
im_pulse_gaussian = gaussian_filter(im_pulse,sigma=10.3)
imageio.imwrite("im_pulse_gaussian_sigma10.3.jpg",im_pulse_gaussian)