应用场景 合同信息提取 在企业的法务部门或商务部门,经常需要处理大量的合同文件。合同中的关键信息(如合同编号、签约日期、双方名称、金额等)通常分布在固定的区域。可以利用上述代码自定义指定图片多个识别区域,精确提取这些关键信息。
要使用 Python 和百度 API 自定义指定图片的多个识别区域,识别文字并保存到 Excel 中,可以按照以下步骤实现:
1. 安装必要的库
sh
pip install baidu-aip pandas pillow
2. 获取百度 OCR API 的密钥
3. 编写 Python 代码
python
from aip import AipOcr
from PIL import Image
import pandas as pd
# 百度OCR API的相关信息
APP_ID = 'your_app_id'
API_KEY = 'your_api_key'
SECRET_KEY = 'your_secret_key'
# 初始化AipOcr对象
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
def recognize_text_in_regions(image_path, regions):
"""
识别指定图片中多个区域的文字
:param image_path: 图片文件路径
:param regions: 识别区域列表,每个区域为一个四元组 (left, top, right, bottom)
:return: 每个区域识别的文字列表
"""
results = []
image = Image.open(image_path)
for region in regions:
left, top, right, bottom = region
# 裁剪图片
cropped_image = image.crop((left, top, right, bottom))
# 将裁剪后的图片保存为临时文件
cropped_image_path = 'temp_cropped_image.jpg'
cropped_image.save(cropped_image_path)
# 读取裁剪后的图片
with open(cropped_image_path, 'rb') as f:
img = f.read()
# 调用百度OCR API进行文字识别
result = client.basicGeneral(img)
# 提取识别结果中的文字
texts = [item['words'] for item in result.get('words_result', [])]
combined_text = ' '.join(texts)
results.append(combined_text)
return results
def save_to_excel(data, output_path):
"""
将识别结果保存到Excel文件中
:param data: 识别结果列表
:param output_path: 输出Excel文件路径
"""
df = pd.DataFrame(data, columns=['识别结果'])
df.to_excel(output_path, index=False)
if __name__ == "__main__":
# 图片文件路径
image_path = 'your_image.jpg'
# 自定义识别区域,每个区域为 (left, top, right, bottom)
regions = [
(100, 100, 300, 200),
(400, 200, 600, 300)
]
# 识别指定区域的文字
recognition_results = recognize_text_in_regions(image_path, regions)
# 保存识别结果到Excel文件
output_excel_path = 'output.xlsx'
save_to_excel(recognition_results, output_excel_path)
print(f"识别结果已保存到 {output_excel_path}")
4. 代码说明
recognize_text_in_regions
函数:该函数接受图片文件路径和识别区域列表作为输入,使用Pillow
库裁剪图片,然后调用百度 OCR API 进行文字识别,最后返回每个区域识别的文字列表。save_to_excel
函数:该函数接受识别结果列表和输出 Excel 文件路径作为输入,使用pandas
库将识别结果保存到 Excel 文件中。- 主程序:指定图片文件路径和识别区域,调用
recognize_text_in_regions
函数进行文字识别,然后调用save_to_excel
函数将识别结果保存到 Excel 文件中。
5. 注意事项
- 请将
your_app_id
、your_api_key
、your_secret_key
替换为你自己的百度 OCR API 的APP ID
、API Key
和Secret Key
。 - 请将
your_image.jpg
替换为你要识别的图片文件路径。 - 识别区域的坐标需要根据实际情况进行调整。