脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python使用opencv对图像添加噪声(高斯/椒盐/泊松/斑点)

python使用opencv对图像添加噪声(高斯/椒盐/泊松/斑点)

2022-11-23 09:46修炼之路 Python

这篇文章主要介绍了python使用opencv对图像添加噪声(高斯/椒盐/泊松/斑点),具有一定的学习价值,需要的小伙伴可以参考一下,希望对你有所帮助

导读:

这篇文章主要介绍如何利用opencv来对图像添加各类噪声,原图:

python使用opencv对图像添加噪声(高斯/椒盐/泊松/斑点)

 

1、高斯噪声

高斯噪声就是给图片添加一个服从高斯分布的噪声,可以通过调节高斯分布标准差(sigma)的大小来控制添加噪声程度,sigma越大添加的噪声越多图片损坏的越厉害

#读取图片
img = cv2.imread("demo.png")
#设置高斯分布的均值和方差
mean = 0
#设置高斯分布的标准差
sigma = 25
#根据均值和标准差生成符合高斯分布的噪声
gauss = np.random.normal(mean,sigma,(img_height,img_width,img_channels))
#给图片添加高斯噪声
noisy_img = image + gauss
#设置图片添加高斯噪声之后的像素值的范围
noisy_img = np.clip(noisy_img,a_min=0,a_max=255)
#保存图片
cv2.imwrite("noisy_img.png",noise_img)

python使用opencv对图像添加噪声(高斯/椒盐/泊松/斑点)

 

2、椒盐噪声

椒盐噪声就是给图片添加黑白噪点,椒指的是黑色的噪点(0,0,0)盐指的是白色的噪点(255,255,255),通过设置amount来控制添加噪声的比例,值越大添加的噪声越多,图像损坏的更加严重

#读取图片
img = cv2.imread("demo.png")
#设置添加椒盐噪声的数目比例
s_vs_p = 0.5
#设置添加噪声图像像素的数目
amount = 0.04
noisy_img = np.copy(image)
#添加salt噪声
num_salt = np.ceil(amount * image.size * s_vs_p)
#设置添加噪声的坐标位置
coords = [np.random.randint(0,i - 1, int(num_salt)) for i in image.shape]
noisy_img[coords] = 255
#添加pepper噪声
num_pepper = np.ceil(amount * image.size * (1. - s_vs_p))
#设置添加噪声的坐标位置
coords = [np.random.randint(0,i - 1, int(num_pepper)) for i in image.shape]
noisy_img[coords] = 0
#保存图片
cv2.imwrite("noisy_img.png",noise_img)

python使用opencv对图像添加噪声(高斯/椒盐/泊松/斑点)

 

3、泊松噪声

#读取图片
img = cv2.imread("demo.png")
#计算图像像素的分布范围
vals = len(np.unique(image))
vals = 2 ** np.ceil(np.log2(vals))
#给图片添加泊松噪声
noisy_img = np.random.poisson(image * vals) / float(vals)
#保存图片
cv2.imwrite("noisy_img.png",noise_img)

python使用opencv对图像添加噪声(高斯/椒盐/泊松/斑点)

 

4、speckle噪声

#读取图片
img = cv2.imread("demo.png")
#随机生成一个服从分布的噪声
gauss = np.random.randn(img_height,img_width,img_channels)
#给图片添加speckle噪声
noisy_img = image + image * gauss
#归一化图像的像素值
noisy_img = np.clip(noisy_img,a_min=0,a_max=255)
#保存图片
cv2.imwrite("noisy_img.png",noise_img)

python使用opencv对图像添加噪声(高斯/椒盐/泊松/斑点)

到此这篇关于python使用opencv对图像添加噪声(高斯/椒盐/泊松/斑点)的文章就介绍到这了,更多相关python使用opencv内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/sinat_29957455/article/details/123977298

延伸 · 阅读

精彩推荐