python-opencv 高斯噪声和椒盐噪声
时间: 2023-09-24 20:07:38 浏览: 125
使用Python-OpenCV向图片添加噪声的实现(高斯噪声、椒盐噪声)
高斯噪声和椒盐噪声是数字图像处理中常见的两种噪声形式。下面是使用python-opencv库生成高斯噪声和椒盐噪声的示例代码:
## 生成高斯噪声
import numpy as np
import cv2
# 读取原始图像
img = cv2.imread('lena.jpg')
# 生成高斯噪声
mean = 0
var = 0.1
sigma = var ** 0.5
gaussian = np.random.normal(mean, sigma, img.shape)
gaussian = gaussian.reshape(img.shape).astype(np.float32)
noisy_image = img + gaussian
# 显示原始图像和加噪后的图像
cv2.imshow('Original', img)
cv2.imshow('Gaussian Noise', noisy_image.astype(np.uint8))
cv2.waitKey(0)
cv2.destroyAllWindows()
## 生成椒盐噪声
import numpy as np
import cv2
# 读取原始图像
img = cv2.imread('lena.jpg')
# 生成椒盐噪声
s_vs_p = 0.5
amount = 0.004
noisy_image = np.copy(img)
# Salt mode
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]
noisy_image[coords] = 255
# Pepper mode
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]
noisy_image[coords] = 0
# 显示原始图像和加噪后的图像
cv2.imshow('Original', img)
cv2.imshow('Salt and Pepper Noise', noisy_image.astype(np.uint8))
cv2.waitKey(0)
cv2.destroyAllWindows()
阅读全文