Python表格识别
图像识别具有较高的商业价值,本节主要通过python调用(百度云、腾讯云)API接口表格识别并保存为excel分析表格识别的能力;
提示:需分别申请密钥,在相应位置添加自己密钥即可;
文章目录
- Python表格识别
- 前言
- 一、图像识别应用分析
- 二、百度云表格识别测试
- 三、腾讯云表格识别测试
- 总结
前言
一、图像识别应用分析
背景:
1、现场每天有大量的手工报表需要汇总;
2、人员手动将报表录入电脑耗费大量时间;
3、在信息量非常大的时代,图片、PDF等格式的信息占很大部分,但是我们不能直接提取其中的信息;
近年来,在深度学习的加持下,OCR(Optical Character Recognition,光学字符识别)的可用性不断提升,大量用户借助OCR软件,从图片中提取文本信息。然而对于表格场景,应用还未普及。
步骤:
1、通过高拍仪或扫描仪拍照;
2、读入图片灰度化(将彩色图片变为灰色图片);
3、图片二值化(将图片变为只有黑白两种颜色);
4、识别出表格的横线、竖线(如果图片不够清晰可以加入腐蚀、膨胀等);
5、得到横竖线的交点,进而得到单元格坐标;
6、通过坐标提取单元格图像,进而用pytesseract识别文字;
7、将得到的信息写入excel;
二、百度云表格识别测试
通过调用百度云识别指定文件夹下所有图片表格,将图片内容输出为excel文本格式,并将输出文件保存到指定文件夹下。
腾讯云:https://cloud.baidu.com/
# encoding: utf-8
import os
import sys
import requests
import time
import tkinter as tk
from tkinter import filedialog
from aip import AipOcr
#代码运行环境: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 = 0
for 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 += 1
print ('{0} : {1} 下载完成。'.format(num, xls_name))
time.sleep(1)
三、腾讯云表格识别测试
通过调用腾讯云识别指定文件夹下所有图片表格,将图片内容输出为excel文本格式,并将输出文件保存到指定文件夹下。
代码如下(示例):
# from PIL import Image
# import pytesseract
##导入通用包
import numpy as np
import pandas as pd
import os
import json
import re
import base64
import xlwings as xw
##导入腾讯AI api
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 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 = "ocr.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = 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)
##提取识别出的数据,并且生成json
result1 = 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 + "的提取.")
总结