python中opencv给图片加入高斯噪声
以下是使用Python中OpenCV给图片加入高斯噪声的示例代码:
import cv2
import numpy as np
# 加载图片
img = cv2.imread('image.jpg')
# 获取图片的高度和宽度
height, width = img.shape[:2]
# 创建一个与原图像大小相同的矩阵
noise = np.zeros((height, width, 3), np.uint8)
# 生成高斯噪声
cv2.randn(noise, 0, 50)
# 将高斯噪声添加到原图像中
img_noise = cv2.add(img, noise)
# 显示原图像和加入噪声后的图像
cv2.imshow('Original Image', img)
cv2.imshow('Image with Gaussian Noise', img_noise)
cv2.waitKey(0)
cv2.destroyAllWindows()
这段代码首先加载一张图片,然后创建一个与原图像大小相同的矩阵用于生成高斯噪声。使用cv2.randn()
函数生成高斯噪声,第一个参数为噪声矩阵,第二个参数为平均值,第三个参数为标准差。最后,将高斯噪声添加到原图像中,并显示原图像和加入噪声后的图像。
python添加高斯噪声_使用Python-OpenCV向图片添加噪声(高斯噪声、椒盐噪声)
添加高斯噪声可以使用NumPy和OpenCV库。具体的步骤如下:
- 导入NumPy和OpenCV库:
import numpy as np
import cv2
- 读取图片:
img = cv2.imread('image.jpg')
- 生成高斯噪声:
mean = 0
var = 100
sigma = var ** 0.5
gaussian = np.random.normal(mean, sigma, (img.shape[0], img.shape[1], img.shape[2]))
gaussian = gaussian.reshape(img.shape)
其中,mean表示噪声的均值,var表示噪声的方差,sigma表示噪声的标准差,np.random.normal是生成高斯分布的函数。
- 将高斯噪声添加到图片中:
img_gaussian = img + gaussian
- 显示添加噪声后的图片:
cv2.imshow('Gaussian noise', img_gaussian)
cv2.waitKey(0)
cv2.destroyAllWindows()
完整代码如下:
import numpy as np
import cv2
img = cv2.imread('image.jpg')
mean = 0
var = 100
sigma = var ** 0.5
gaussian = np.random.normal(mean, sigma, (img.shape[0], img.shape[1], img.shape[2]))
gaussian = gaussian.reshape(img.shape)
img_gaussian = img + gaussian
cv2.imshow('Gaussian noise', img_gaussian)
cv2.waitKey(0)
cv2.destroyAllWindows()
注意:在添加噪声后,像素值可能会超出0-255的范围,需要使用clip函数将其限制在0-255之间,如下所示:
img_gaussian = np.clip(img_gaussian, 0, 255)
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()
相关推荐













