编写Python程序,给图像添加高斯噪声、椒盐噪声、泊松噪声、瑞利噪声、指数分布噪声和均匀分布噪声
时间: 2023-10-20 10:55:25 浏览: 201
图像添加高斯椒盐噪声
可以使用OpenCV库来对图像添加噪声。下面是一个示例程序,展示如何给图像添加高斯噪声、椒盐噪声、泊松噪声、瑞利噪声、指数分布噪声和均匀分布噪声。
```python
import cv2
import numpy as np
# 添加高斯噪声
def add_gaussian_noise(image):
row, col, ch = image.shape
mean = 0
var = 0.1
sigma = var ** 0.5
gauss = np.random.normal(mean, sigma, (row, col, ch))
gauss = gauss.reshape(row, col, ch)
noisy_image = image + gauss
return noisy_image
# 添加椒盐噪声
def add_salt_and_pepper_noise(image, ratio=0.05):
row, col, ch = image.shape
num_pixels = row * col
num_salt = int(num_pixels * ratio)
coords = [np.random.randint(0, i - 1, num_salt) for i in image.shape]
image[coords] = 1
num_pepper = int(num_pixels * ratio)
coords = [np.random.randint(0, i - 1, num_pepper) for i in image.shape]
image[coords] = 0
return image
# 添加泊松噪声
def add_poisson_noise(image):
vals = len(np.unique(image))
vals = 2 ** np.ceil(np.log2(vals))
noisy_image = np.random.poisson(image * vals) / float(vals)
return noisy_image
# 添加瑞利噪声
def add_rayleigh_noise(image):
row, col, ch = image.shape
sigma = 0.1
rayleigh = np.random.rayleigh(sigma, (row, col, ch))
noisy_image = image + rayleigh
return noisy_image
# 添加指数分布噪声
def add_exponential_noise(image):
row, col, ch = image.shape
scale = 0.1
exponential = np.random.exponential(scale, (row, col, ch))
noisy_image = image + exponential
return noisy_image
# 添加均匀分布噪声
def add_uniform_noise(image):
row, col, ch = image.shape
low = -0.5
high = 0.5
uniform = np.random.uniform(low, high, (row, col, ch))
noisy_image = image + uniform
return noisy_image
# 读取图像
image_path = 'image.jpg'
image = cv2.imread(image_path)
# 添加高斯噪声
gaussian_noisy_image = add_gaussian_noise(image.copy())
# 添加椒盐噪声
salt_and_pepper_noisy_image = add_salt_and_pepper_noise(image.copy())
# 添加泊松噪声
poisson_noisy_image = add_poisson_noise(image.copy())
# 添加瑞利噪声
rayleigh_noisy_image = add_rayleigh_noise(image.copy())
# 添加指数分布噪声
exponential_noisy_image = add_exponential_noise(image.copy())
# 添加均匀分布噪声
uniform_noisy_image = add_uniform_noise(image.copy())
# 显示原图和添加噪声后的图像
cv2.imshow('Original Image', image)
cv2.imshow('Gaussian Noisy Image', gaussian_noisy_image)
cv2.imshow('Salt and Pepper Noisy Image', salt_and_pepper_noisy_image)
cv2.imshow('Poisson Noisy Image', poisson_noisy_image)
cv2.imshow('Rayleigh Noisy Image', rayleigh_noisy_image)
cv2.imshow('Exponential Noisy Image', exponential_noisy_image)
cv2.imshow('Uniform Noisy Image', uniform_noisy_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,这只是一个示例程序,你可以根据自己的需求进行修改和扩展。
阅读全文