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

【Ollama】本地OCR

文章目录

  • 1. 简述
  • 2. python简单实现

1. 简述

利用ollama的API接口访问qwen2.5vl,提供提示词和图片,返回提取后的文字/公式,实现本地OCR功能。

2. python简单实现

import base64
import requests
import jsondef image_to_base64(image_path):"""将图像文件转换为 base64 编码字符串"""with open(image_path, "rb") as image_file:# 读取图像并转换为 base64 编码base64_str = base64.b64encode(image_file.read()).decode('utf-8')return base64_strdef ocr_with_qwen25vl(image_path, model="qwen2.5vl", stream=False):"""使用 qwen2.5vl 模型进行 OCR 识别参数:image_path: 图像文件路径model: 模型名称,默认为 qwen2.5vlstream: 是否流式返回结果返回:识别到的文本内容"""# 转换图像为 base64 编码image_base64 = image_to_base64(image_path)# API 请求 URLurl = "http://localhost:11434/api/chat"# 请求参数payload = {"model": model,"messages": [{"role": "user","content": "请识别图像中的所有文本内容,包括格式和排版信息,直接返回识别结果,不要额外解释。","images": [image_base64]  # 多模态模型接收的图像列表}],"stream": stream}try:# 发送 POST 请求response = requests.post(url,headers={"Content-Type": "application/json"},data=json.dumps(payload))response.raise_for_status()  # 检查请求是否成功if stream:# 流式处理响应result = ""for line in response.iter_lines():if line:line_data = json.loads(line)if "message" in line_data and "content" in line_data["message"]:result += line_data["message"]["content"]if line_data.get("done", False):breakreturn resultelse:# 非流式响应response_data = response.json()return response_data["message"]["content"]except requests.exceptions.RequestException as e:print(f"API 请求失败: {e}")return Noneexcept json.JSONDecodeError as e:print(f"响应解析失败: {e}")return None# 使用示例
if __name__ == "__main__":# 替换为你的图像文件路径image_path = R"图片路径"# 调用 OCR 函数ocr_result = ocr_with_qwen25vl(image_path=image_path,model="qwen2.5vl",stream=False  # 非流式模式,一次性获取结果)# 打印识别结果if ocr_result:print("OCR 识别结果:")print(ocr_result)
http://www.dtcms.com/a/348665.html

相关文章:

  • 基于SpringBoot的校园信息共享系统【2026最新】
  • pod管理
  • scanner、arrylist、反转数组
  • FPGA 时序分析(五)
  • 十、redis 入门 之 redis事务
  • (Redis)主从哨兵模式与集群模式
  • 【机器学习】7 Linear regression
  • VScode设置鼠标滚轮调节代码
  • 嵌入式第三十六天(网络编程(TCP))
  • springboot项目搭建步骤
  • 【Flink】部署模式
  • Maven项目中settings.xml终极优化指南
  • Excel 表格 - 乘法与除法处理(保留两位小数四舍五入实现、保留两位小数截断实现、添加百分号)
  • 单片机外设(七)RTC时间获取
  • 深入解析Java NIO多路复用原理与性能优化实践指南
  • 重置MySQL数据库的密码指南(Windows/Linux全适配)
  • 基于springboot的理商管理平台设计与实现、java/vue/mvc
  • 得物25年春招-安卓部分笔试题1
  • Linux camera 驱动流程介绍(rgb: ov02k10)(chatgpt version)
  • AlmaLinux 上 Python 3.6 切换到 Python 3.11
  • EP02:【DA】数据分析的价值创造与应用流程
  • 基于SpringBoot的新能源汽车租赁管理系统【2026最新】
  • 【Linux文件系统】Linux文件系统与设备驱动
  • MySQL数据库精研之旅第十一期:打造高效联合查询的实战宝典(二)
  • python中的filter函数
  • 学习做动画1.简易行走
  • 人工智能之数学基础:离散型随机变量
  • 源滚滚React消息通知框架v1.0.2使用教程
  • 管道符在渗透测试与网络安全中的全面应用指南
  • sim2real!so-arm100 机械臂 Mujoco 仿真与实机控制