图像数据处理—添加噪声

首先是噪声的大体分类:

噪点噪声:又称脉冲噪声、椒盐噪声

雪花噪声:又称高斯噪声

条纹噪声:

给图像添加椒盐噪声

import cv2 as cv
import numpy as np

def addnoise():
    src = cv.imread("lena.tiff")
    cv.imshow("input",src)
    h,w = src.shape[:2]  #获取图像的宽高信息
    nums = 5000
    rows = np.random.randint(0, h, (5000), dtype = np.int)
    cols = np.random.randint(0,w,(5000),dtype = np.int)
    for i in range(nums):
        if i%2 == 1:
            src[rows[i],cols[i]] = (255,255,255)#奇数则产生白色
        else:src[rows[i],cols[i]] = (0,0,0) 偶数则产生黑椒盐色
    cv.imshow("salt and pepper image", src)

if __name__ == '__main__':
    addnoise()
    cv.waitKey(0)

添加高斯噪声

import cv2 as cv
import numpy as np

def addnoise():
    src = cv.imread("lena.tiff")
    copy = np.copy(src)
    cv.imshow("input",src)
    h,w = src.shape[:2]  #获取图像的宽高信息
    nums = 5000
    rows = np.random.randint(0, h, (5000), dtype = np.int)
    cols = np.random.randint(0,w,(5000),dtype = np.int)
    for i in range(nums):
        if i%2 == 1:
            src[rows[i],cols[i]] = (255,255,255)
        else:src[rows[i],cols[i]] = (0,0,0)
    cv.imshow("salt and pepper image", src)
    gnoise = np.zeros(src.shape,src.dtype)
    m=(15,15,15)  #噪声均值
    s=(30,30,30) #噪声方差
    cv.randn(gnoise,m,s)##产生高斯噪声
    cv.imshow("gnoise",gnoise)#
    dst = cv.add(copy,gnoise)#将高斯噪声图像加到原图上去
    cv.imshow("gaussion",dst)



if __name__ == '__main__':
    addnoise()
    cv.waitKey(0)

条纹噪声

 

from PIL import Image
import numpy as np
import warnings

T1=100#阈值1,通道行差
T2=1000#阈值2,A通道差绝对和
T3=1000#阈值3,AB通道绝对和
#算法来源,论文http://www.doc88.com/p-2572496212147.html
warnings.filterwarnings("ignore")
demo=Image.open("noise_check//21.jpg")
im=np.array(demo.convert('L'))#灰度化矩阵
print(im.shape)
print(im.dtype)
r,g,b=demo.split()
#gm=demo.convert('L')
#plt.subplot(2,2,1)
#plt.imshow(gm,cmap='gray'),plt.axis('off')
#plt.subplot(2,2,2)
#plt.imshow(r,cmap='gray'),plt.axis('off')
#plt.subplot(2,2,3)
#plt.imshow(g,cmap='gray'),plt.axis('off')
#plt.subplot(2,2,4)
#plt.imshow(b,cmap='gray'),plt.axis('off')
#plt.show()
rm=np.array(r)
gm=np.array(g)
bm=np.array(b)
height=im.shape[0]#尺寸
width=im.shape[1]
midimg=[im,rm,gm,bm]
count=0
for i in range(4):
    mid=midimg[i]
    n=0
    while(1):
        if n+3>=height:break
        for j in range(6,width-6,1):
            grA=mid[n][j]
            grB=mid[n+3][j]
            if abs(grA-grB)>T1:
                L1=0
                L2=0
                for k in range(j-6,j+6,1):
                    L1+=abs(mid[n][k]-grA)
                    L2+=abs(mid[n][k]-mid[n+3][k])
                    #print(L1)
                    #print(L2)
                    #print("-----")
                    if L1T3:
                        count+=1
        n+=10
#print(count)
sum=(height-3)*4*(width-12)
#print(count/sum)
res=round(count/sum,5)#保留3位小数
print(str(res*100)+"%")

你可能感兴趣的:(python,开发语言)