python读取图片文字为表格_python-使用百度AipOcr实现表格文字图片识别

代码运行环境: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)实现效果

识别的表格图片为:

1078885-20200404012744780-1724546907.png

实现的效果为(注:表格的格式人为调整过,但内容没人为修改):

1078885-20200404012856765-1966182948.png

可以看出,识别的精度还是很高的,只有“Fellow”识别为了“Fel1low”。

(4)其它

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值