OpenCV3 椒盐噪声python语言实现

salt & pepper()

在OpenCV中并没有像MATLAB中提供现成可以使用的噪声函数,比如在MATLAB中我们可以使用salt & pepper(),gaussian(),等函数方便的添加椒盐噪声和高斯噪声,为了使使用OpenCV处理数字图像的童鞋们能够像使用MATLAB一样使用噪声函数,为此我编写了一个尽量贴近于MATLAB风格的椒盐噪声函数,其他的噪声函数等我闲下来了再继续添加。
废话不多说,开干!

import cv2
import numpy as np
def saltpepper(img,n):
    m=int((img.shape[0]*img.shape[1])*n)
    for a in range(m):
        i=int(np.random.random()*img.shape[1])
        j=int(np.random.random()*img.shape[0])
        if img.ndim==2:
            img[j,i]=255
        elif img.ndim==3:
            img[j,i,0]=255
            img[j,i,1]=255
            img[j,i,2]=255
    for b in range(m):
        i=int(np.random.random()*img.shape[1])
        j=int(np.random.random()*img.shape[0])
        if img.ndim==2:
            img[j,i]=0
        elif img.ndim==3:
            img[j,i,0]=0
            img[j,i,1]=0
            img[j,i,2]=0
    return img


#上面就是椒盐噪声函数,下面是使用方法,大家可以愉快的玩耍了
img=cv2.imread('adel.jpg')
saltImage=saltpepper(img,0.02)
cv2.imshow('saltImage',saltImage)
cv2.waitKey(0)
cv2.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/KimLK/article/details/78261809