使用Python-OpenCV向图片添加噪声的实现(高斯噪声、椒盐噪声)
Python  /  管理员 发布于 7年前   350
在matlab中,存在执行直接得函数来添加高斯噪声和椒盐噪声。Python-OpenCV中虽然不存在直接得函数,但是很容易使用相关的函数来实现。
代码:
import numpy as npimport randomimport cv2def sp_noise(image,prob): ''' 添加椒盐噪声 prob:噪声比例 ''' output = np.zeros(image.shape,np.uint8) thres = 1 - prob for i in range(image.shape[0]): for j in range(image.shape[1]): rdn = random.random() if rdn < prob: output[i][j] = 0 elif rdn > thres: output[i][j] = 255 else: output[i][j] = image[i][j] return outputdef gasuss_noise(image, mean=0, var=0.001): ''' 添加高斯噪声 mean : 均值 var : 方差 ''' image = np.array(image/255, dtype=float) noise = np.random.normal(mean, var ** 0.5, image.shape) out = image + noise if out.min() < 0: low_clip = -1. else: low_clip = 0. out = np.clip(out, low_clip, 1.0) out = np.uint8(out*255) #cv.imshow("gasuss", out) return out
可见,只要我们得到满足某个分布的多维数组,就能作为噪声添加到图片中。
例如:
import cv2import numpy as np>>> im = np.empty((5,5), np.uint8) # needs preallocated input image>>> imarray([[248, 168, 58, 2, 1], # uninitialized memory counts as random, too ? fun ;) [ 0, 100, 2, 0, 101], [ 0, 0, 106, 2, 0], [131, 2, 0, 90, 3], [ 0, 100, 1, 0, 83]], dtype=uint8)>>> im = np.zeros((5,5), np.uint8) # seriously now.>>> imarray([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], dtype=uint8)>>> cv2.randn(im,(0),(99)) # normalarray([[ 0, 76, 0, 129, 0], [ 0, 0, 0, 188, 27], [ 0, 152, 0, 0, 0], [ 0, 0, 134, 79, 0], [ 0, 181, 36, 128, 0]], dtype=uint8)>>> cv2.randu(im,(0),(99)) # uniformarray([[19, 53, 2, 86, 82], [86, 73, 40, 64, 78], [34, 20, 62, 80, 7], [24, 92, 37, 60, 72], [40, 12, 27, 33, 18]], dtype=uint8)
然后再:
img = ...noise = ...image = img + noise
参考链接:
1、https://stackoverflow.com/questions/22937589/how-to-add-noise-gaussian-salt-and-pepper-etc-to-image-in-python-with-opencv#
2、https://stackoverflow.com/questions/14435632/impulse-gaussian-and-salt-and-pepper-noise-with-opencv#
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号