因为注释给的很详细,所以直接给代码:
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 = data[w * y + (x - 1)] 30 down_pixel = data[w * (y + 1) + x] 31 right_pixel = data[w * y + (x + 1)] 32 # 判断上下左右的黑色像素点总个数 33 if top_pixel < 10: 34 black_point += 1 35 if left_pixel < 10: 36 black_point += 1 37 if down_pixel < 10: 38 black_point += 1 39 if right_pixel < 10: 40 black_point += 1 41 if black_point < 1: 42 im.putpixel((x, y), 255) 43 # print(black_point) 44 black_point = 0 45 return im 46 47 def 边缘黑像素(im): 48 # 去除干扰线 49 50 # 图像二值化 51 data = im.getdata() 52 w, h = im.size 53 black_point = 0 54 for x in range(1, w - 1): 55 for y in range(1, h - 1): 56 if x < 2 or y < 2: 57 im.putpixel((x - 1, y - 1), 255) 58 if x > w - 3 or y > h - 3: 59 im.putpixel((x + 1, y + 1), 255) 60 return im 61 62 if __name__ =='__main__': 63 image = Image.open('../../data/test/8.png') 64 im_1=二值化处理(image) 65 im_2=对黑白图片进行降噪(im_1) 66 im_3=边缘黑像素(im_2) 67 68 im_3.save('../../data/test/8_降噪.png')
处理前
处理后:
转型后:
来源:https://www.cnblogs.com/smartisn/p/12629902.html