Rogn

# 使用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

posted @ 2019-03-30 15:45  Rogn  阅读(32608)  评论(0编辑  收藏  举报