图片处理完整流程(包含二值化处理、对黑白照片降噪、边缘去黑像素、三通道转为一通道、图片转array、图片转成任意像素等功能)——可满足一般图片处理要求
因为注释给的很详细,所以直接给代码:
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)
处理前
处理后:
转型后: