因为注释给的很详细,所以直接给代码:
1 from PIL import Image
2 # 二值化处理
3
4
5 def 二值化处理(image):
6 for i in range(1, 5):
7 # 灰度图
8 lim = image.convert('L')
9 # 灰度阈值设为165,低于这个值的点全部填白色
10 threshold = 165
11 table = []
12 for j in range(256):
13 if j < threshold:
14 table.append(0)
15 else:
16 table.append(1)
17 bim = lim.point(table, '1')
18 return bim
19 def 对黑白图片进行降噪(im):
20 # 图像二值化
21 data = im.getdata()
22 w, h = im.size
23 black_point = 0
24 for x in range(1, w - 1):
25 for y in range(1, h - 1):
26 mid_pixel = data[w * y + x] # 中央像素点像素值
27 if mid_pixel < 50: # 找出上下左右四个方向像素点像素值
28 top_pixel = data[w * (y - 1) + x]
29 left_pixel