当前位置: 首页 > news >正文

Qianfan-OCR代码实例:Python调用API实现批量PDF图像文字提取

Qianfan-OCR代码实例:Python调用API实现批量PDF图像文字提取

1. 项目概述

Qianfan-OCR是百度千帆推出的开源文档智能多模态模型,基于4B参数的端到端架构设计。相比传统OCR技术,它不仅能识别文字,还能理解文档结构和语义信息。

核心优势

  • 单模型完成OCR+版面分析+文档理解
  • 支持多语言文本识别
  • 开源可商用(Apache 2.0协议)
  • 基于Qwen3-4B语言模型,理解能力强

2. 环境准备

2.1 安装依赖库

pip install requests pillow pypdf2 python-multipart

2.2 服务访问配置

确保Qianfan-OCR服务已启动并运行在本地7860端口:

API_URL = "http://localhost:7860/api/ocr"

3. 基础OCR功能实现

3.1 单张图片文字提取

import requests from PIL import Image import io def ocr_single_image(image_path): with open(image_path, 'rb') as f: files = {'image': f} response = requests.post(API_URL, files=files) if response.status_code == 200: return response.json()['text'] else: raise Exception(f"OCR失败: {response.text}") # 使用示例 result = ocr_single_image('test.jpg') print("识别结果:", result)

3.2 PDF文档批量处理

from PyPDF2 import PdfReader import os def pdf_to_images(pdf_path, output_dir='temp_images'): os.makedirs(output_dir, exist_ok=True) reader = PdfReader(pdf_path) images = [] for i, page in enumerate(reader.pages): for img in page.images: img_path = f"{output_dir}/page_{i}_{img.name}" with open(img_path, "wb") as f: f.write(img.data) images.append(img_path) return images def ocr_pdf(pdf_path): image_paths = pdf_to_images(pdf_path) results = [] for img_path in image_paths: try: text = ocr_single_image(img_path) results.append(text) except Exception as e: print(f"处理{img_path}时出错:", str(e)) return "\n\n".join(results)

4. 进阶功能实现

4.1 带布局分析的OCR

def ocr_with_layout(image_path): data = { 'enable_layout': 'true' } with open(image_path, 'rb') as f: files = {'image': f} response = requests.post(API_URL, files=files, data=data) if response.status_code == 200: return response.json() else: raise Exception(f"带布局OCR失败: {response.text}") # 使用示例 layout_result = ocr_with_layout('document.jpg') print("标题:", layout_result['title']) print("正文:", layout_result['content']) print("表格:", layout_result['tables'])

4.2 定向信息提取

def extract_specific_info(image_path, prompt): data = { 'prompt': prompt } with open(image_path, 'rb') as f: files = {'image': f} response = requests.post(API_URL, files=files, data=data) if response.status_code == 200: return response.json() else: raise Exception(f"定向提取失败: {response.text}") # 使用示例:提取发票关键信息 invoice_info = extract_specific_info( 'invoice.jpg', '请提取发票中的以下信息:发票号码、开票日期、金额(大写)、金额(小写)。以JSON格式返回' ) print(invoice_info)

5. 批量处理实战案例

5.1 批量处理文件夹内PDF

import glob def batch_process_pdfs(folder_path, output_dir='results'): os.makedirs(output_dir, exist_ok=True) pdf_files = glob.glob(f"{folder_path}/*.pdf") for pdf in pdf_files: try: filename = os.path.basename(pdf).replace('.pdf', '.txt') output_path = f"{output_dir}/{filename}" text = ocr_pdf(pdf) with open(output_path, 'w', encoding='utf-8') as f: f.write(text) print(f"已处理: {pdf} -> {output_path}") except Exception as e: print(f"处理{pdf}时出错:", str(e))

5.2 结果后处理与保存

def save_structured_results(results, output_format='markdown'): if output_format == 'markdown': with open('output.md', 'w', encoding='utf-8') as f: for item in results: f.write(f"## {item['title']}\n\n") f.write(f"{item['content']}\n\n") if item['tables']: f.write("### 表格\n\n") f.write(item['tables'] + "\n\n") elif output_format == 'json': import json with open('output.json', 'w', encoding='utf-8') as f: json.dump(results, f, ensure_ascii=False, indent=2)

