【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)