import numpy
as np
from PIL
import Image
import matplotlib
.pyplot
as plt
import matplotlib
.cm
as cm
import scipy
.signal
as signal
import cv2
as cv
import random
import easygui
as g
import imutils
import time
class Point(object):
def __init__(self
,x
,y
):
self
.x
= x
self
.y
= y
def getX(self
):
return self
.x
def getY(self
):
return self
.y
def criterion(p
):
if p
== 1:
connect
= [Point
(-1,-1),Point
(-1,0),Point
(0,-1),Point
(0,1),Point
(1,1),Point
(1,0),Point
(-1,1),Point
(1,-1)]
else:
connect
= [Point
(-1,0),Point
(0,-1),Point
(0,1),Point
(1,0)]
return connect
def gray_distance(image
,point1
,point2
):
return abs(int(image
[point1
.x
,point1
.y
])-int(image
[point2
.x
,point2
.y
]))
def seed_growing(image
):
thresh
= 3
label1
= 1
seed
= [Point
(250,100),Point
(82,75),Point
(20,300)]
image
= image
[:, :, 0] * 0.11 + image
[:, :, 1] * 0.59 + image
[:, :, 2] * 0.3
image
= image
.astype
(np
.uint8
)
rows
= image
.shape
[0]
cols
= image
.shape
[1]
image_mark
= np
.full
((rows
,cols
),255)
seedlist
= []
p
=1
connects
= criterion
(p
)
for i
in seed
:
seedlist
.append
(i
)
while ( len(seedlist
) > 0):
seed_testing
= seedlist
.pop
(0)
image_mark
[seed_testing
.x
,seed_testing
.y
] = label1
for i
in range(8):
tempX
= seed_testing
.x
+ connects
[i
].x
tempY
= seed_testing
.y
+ connects
[i
].y
if tempX
< 0 or tempY
< 0 or tempX
>=rows
or tempY
>= cols
:
continue
gray_dis
= gray_distance
(image
,seed_testing
,Point
(tempX
,tempY
))
if gray_dis
< thresh
and image_mark
[tempX
,tempY
] == 255:
seedlist
.append
(Point
(tempX
,tempY
))
image_mark
[tempX
,tempY
] = label1
cv
.imshow
('seed grow',image_mark
.astype
(np
.uint8
))
cv
.waitKey
(0)
def nothing(x
):
pass
def change_number(image
):
image
= image
[:, :, 0] * 0.11 + image
[:, :, 1] * 0.59 + image
[:, :, 2] * 0.3
image
= image
.astype
(np
.uint8
)
rows
= image
.shape
[0]
cols
= image
.shape
[1]
min_area
= 0
max_area
= 0
area
= rows
* cols
cv
.namedWindow
('could change threshhold')
cv
.createTrackbar
('intensity', 'could change threshhold', 0, 255, nothing
)
count
= 0
data1
= 699
data
= 0
while (1):
cv
.imshow
('could change threshhold', image
)
medium_number
= cv
.getTrackbarPos
('intensity', 'could change threshhold')
image2
=image
.copy
()
for i
in range(rows
):
for j
in range(cols
):
if int(image2
[i
, j
]) < medium_number
:
image2
[i
, j
] = 0
min_area
+= 1
else:
image2
[i
, j
] = 255
max_area
+= 1
image2
= image2
.astype
(np
.uint8
)
cv
.imshow
('image2',image2
)
data
+=1
if data
==8:
string
= 'gray area is {},white area is {}'.format(min_area
* area
/ (min_area
+ max_area
),max_area
* area
/ (min_area
+ max_area
))
print(string
)
data
= 0
if cv
.waitKey
(1) == ord('q'):
break
cv
.destroyAllWindows
()
def static_number(image
):
image
= image
[:, :, 0] * 0.11 + image
[:, :, 1] * 0.59 + image
[:, :, 2] * 0.3
image
= image
.astype
(np
.uint8
)
rows
= image
.shape
[0]
cols
= image
.shape
[1]
sum2
= []
for i
in range(rows
):
for j
in range(cols
):
sum2
.append
(int(image
[i
, j
]))
sum2
.sort
()
medium_number
= sum2
[len(sum2
)//2]
min_area
= 0
max_area
= 0
area
= rows
* cols
for i
in range(rows
):
for j
in range(cols
):
if int(image
[i
,j
]) < medium_number
:
image
[i
,j
] = 0
min_area
+=1
else:
image
[i
,j
] = 255
max_area
+=1
image
= image
.astype
(np
.uint8
)
g
.msgbox
('灰色区域面积为{0},白色面积为{1}'.format(min_area
* area
/(min_area
+max_area
),max_area
* area
/(min_area
+max_area
) ))
cv
.imshow
('static number image',image
)
cv
.waitKey
(0)
def myvar(image
):
image
= image
[:, :, 0] * 0.11 + image
[:, :, 1] * 0.59 + image
[:, :, 2] * 0.3
image
= image
.astype
(np
.uint8
)
rows
= image
.shape
[0]
cols
= image
.shape
[1]
sum1
=[]
for i
in range(rows
):
for j
in range(cols
):
sum1
.append
(int(image
[i
,j
]))
sum_average
= sum(sum1
)/len(sum1
)
var_sum
=[]
for i
in range(rows
):
for j
in range(cols
):
var_sum
.append
(image
[i
,j
]**2/len(sum1
))
var
= sum(var_sum
) - sum_average
**2
return var
def hist_stretch(image
):
r_min
, r_max
= 255, 0
a
=[]
for i
in range(image
.shape
[0]):
for j
in range(image
.shape
[1]):
for k
in range(image
.shape
[2]):
a
.append
(image
[i
,j
,k
])
if image
[i
, j
, k
] > r_max
:
r_max
= image
[i
, j
, k
]
if image
[i
, j
, k
] < r_min
:
r_min
= image
[i
, j
, k
]
a
=np
.array
(a
).reshape
(-1)
a_var
=np
.var
(a
)
r1
, s1
= r_min
, 0
r2
, s2
= r_max
, 255
k2
= (s2
- s1
) / (r2
- r1
)
b
=[]
precewise_img
= np
.zeros
((image
.shape
[0], image
.shape
[1], 3), dtype
=np
.float32
)
for i
in range(image
.shape
[0]):
for j
in range(image
.shape
[1]):
for k
in range(image
.shape
[2]):
precewise_img
[i
, j
, k
] = k2
* (image
[i
, j
, k
] - r1
)
b
.append
(precewise_img
[i
,j
,k
])
b
= np
.array
(b
).reshape
(-1,1)
b_var
= np
.var
(b
)
print(a
)
print(b
)
cv
.normalize
(precewise_img
, precewise_img
, 0, 255, cv
.NORM_MINMAX
)
precewise_img
= cv
.convertScaleAbs
(precewise_img
)
g
.msgbox
('处理前的图片方差为{one},处理后的方差为{two}'.format(one
=myvar
(image
), two
=myvar
(precewise_img
)))
cv
.imshow
('origin image', imutils
.resize
(image
, 480))
cv
.imshow
('hist_stretch image', imutils
.resize
(precewise_img
, 480))
if cv
.waitKey
(0) == 27:
cv
.destroyAllWindows
()
def muti_liner_stretch(image
):
r1
, s1
= 50,100
r2
, s2
= 170,200
k1
= s1
/ r1
k3
= (255 - s2
) / (255 - r2
)
k2
= (s2
- s1
) / (r2
- r1
)
precewise_img
= np
.zeros
((image
.shape
[0], image
.shape
[1], 3), dtype
=np
.float32
)
for i
in range(image
.shape
[0]):
for j
in range(image
.shape
[1]):
for k
in range(image
.shape
[2]):
if r1
<= image
[i
, j
, k
] <= r2
:
precewise_img
[i
, j
, k
] = k2
* (image
[i
, j
, k
] - r1
)
elif image
[i
, j
, k
] < r1
:
precewise_img
[i
, j
, k
] = k1
* image
[i
, j
, k
]
elif image
[i
, j
, k
] > r2
:
precewise_img
[i
, j
, k
] = k3
* (image
[i
, j
, k
] - r2
)
cv
.normalize
(precewise_img
, precewise_img
, 0, 255, cv
.NORM_MINMAX
)
precewise_img
= cv
.convertScaleAbs
(precewise_img
)
g
.msgbox
('处理前的图片方差为{one},处理后的方差为{two}'.format(one
=myvar
(image
),two
=myvar
(precewise_img
)))
cv
.imshow
('origin image', imutils
.resize
(image
, 480))
cv
.imshow
('muti_liner_stretch image', imutils
.resize
(precewise_img
, 480))
if cv
.waitKey
(0) == 27:
cv
.destroyAllWindows
()
def medium_filter(image
):
image
= image
[:, :, 0] * 0.11 + image
[:, :, 1] * 0.59 + image
[:, :, 2] * 0.3
image
= image
.astype
(np
.uint8
)
rows
=image
.shape
[0]
cols
= image
.shape
[1]
gray_data
= image
.copy
()
img_new
= []
for i
in range(rows
-3):
line
= []
for j
in range(cols
-3):
a
= gray_data
[i
:i
+3,j
:j
+3]
a
=np
.array
(a
)
a
=np
.sort
(a
.reshape
(-1))
line
.append
(a
[4])
img_new
.append
(line
)
image2
=np
.array
(img_new
)
image2
= (image2
/ float(image2
.max())) * 255
plt
.subplot
(2,1,1)
plt
.title
('original image')
plt
.imshow
(image
,cmap
=cm
.gray
)
plt
.axis
("off")
plt
.subplot
(2,1,2)
plt
.title
('after medium image')
plt
.imshow
(image2
,cmap
=cm
.gray
)
plt
.axis
("off")
plt
.show
()
def PepperandSalt(image
,percentage
):
img_gray2
= image
[:, :, 0] * 0.11 + image
[:, :, 1] * 0.59 + image
[:, :, 2] * 0.3
img_gray2
= img_gray2
.astype
(np
.uint8
)
NoiseImg
=img_gray2
rows
,cols
=NoiseImg
.shape
NoiseNum
=int(percentage
*rows
*cols
)
for i
in range(NoiseNum
):
randX
=np
.random
.randint
(0,rows
)
randY
=np
.random
.randint
(0,cols
)
if random
.randint
(0,1) == 0:
NoiseImg
[randX
,randY
]=0
else:
NoiseImg
[randX
,randY
]=255
cv
.imshow
('Peppernoise image', NoiseImg
)
cv
.waitKey
(1000)
def GaussianNoise(image
,mean
,sigma
):
img_gray2
= image
[:, :, 0] * 0.11 + image
[:, :, 1] * 0.59 + image
[:, :, 2] * 0.3
img_gray2
= img_gray2
.astype
(np
.uint8
)
NoiseImg
=img_gray2
rows
= NoiseImg
.shape
[0]
cols
= NoiseImg
.shape
[1]
rows
,cols
=NoiseImg
.shape
for i
in range(rows
):
for j
in range(cols
):
NoiseImg
[i
,j
]=NoiseImg
[i
,j
]+random
.gauss
(mean
,sigma
)
if NoiseImg
[i
,j
]<0:
NoiseImg
[i
,j
] = 0
elif NoiseImg
[i
,j
]>255:
NoiseImg
[i
,j
] = 255
cv
.imshow
('guasenoise image', NoiseImg
)
cv
.waitKey
(1000)
def salt(image1
,number
):
image
= image1
.copy
()
rows
= image
.shape
[0]
cols
= image
.shape
[1]
for i
in range(number
):
x
=np
.random
.randint
(0,rows
)
y
=np
.random
.randint
(0,cols
)
c
=random
.randint
(0,1)
if c
== 1:
image
[x
,y
] = 255
else:
image
[x
,y
] = 0
return image
def convolution(kernal_size
, image
):
rows
=image
.shape
[0]
cols
= image
.shape
[1]
gray_data
= image
.copy
()
img_new
= []
for i
in range(rows
-3):
line
= []
for j
in range(cols
-3):
a
= gray_data
[i
:i
+3,j
:j
+3]
a
=np
.array
(a
)
line
.append
(np
.sum(np
.multiply
(kernal_size
, a
)))
img_new
.append
(line
)
return np
.array
(img_new
)
def mean_image(image
):
suanzi
= np
.ones
((3,3))/9
image
= image
[:, :, 0] * 0.11 + image
[:, :, 1] * 0.59 + image
[:, :, 2] * 0.3
image
= image
.astype
(np
.uint8
)
image2
= convolution
(image
=image
,kernal_size
=suanzi
)
image2
= (image2
/float(image2
.max()))*255
image3
=cv
.blur
(image
,(5,5))
plt
.subplot
(3,1,1)
plt
.title
('original image')
plt
.imshow
(image
,cmap
=cm
.gray
)
plt
.axis
("off")
plt
.subplot
(3,1,2)
plt
.title
('after meaning image')
plt
.imshow
(image2
,cmap
=cm
.gray
)
plt
.axis
("off")
plt
.subplot
(3, 1, 3)
plt
.title
('function made')
plt
.imshow
(image3
, cmap
=cm
.gray
)
plt
.axis
("off")
plt
.show
()
def func(x
,y
,sigma
=1):
return 100*(1/(2*np
.pi
*sigma
))*np
.exp
(-((x
-1)**2+(y
-1)**2)/(2.0*sigma
**2))
def gause_image(image
):
suanzi
= np
.fromfunction
(func
,(3,3),sigma
=2)
image
= image
[:, :, 0] * 0.11 + image
[:, :, 1] * 0.59 + image
[:, :, 2] * 0.3
image
= image
.astype
(np
.uint8
)
image2
= convolution
(image
=image
, kernal_size
=suanzi
)
image2
= (image2
/ float(image2
.max())) * 255
plt
.subplot
(2, 1, 1)
plt
.title
('original image')
plt
.imshow
(image
, cmap
=cm
.gray
)
plt
.axis
("off")
plt
.subplot
(2, 1, 2)
plt
.title
('after gause image')
plt
.imshow
(image2
, cmap
=cm
.gray
)
plt
.axis
("off")
plt
.show
()
if __name__
== '__main__':
msg
= "请输入您想要完成的任务(建议您第一步先打开图片)"
title
= '第二次作业'
choice
= ('打开图片', '退出')
a
= g
.buttonbox
(msg
=msg
, title
=title
, choices
=choice
)
if a
== '打开图片':
filename
= g
.fileopenbox
(msg
="请打开一个jpg文件")
img
= cv
.imread
(filename
)
msg1
= "选择您想要实现的功能"
title1
= '第二次作业'
choice1
= ('显示噪声图', '滤波', '阈值分割', '分段线性法拉伸', '直方图拉伸', '区域生长法分割','重新选择图片','退出')
q
= 1
while q
:
b
= g
.buttonbox
(msg
=msg1
, title
=title1
, choices
=choice1
)
if b
== '显示噪声图':
msg2
= "选择您想要实现的功能"
title2
= '第二次作业'
choice2
= ('灰色椒盐噪声图', '灰色高斯噪声图','退出')
q1
=1
while q1
:
noise_image_choice
= g
.buttonbox
(msg
=msg2
, title
=title2
, choices
=choice2
)
if noise_image_choice
== '灰色椒盐噪声图':
PepperandSalt
(img
, percentage
=0.01)
elif noise_image_choice
== '灰色高斯噪声图':
GaussianNoise
(img
, mean
=2, sigma
=14)
else:
q1
=0
elif b
== '滤波':
msg_b
= "选择您想要实现的功能"
title_b
= '第二次作业'
choice_b
= ('均值滤波', '高斯滤波','中值滤波')
q_b
= 1
while q_b
:
b_remove_noise
= g
.buttonbox
(msg
=msg_b
, title
=title_b
, choices
=choice_b
)
if b_remove_noise
== '均值滤波':
mean_image
(salt
(img
,number
=5000))
elif b_remove_noise
=='高斯滤波':
gause_image
(salt
(img
,number
=5000))
elif b_remove_noise
== '中值滤波':
medium_filter
(salt
(img
,number
=5000))
else:
q_b
= 0
elif b
== '阈值分割':
msg_b1
= "选择您想要实现的功能"
title_b1
= '第二次作业'
choice_b1
= ('固定阈值', '调节参数窗')
q_b1
= 1
while q_b1
:
b_remove_noise1
= g
.buttonbox
(msg
=msg_b1
, title
=title_b1
, choices
=choice_b1
)
if b_remove_noise1
== '固定阈值':
static_number
(img
)
elif b_remove_noise1
== '调节参数窗':
change_number
(img
)
else:
q_b1
= 0
elif b
== '分段线性法拉伸':
muti_liner_stretch
(img
)
elif b
== '直方图拉伸':
hist_stretch
(img
)
elif b
== '区域生长法分割':
seed_growing
(img
)
elif b
== '重新选择图片':
filename
= g
.fileopenbox
(msg
="请打开一个jpg文件")
img
= cv
.imread
(filename
)
else:
q
= 0
```python
在这里插入代码片
转载请注明原文地址: https://lol.8miu.com/read-24461.html