6. 性能优化建议

6.1 多线程处理

from concurrent.futures import ThreadPoolExecutor def parallel_ocr(image_paths, max_workers=4): with ThreadPoolExecutor(max_workers=max_workers) as executor: results = list(executor.map(ocr_single_image, image_paths)) return results

6.2 图像预处理

from PIL import Image, ImageEnhance def preprocess_image(image_path): img = Image.open(image_path) # 增强对比度 enhancer = ImageEnhance.Contrast(img) img = enhancer.enhance(1.5) # 转换为灰度图 img = img.convert('L') # 保存预处理后的图像 processed_path = f"processed_{os.path.basename(image_path)}" img.save(processed_path) return processed_path

7. 总结

通过本教程,我们实现了:

  1. 基础OCR功能:单张图片文字提取
  2. PDF处理能力:批量转换PDF为文本
  3. 高级功能应用:布局分析和定向信息提取
  4. 批量处理方案:文件夹批量处理和结果保存
  5. 性能优化技巧:多线程和图像预处理

Qianfan-OCR相比传统OCR方案的优势在于:

  • 端到端处理,无需多模型串联
  • 理解文档语义结构
  • 支持自然语言指令
  • 开源可商用,部署简单

获取更多AI镜像

想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。

http://www.jsqmd.com/news/706381/

相关文章:

  • 终极指南:ComfyUI-Manager依赖安装的完整解决方案与性能优化
  • Venera漫画阅读器:从入门到精通的完整使用手册
  • BabyAGI 架构详解
  • 手把手教你完成OpenClaw飞书绑定(含最新版安装包)
  • 导航参数的精细化管理
  • 机器学习中类别特征编码的3种核心方法与选择策略
  • 多智能体强化学习论文资源导航:从入门到精通的学术地图
  • OpenEuler文件被锁定的解决方法|网卡修改不生效的解决办法
  • 2.9 会话、窗口站、桌面和窗口消息:图形界面背后的“分层舞台”
  • MCP 2026适配不是选型问题,而是生存问题:2026Q2起未达标设备将被禁止接入省级工业互联网平台
  • Kubernetes v1.24 高可用集群安装教程(基于 containerd + Flannel)
  • C语言进阶篇(文件操作)
  • 基于多模态大模型与智能体协作的像素艺术生成技术实践
  • 设备检测库device-detector:从UA解析到精细化运营的实战指南
  • 2026年人力资源数据分析的技术价值与应用前景
  • 第五章-05-练习案例:升级版自动查核酸
  • 2015-2025年地级市公共安全基建省内横向压力
  • 2026专业户外路灯TOP5推荐:LED路灯、乡村路灯、农村太阳能路灯、太阳能路灯安装、太阳能路灯工厂、太阳能路灯批发选择指南 - 优质品牌商家
  • WebCanvas:可视化AI工作流引擎的设计与实现
  • Windows更改远程桌面3389端口
  • 基于Node.js与Vue 3的轻量级服务器监控仪表盘实战
  • 安装OpenCV-Python 3.4.1.15和opencv-contrib-python 3.4.1.15,并将anaconda prompt创建的python3.6虚拟环境加到pycharm中
  • AI应用开发实战指南:从架构设计到生产部署的完整路径
  • 2026义乌正规诉讼律师机构名录:义乌离婚诉讼咨询、义乌诉讼律师公司、义乌刑事离婚律师、义乌律师公司、义乌离婚律师公司选择指南 - 优质品牌商家
  • 【SSD202 开发实战 18】JPEG 编解码与图片处理
  • 2026年3月优秀的机器人第七轴源头厂家推荐,车铣复合机自动化上下料核心设备/压铸机械手,机器人第七轴源头厂家哪家靠谱 - 品牌推荐师
  • LLM应用开发工具全景指南:从RAG到智能体的高效选型与实践
  • 稀疏矩阵在机器学习中的高效应用与优化技巧
  • 时间序列分析:自相关与偏自相关函数详解
  • AI Agent 面试题 014:Agent的动作空间(Action Space)设计有哪些最佳实践?