1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
import cv2
import numpy as np
import random as r
def salt(origin_img, n):#椒盐噪声
img=origin_img.copy()
for k in range(n):
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
return img
def makegauss(origin_img):#高斯噪声
img=origin_img.copy();
for i in range(img.shape[0]):
for j in range(img.shape[1]):
g=r.gauss(0,10)
r1=np.where((g+img[i,j])>255,255,(g+img[i,j]))
r2=np.where(r1<0,0,r1)
img[i,j]=np.round(r2)
return img
def picdiff(img1,img2):
r=0;g=0;b=0
for i in range(img1.shape[0]):
for j in range(img1.shape[1]):
r+=abs(int(img1[i,j,0])-int(img2[i,j,0]))
g+=abs(int(img1[i,j,1])-int(img2[i,j,1]))
b+=abs(int(img1[i,j,2])-int(img2[i,j,2]))
print("r:",r,"g:",g,"b:",b)
#------------------------------------------
#read
path2pic=".\\"#input("input the path:")
picname="try.bmp"#input("input pic name:")
winsize=3#int(input("size of win:"))
img01 = cv2.imread(path2pic+picname)#读取目标图片
#------------------------------------------
#salt
imgwithsalt=salt(img01,10000)
#中值滤波
img_medianBlur=cv2.medianBlur(imgwithsalt,winsize)
#均值滤波
img_Blur=cv2.blur(imgwithsalt,(winsize,winsize))
#显示
cv2.namedWindow("salt")
cv2.imshow("salt",imgwithsalt)
cv2.namedWindow("medianBlur")
cv2.imshow("medianBlur",img_medianBlur)
cv2.namedWindow("Blur")
cv2.imshow("Blur",img_Blur)
cv2.waitKey (0)
cv2.destroyAllWindows()
#还原程度
print("diff with origin pic:")
picdiff(img01,imgwithsalt)#原图与噪点图的差异
picdiff(img01,img_medianBlur)
picdiff(img01,img_Blur)
print("---------------------------")
#------------------------------------------
#gauss
imgwithgauss=makegauss(img01)
#中值滤波
img_medianBlur=cv2.medianBlur(imgwithgauss,winsize)
#均值滤波
img_Blur=cv2.blur(imgwithgauss,(winsize,winsize))
#显示
cv2.namedWindow("gauss")
cv2.imshow("gauss",imgwithgauss)
cv2.namedWindow("medianBlur")
cv2.imshow("medianBlur",img_medianBlur)
cv2.namedWindow("Blur")
cv2.imshow("Blur",img_Blur)
cv2.waitKey (0)
cv2.destroyAllWindows()
#还原程度
print("diff with origin pic:")
picdiff(img01,imgwithgauss)#原图与噪点图的差异
picdiff(img01,img_medianBlur)
picdiff(img01,img_Blur)
#------------------------------------------
#存储
#save=input("save or not?[y/n]:")
#if save=="y":
# cv2.imwrite(path2pic+"medianBlur.bmp",img_medianBlur)
# cv2.imwrite(path2pic+"Blur.bmp",img_Blur)
# cv2.imwrite(path2pic+"white.bmp",imgwithgauss)
|