因為注釋給的很詳細,所以直接給代碼:
1 from PIL import Image 2 import numpy as np 3 # 二值化處理 4 5 6 def 二值化處理(image): 7 for i in range(1, 5): 8 # 灰度圖 9 lim = image.convert('L') 10 # 灰度閾值設為165,低於這個值的點全部填白色 11 threshold = 165 12 table = [] 13 for j in range(256): 14 if j < threshold: 15 table.append(0) 16 else: 17 table.append(1) 18 bim = lim.point(table, '1') 19 return bim 20 def 對黑白圖片進行降噪(im): 21 # 圖像二值化 22 data = im.getdata() 23 w, h = im.size 24 black_point = 0 25 for x in range(1, w - 1): 26 for y in range(1, h - 1): 27 mid_pixel = data[w * y + x] # 中央像素點像素值 28 if mid_pixel < 50: # 找出上下左右四個方向像素點像素值 29 top_pixel = data[w * (y - 1) + x] 30 left_pixel = data[w * y + (x - 1)] 31 down_pixel = data[w * (y + 1) + x] 32 right_pixel = data[w * y + (x + 1)] 33 # 判斷上下左右的黑色像素點總個數 34 if top_pixel < 10: 35 black_point += 1 36 if left_pixel < 10: 37 black_point += 1 38 if down_pixel < 10: 39 black_point += 1 40 if right_pixel < 10: 41 black_point += 1 42 if black_point < 1: 43 im.putpixel((x, y), 255) 44 # print(black_point) 45 black_point = 0 46 return im 47 48 def 邊緣黑像素(im): 49 # 去除干擾線 50 51 # 圖像二值化 52 data = im.getdata() 53 w, h = im.size 54 black_point = 0 55 for x in range(1, w - 1): 56 for y in range(1, h - 1): 57 if x < 2 or y < 2: 58 im.putpixel((x - 1, y - 1), 255) 59 if x > w - 3 or y > h - 3: 60 im.putpixel((x + 1, y + 1), 255) 61 return im 62 def 處理照片(image): 63 im_1=二值化處理(image) 64 im_2=對黑白圖片進行降噪(im_1) 65 im_3=邊緣黑像素(im_2) 66 return im_3 67 68 def 切圖片(im): 69 gray = im.convert('L') 70 (x, y) = gray.size # read image size 71 x_s = 28 # define standard width 72 y_s = 28 # calc height based on standard width 73 out = gray.resize((x_s, y_s), Image.ANTIALIAS) # resize image with high-quality 74 return out 75 def 轉array(im): 76 im2 = 1 - np.array(im) / 255 77 print(im2) 78 print(im2.shape) 79 return im2 80 def GET_true_img(url_name): 81 image = Image.open('../data/test/'+url_name+'.png') 82 im_1=處理照片(image) 83 im_1.save("../data/test/去噪/"+url_name+"_out_處理.png") 84 im_2=切圖片(im_1) 85 im_2.save("../data/test/去噪/"+url_name+"_out.png") 86 im_narray=轉array(im_2) 87 88 return im_narray 89 if __name__ =='__main__': 90 image = Image.open('../data/test/8.png') 91 im_1=處理照片(image) 92 im_1.save("../data/test/去噪/8_out_處理.png") 93 im_2=切圖片(im_1) 94 im_2.save("../data/test/去噪/8_out.png") 95 im_narray=轉array(im_2)
處理前
處理后:
轉型后: