文章目录
🧡🧡实验流程🧡🧡
3.对图像加入任意噪声,并用中值滤波进行过滤
5.实现高斯滤波
🧡🧡全部代码🧡🧡
import cv2
import numpy as np
import matplotlib.pyplot as plt
def cv_show(img):
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
"""
3-1 均值滤波
"""
I = cv2.imread('img/test1_LenaRGB.tif')
J = I.copy()
rows, cols, _ = J.shape
amount = 0.05
salt_vs_pepper = 0.5
num_salt = np.ceil(amount * salt_vs_pepper * rows * cols)
coords = [np.random.randint(0, i - 1, int(num_salt)) for i in [rows,cols]]
coords = tuple(coords)
J[coords[:]] = (255, 255, 255)
num_pepper = np.ceil(amount * (1-salt_vs_pepper) * rows * cols)
coords = [np.random.randint(0,i-1,int(num_pepper)) for i in [rows,cols]]
oords = tuple(coords)
J[coords[:]] = (0,0,0,)
res = np.hstack((I, J))
cv_show(res)
K1 = cv2.blur(J, (3, 3))
K2 = cv2.blur(J, (5, 5))
res = np.hstack((K1, K2))
cv_show(res)
"""
3-2 高斯滤波
"""
I = cv2.imread('img/test1_LenaRGB.tif')
J = I.copy()
gauss = np.random.normal(0, 25, J.shape)
J = J + gauss
J = np.clip(J,a_min=0,a_max=255).astype(np.uint8)
res = np.hstack((I, J))
cv_show(res)
K1 = cv2.GaussianBlur(J, (5, 5), 1)
cv_show(K1)
"""
3-3 中值滤波
"""
I = cv2.imread('img/test1_LenaRGB.tif')
J = I.copy()
rows, cols, _ = J.shape
amount = 0.05
salt_vs_pepper = 0.5
num_salt = np.ceil(amount * salt_vs_pepper * rows * cols)
coords = [np.random.randint(0, i - 1, int(num_salt)) for i in [rows,cols]]
coords = tuple(coords)
J[coords[:]] = (255, 255, 255)
num_pepper = np.ceil(amount * (1-salt_vs_pepper) * rows * cols)
coords = [np.random.randint(0,i-1,int(num_pepper)) for i in [rows,cols]]
oords = tuple(coords)
J[coords[:]] = (0,0,0,)
res = np.hstack((I, J))
cv_show(res)
K1 = cv2.medianBlur(J, 5)
cv_show(K1)
"""
3-4 比较不同模板、不同噪声类型、不同滤波器类型的效果
"""
def generate_noise(image, noise_type):
if noise_type == 'gaussian':
noise = np.random.normal(0, 50, image.shape).astype(np.float32)
noisy_image = cv2.add(image.astype(np.float32), noise)
elif noise_type == 'salt':
salt_pepper_ratio = 0.3
salt = np.where(np.random.random(image.shape) < salt_pepper_ratio, 255, 0).astype(np.uint8)
noisy_image = cv2.add(image, salt)
elif noise_type == 'exponential':
lambd = 50
noise = np.random.exponential(lambd, image.shape).astype(np.float32)
noisy_image = cv2.add(image.astype(np.float32), noise)
else:
raise ValueError("Unsupported noise type")
return noisy_image.clip(0, 255).astype(np.uint8)
def apply_filter(image, filter_type, kernel_size):
if filter_type == 'mean':
filtered_image = cv2.blur(image, (kernel_size, kernel_size))
elif filter_type == 'gaussian':
filtered_image = cv2.GaussianBlur(image, (kernel_size, kernel_size), 0)
elif filter_type == 'median':
filtered_image = cv2.medianBlur(image, kernel_size)
else:
raise ValueError("Unsupported filter type")
return filtered_image
image = cv2.imread('img/test1_lena.tif', cv2.IMREAD_GRAYSCALE)
kernel_sizes = [3, 5, 9]
noise_types = ['gaussian', 'salt', 'exponential']
plt.figure(figsize=(12, 8))
for i, noise_type in enumerate(noise_types):
for j, kernel_size in enumerate(kernel_sizes):
noisy_image = generate_noise(image, noise_type)
filtered_mean = apply_filter(noisy_image, 'mean', kernel_size)
filtered_gaussian = apply_filter(noisy_image, 'gaussian', kernel_size)
filtered_median = apply_filter(noisy_image, 'median', kernel_size)
plt.subplot(len(noise_types), len(kernel_sizes), i * len(kernel_sizes) + j + 1)
plt.imshow(filtered_median, cmap='gray')
plt.title(f'Median Filter (Size: {kernel_size})(Noise: {noise_type})')
plt.axis('off')
plt.tight_layout()
plt.show()
"""
3-5 实现高斯滤波器
"""
def noise_Gaussian(img,mean,var):
J = img.copy()
size = J.shape
J = J / 255
gauss = np.random.normal(0, 0.1, size)
J = J + gauss
J = np.clip(J, 0, 1)
J = (J * 255).astype(np.uint8)
return J
ori = cv2.imread('img/test1_LenaRGB.tif')
img = noise_Gaussian(ori,mean=0,var=0.1)
cv_show(img)
def gaussian_filter(img, K_size=3, sigma=1.0):
img = np.asarray(np.uint8(img))
if len(img.shape) == 3:
H, W, C = img.shape
else:
img = np.expand_dims(img, axis=-1)
H, W, C = img.shape
pad = K_size // 2
out = np.zeros((H + pad * 2, W + pad * 2, C), dtype=float)
out[pad: pad + H, pad: pad + W] = img.copy().astype(float)
K = np.zeros((K_size, K_size), dtype=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()
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
gs1=gaussian_filter(img,K_size=5,sigma=5)
cv_show(gs1)
gs2 = cv2.GaussianBlur(img, (5, 5), 1)
cv_show(gs2)