import random
def sp_noise(image,prob):
'''
Add salt and pepper noise to image
prob: Probability of the noise
'''
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
这就是我想要实现的。我知道这个函数不使用矢量化,但我不知道在这种情况下如何摆脱循环。如果有像素值的条件,那将是微不足道的。但在这种情况下,索引或像素值没有条件,我只需要保留像素值,或者根据随机变量的值,将其设置为0或1
如何将其矢量化
不确定这是否会产生完全相同的结果-因为有一种可能性(非常小),你可以用盐击中一个像素,然后再用胡椒再次击中同一个像素-但我尝试了不同的方法。它还能产生半盐半胡椒,其他溶液只有在对大量样本进行平均时才会产生。也许节省的速度和内存值得不精确性—YMMV:-)
首先确定有多少像素将受到噪声的影响,称之为
N
。然后生成N/2对[x,y]坐标并将输出图像中的对应像素设置为黑色,然后生成另一N/2对[x,y]坐标并将其设置为白色通过
p=0.1
和p=0.01
,我得到:您可以使用附加的} ,以获得整个随机浮点数组。然后,使用^{} 和boolean array indexing访问与其中一个条件匹配的所有像素
size
参数调用^{这就是我的解决方案,包括OpenCV图像加载和显示以及一些简单的性能分析:
图像输出具有可比性。对于某些
400 x 400
RGB图像,我得到以下时间:希望有帮助
相关问题 更多 >
编程相关推荐