使用Python-OpenCV向图片添加噪声的实现(高斯噪声、椒盐噪声)
作者:Rogn 时间:2023-07-01 06:32:45
在matlab中,存在执行直接得函数来添加高斯噪声和椒盐噪声。Python-OpenCV中虽然不存在直接得函数,但是很容易使用相关的函数来实现。
代码:
import numpy as np
import random
import cv2
def 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 output
def 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 cv2
import numpy as np
>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[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.
>>> im
array([[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)) # normal
array([[ 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)) # uniform
array([[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#
来源:https://www.cnblogs.com/lfri/p/10627595.html
标签:OpenCV,图片,噪声
0
投稿
猜你喜欢
python 使用paramiko模块进行封装,远程操作linux主机的示例代码
2023-03-08 19:38:19
SQL Server 2005 五个动态管理对象
2008-12-18 14:50:00
Python内置数据结构列表与元组示例详解
2021-08-17 21:28:14
MySQL数据备份方法的选择与思考
2024-01-19 21:02:50
仅Firefox中链接A无法实现模拟点击以触发其默认行为
2023-06-27 23:29:02
Python中的单继承与多继承实例分析
2022-07-03 13:48:06
python求质数的3种方法
2023-02-12 04:07:54
vue实现菜单切换功能
2024-05-03 15:12:08
Python使用asyncio异步时的常见问题总结
2021-02-06 04:43:12
Python bsddb模块操作Berkeley DB数据库介绍
2024-01-18 05:32:02
Python MySQLdb模块连接操作mysql数据库实例
2024-01-18 03:10:26
jupyter notebook 增加kernel教程
2023-04-27 20:28:43
python包的导入方式总结
2021-01-18 08:55:23
Python3实现对列表按元组指定列进行排序的方法分析
2022-10-05 18:01:13
JS实现匀加速与匀减速运动的方法示例
2024-06-07 15:27:36
asp如何用Access加密页面?
2010-06-10 18:41:00
PHP如何实现HTTP验证
2023-09-04 05:32:46
springBoot下实现java自动创建数据库表
2024-01-24 12:26:31
优化SQL Server的内存占用之执行缓存
2024-01-12 19:13:27
Mysql中的find_in_set的使用方法介绍
2024-01-14 06:24:19