代码运行环境:win10 python3.7
需要aip库,使用pip install baidu-aip即可
(1)目的
通过百度AipOcr库,来实现识别图片中的表格,并输出问表格文件。
(2)实现
1 #encoding: utf-8
2 importos3 importsys4 importrequests5 importtime6 importtkinter as tk7 from tkinter importfiledialog8 from aip importAipOcr9
10 #定义常量
11 APP_ID = 'xxxxxx'
12 API_KEY = 'xxxxxxxxxxxxxxxxxxxxxx'
13 SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
14 #初始化AipFace对象
15 client =AipOcr(APP_ID, API_KEY, SECRET_KEY)16
17 #读取图片
18 defget_file_content(filePath):19 with open(filePath, 'rb') as fp:20 returnfp.read()21
22
23 #文件下载函数
24 deffile_download(url, file_path):25 r =requests.get(url)26 with open(file_path, 'wb') as f:27 f.write(r.content)28
29
30 if __name__ == "__main__":31 root =tk.Tk()32 root.withdraw()33 data_dir = filedialog.askdirectory(title='请选择图片文件夹') + '/'
34 result_dir = filedialog.askdirectory(title='请选择输出文件夹') + '/'
35 num =036 for name inos.listdir(data_dir):37 print ('{0} : {1} 正在处理:'.format(num+1, name.split('.')[0]))38 image =get_file_content(os.path.join(data_dir, name))39 res =client.tableRecognitionAsync(image)40 #print ("res:", res)
41 if 'error_code' inres.keys():42 print ('Error! error_code:', res['error_code'])43 sys.exit()44 req_id = res['result'][0]['request_id'] #获取识别ID号
45
46 for count in range(1, 20): #OCR识别也需要一定时间,设定10秒内每隔1秒查询一次
47 res = client.getTableRecognitionResult(req_id) #通过ID获取表格文件XLS地址
48 print(res['result']['ret_msg'])49 if res['result']['ret_msg'] == '已完成':50 break #云端处理完毕,成功获取表格文件下载地址,跳出循环
51 else:52 time.sleep(1)53
54 url = res['result']['result_data']55 xls_name = name.split('.')[0] + '.xls'
56 file_download(url, os.path.join(result_dir, xls_name))57 num += 1
58 print ('{0} : {1} 下载完成。'.format(num, xls_name))59 time.sleep(1)
(3)实现效果
识别的表格图片为:
实现的效果为(注:表格的格式人为调整过,但内容没人为修改):
可以看出,识别的精度还是很高的,只有“Fellow”识别为了“Fel1low”。
(4)其它