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
| def his_equ(img, outfile,level=256,mode='RGB'):
'''
:param img: Image.open打开的文件句柄
:param outfile: 输出文件的文件名
:param level:灰度等级,彩色图是每个通道对应的等级数
:param mode:'rgb'为彩色模式,'gray'为灰度图
:return: 按照输出文件路径保存均衡化之后的图片
'''
if mode == 'RGB' or mode == 'rgb':
r, g, b = [], [], []
width, height = img.size[0], img.size[1]
sum_pix = width * height
pix = img.load()
for x in range(width):
for y in range(height):
r.append(pix[x, y][0])
g.append(pix[x, y][1])
b.append(pix[x, y][2])
r_c = dict(Counter(r))
g_c = dict(Counter(g))
b_c = dict(Counter(b))
r_p,g_p,b_p = [],[],[]
for i in range(level):
if r_c.has_key(i):
r_p.append(float(r_c[i]) / sum_pix)
else:
r_p.append(0)
if g_c.has_key(i):
g_p.append(float(g_c[i])/sum_pix)
else:
g_p.append(0)
if b_c.has_key(i):
b_p.append(float(b_c[i])/sum_pix)
else:
b_p.append(0)
temp_r,temp_g,temp_b = 0,0,0
for i in range(level):
temp_r += r_p[i]
r_p[i] = int(temp_r * (level-1))
temp_b += b_p[i]
b_p[i] = int(temp_b *(level-1))
temp_g += g_p[i]
g_p[i] = int(temp_g*(level -1))
new_photo = Image.new('RGB',(width,height))
for x in range(width):
for y in range(height):
new_photo.putpixel((x,y),(r_p[pix[x,y][0]],g_p[pix[x,y][1]],b_p[pix[x,y][2]]))
new_photo.save(outfile)
elif mode == 'gray' or mode == 'GRAY':
width, height = img.size[0], img.size[1]
sum_pix = width * height
pix = img.load()
pb = []
for x in range(width):
for y in range(height):
pb.append(pix[x,y])
pc = dict(Counter(pb))
pb = []
for i in range(level):
if pc.has_key(i):
pb.append(float(pc[i]) / sum_pix)
else:
pb.append(0)
temp = 0
for i in range(level):
temp += pb[i]
pb[i] = int(temp * (level-1))
new_photo = Image.new('L',(width,height))
for x in range(width):
for y in range(height):
new_photo.putpixel((x,y),pb[pix[x,y]])
new_photo.save(outfile)
if __name__ == '__main__':
ppp = Image.open('Lena.jpg','r')
his_equ(ppp,'lena_his.jpg')
|