代码实现 选取张图像, 进行以下操作:①对原始图像,分别添加高斯噪声、椒盐噪声②对原始图像,分别进行均匀平滑和高斯平滑③对加噪产后的图像。分别进行高斯平滑、中值滤波和信里叶频域滤波
时间: 2023-06-25 20:03:31 浏览: 246
好的,这是一个图像处理的任务,需要使用Python中的OpenCV库来实现。以下是代码实现:
```python
import cv2
import numpy as np
# 读入图像
img = cv2.imread('image.jpg')
# 添加高斯噪声
mean = 0
var = 0.1
sigma = var ** 0.5
gauss = np.random.normal(mean, sigma, img.shape)
gauss = gauss.reshape(img.shape)
img_gauss = img + gauss
# 添加椒盐噪声
s_vs_p = 0.5
amount = 0.004
out = np.copy(img)
num_salt = np.ceil(amount * img.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in img.shape]
out[coords] = 255
num_pepper = np.ceil(amount * img.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in img.shape]
out[coords] = 0
img_sp = out
# 均匀平滑
kernel = np.ones((5, 5), np.float32) / 25
img_blur = cv2.filter2D(img, -1, kernel)
# 高斯平滑
img_gaussian = cv2.GaussianBlur(img, (5, 5), 0)
# 对加噪图像进行高斯平滑
img_gauss_blur = cv2.GaussianBlur(img_gauss, (5, 5), 0)
# 对加噪图像进行中值滤波
img_median = cv2.medianBlur(img_sp, 5)
# 对加噪图像进行信里叶频域滤波
f = np.fft.fft2(img_sp)
fshift = np.fft.fftshift(f)
rows, cols = img_sp.shape
crow, ccol = int(rows/2), int(cols/2)
fshift[crow-30:crow+30, ccol-30:ccol+30] = 0
f_ishift = np.fft.ifftshift(fshift)
img_fft = np.fft.ifft2(f_ishift)
img_fft = np.abs(img_fft)
# 显示原始图像和处理后的图像
cv2.imshow('Original Image', img)
cv2.imshow('Gaussian Noise', img_gauss)
cv2.imshow('Salt and Pepper Noise', img_sp)
cv2.imshow('Uniform Blur', img_blur)
cv2.imshow('Gaussian Blur', img_gaussian)
cv2.imshow('Gaussian Blur on Gaussian Noise', img_gauss_blur)
cv2.imshow('Median Filter on Salt and Pepper Noise', img_median)
cv2.imshow('FFT Filter on Salt and Pepper Noise', img_fft)
# 等待按键,退出程序
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这段代码会读入一个名为 `image.jpg` 的图像,并且对其进行高斯噪声、椒盐噪声、均匀平滑、高斯平滑等操作。最后还会对产生噪声的图像进行高斯平滑、中值滤波和信里叶频域滤波。所有处理后的图像都会在窗口中显示出来。
阅读全文