失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python调用(百度云 腾讯云)API接口表格识别并保存为excel

python调用(百度云 腾讯云)API接口表格识别并保存为excel

时间:2021-05-27 17:38:03

相关推荐

python调用(百度云 腾讯云)API接口表格识别并保存为excel

Python表格识别

图像识别具有较高的商业价值,本节主要通过python调用(百度云、腾讯云)API接口表格识别并保存为excel分析表格识别的能力;


提示:需分别申请密钥,在相应位置添加自己密钥即可;

文章目录

Python表格识别前言一、图像识别应用分析二、百度云表格识别测试三、腾讯云表格识别测试总结

前言


提示:以下是本篇文章正文内容,下面案例可供参考

一、图像识别应用分析

背景:

1、现场每天有大量的手工报表需要汇总;

2、人员手动将报表录入电脑耗费大量时间;

3、在信息量非常大的时代,图片、PDF等格式的信息占很大部分,但是我们不能直接提取其中的信息;

近年来,在深度学习的加持下,OCR(Optical Character Recognition,光学字符识别)的可用性不断提升,大量用户借助OCR软件,从图片中提取文本信息。然而对于表格场景,应用还未普及。

步骤:

1、通过高拍仪或扫描仪拍照;

2、读入图片灰度化(将彩色图片变为灰色图片);

3、图片二值化(将图片变为只有黑白两种颜色);

4、识别出表格的横线、竖线(如果图片不够清晰可以加入腐蚀、膨胀等);

5、得到横竖线的交点,进而得到单元格坐标;

6、通过坐标提取单元格图像,进而用pytesseract识别文字;

7、将得到的信息写入excel;

二、百度云表格识别测试

通过调用百度云识别指定文件夹下所有图片表格,将图片内容输出为excel文本格式,并将输出文件保存到指定文件夹下。

腾讯云:/

# encoding: utf-8import osimport sysimport requestsimport timeimport tkinter as tkfrom tkinter import filedialogfrom aip import AipOcr#转载来源#/mrlayfolk/p/12630128.html#代码运行环境:win10 python3.7#需要aip库,使用pip install baidu-aip即可# 定义常量APP_ID = 'APP_ID'API_KEY = 'API_KEY'SECRET_KEY = 'SECRET_KEY'# 初始化AipFace对象client = AipOcr(APP_ID, API_KEY, SECRET_KEY)# 读取图片def get_file_content(filePath):with open(filePath, 'rb') as fp:return fp.read()#文件下载函数def file_download(url, file_path):r = requests.get(url)with open(file_path, 'wb') as f:f.write(r.content)if __name__ == "__main__":root = tk.Tk()root.withdraw()data_dir = filedialog.askdirectory(title='请选择图片文件夹') + '/'result_dir = filedialog.askdirectory(title='请选择输出文件夹') + '/'num = 0for name in os.listdir(data_dir):print ('{0} : {1} 正在处理:'.format(num+1, name.split('.')[0]))image = get_file_content(os.path.join(data_dir, name))res = client.tableRecognitionAsync(image)# print ("res:", res)if 'error_code' in res.keys():print ('Error! error_code: ', res['error_code'])sys.exit()req_id = res['result'][0]['request_id'] #获取识别ID号for count in range(1, 20): #OCR识别也需要一定时间,设定10秒内每隔1秒查询一次res = client.getTableRecognitionResult(req_id) #通过ID获取表格文件XLS地址print(res['result']['ret_msg'])if res['result']['ret_msg'] == '已完成':break #云端处理完毕,成功获取表格文件下载地址,跳出循环else:time.sleep(1)url = res['result']['result_data']xls_name = name.split('.')[0] + '.xls'file_download(url, os.path.join(result_dir, xls_name))num += 1print ('{0} : {1} 下载完成。'.format(num, xls_name))time.sleep(1)

三、腾讯云表格识别测试

通过调用腾讯云识别指定文件夹下所有图片表格,将图片内容输出为excel文本格式,并将输出文件保存到指定文件夹下。

腾讯云:/

代码如下(示例):

# from PIL import Image# import pytesseract##导入通用包import numpy as npimport pandas as pdimport osimport jsonimport reimport base64import xlwings as xw##导入腾讯AI apifrom mon import credentialfrom mon.profile.client_profile import ClientProfilefrom mon.profile.http_profile import HttpProfilefrom mon.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom tencentcloud.ocr.v1119 import ocr_client, models#定义函数def excelFromPictures(picture,SecretId,SecretKey):try:with open(picture,"rb") as f:img_data = f.read()img_base64 = base64.b64encode(img_data)cred = credential.Credential(SecretId, SecretKey) #ID和Secret从腾讯云申请httpProfile = HttpProfile()httpProfile.endpoint = ""clientProfile = ClientProfile()clientProfile.httpProfile = httpProfileclient = ocr_client.OcrClient(cred, "ap-shanghai", clientProfile)req = models.TableOCRRequest()params = '{"ImageBase64":"' + str(img_base64, 'utf-8') + '"}'req.from_json_string(params)resp = client.TableOCR(req)#print(resp.to_json_string())except TencentCloudSDKException as err:print(err)##提取识别出的数据,并且生成jsonresult1 = json.loads(resp.to_json_string())rowIndex = []colIndex = []content = []for item in result1['TextDetections']:rowIndex.append(item['RowTl'])colIndex.append(item['ColTl'])content.append(item['Text'])##导出Excel##ExcelWriter方案rowIndex = pd.Series(rowIndex)colIndex = pd.Series(colIndex)index = rowIndex.unique()index.sort()columns = colIndex.unique()columns.sort()data = pd.DataFrame(index = index, columns = columns)for i in range(len(rowIndex)):data.loc[rowIndex[i],colIndex[i]] = re.sub(" ","",content[i])writer = pd.ExcelWriter("../tables/" + re.match(".*\.",f.name).group() + "xlsx", engine='xlsxwriter')data.to_excel(writer,sheet_name = 'Sheet1', index=False,header = False)writer.save()#xlwings方案 # wb = xw.Book()# sht = wb.sheets('Sheet1')# for i in range(len(rowIndex)):#sht[rowIndex[i],colIndex[i]].value = re.sub(" ",'',content[i])# wb.save("../tables/" + re.match(".*\.",f.name).group() + "xlsx")# wb.close()if not ('tables') in os.listdir():os.mkdir("./tables/")os.chdir("./image2/")pictures = os.listdir()for pic in pictures:excelFromPictures(pic,"SecretId","SecretKey")print("已经完成" + pic + "的提取.")


总结

有不对的地方希望大家可以评论留言,帮助大家不迷路!!

期待大家的加入,一起学习,一起交流!!。

如果觉得《python调用(百度云 腾讯云)API接口表格识别并保存为excel》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。