图片添加椒盐噪声

图片添加椒盐噪声,第1张

import cv2 as cv
import numpy as np
def rgb2gray(img):
    h=img.shape[0]
    w=img.shape[1]
    img1=np.zeros((h,w),np.uint8)
    for i in range(h):
        for j in range(w):
            img1[i,j]=0.144*img[i,j,0]+0.587*img[i,j,1]+0.299*img[i,j,2]
    return img1
def noise(img,snr):
    h=img.shape[0]
    w=img.shape[1]
    img1=img.copy()
    sp=h*w   # 计算图像像素点个数
    NP=int(sp*(1-snr))   # 计算图像椒盐噪声点个数
    for i in range (NP):
        randx=np.random.randint(1,h-1)   # 生成一个 1 至 h-1 之间的随机整数
        randy=np.random.randint(1,w-1)   # 生成一个 1 至 w-1 之间的随机整数
        if np.random.random()<=0.5:   # np.random.random()生成一个 0 至 1 之间的浮点数
            img1[randx,randy]=0
        else:
            img1[randx,randy]=255
    return img1
image=cv.imread("C:/Users/Privirea Ta/Desktop/00/psp-tsp.jpg")
grayimage=rgb2gray(image)
noiseimage=noise(grayimage,0.6)   # 将信噪比设定为0.6
# cv.imshow("image",image)
# cv.imshow("grayimage",grayimage)
# cv.imshow("noiseimage",noiseimage)
cv.imwrite("C:/Users/Privirea Ta/Desktop/000/psp-tsp.jpg", noiseimage)
# cv.waitKey(0)
# cv.destroyAllWindows()

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/570551.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存