hunyuanOCR识别图片文本
HunyuanOCR是腾讯混元视觉团队于2025年11月25日正式开源的轻量级OCR专用视觉语言模型,参数规模仅为1B,凭借端到端的创新架构实现了远超同规模模型的性能表现。

核心架构特点
- 纯端到端训推范式:摒弃传统OCR流水线的多阶段级联模式,通过单次前向推理即可完成全流程任务,从根本上解决了多阶段方案的错误累积问题,大幅降低部署复杂度。
- 三大核心组件:由原生分辨率视觉编码器(基于SigLIP-v2-400M)、自适应视觉适配器、轻量化混元语言模型(基于Hunyuan-0.5B)协同构成,支持任意分辨率输入,避免长文档图像失真。
- 创新技术加持:引入XD-RoPE技术实现一维文本、二维版面、三维时空信息的解耦对齐,搭配强化学习混合奖励策略,大幅提升复杂场景下的识别鲁棒性。
下面开始介绍自己在ubuntu上的部署流程。
1. 部署硬件设备
- 显卡:3060,12G
- 操作系统:ubuntu;具体为Linux lxuottdefjevlvyu-snow-9cc8c95db-tmnw6 5.19.0-50-generic #50-Ubuntu SMP PREEMPT_DYNAMIC Mon Jul 10 18:24:29 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux
- 内核版本:5.19.0-50-generic
2. python版本
我使用的是python 3.10.16
3. 模型与源码下载
3.1 模型下载
使用国内的modelscope下载,先安装modelscope
#安装modelscope
pip install modelscope

3.2 模型下载
#默认路径下载hunyuanocr模型
modelscope download --model Tencent-Hunyuan/HunyuanOCR
#指定路径下载hunyuanocr模型
modelscope download --model Tencent-Hunyuan/HunyuanOCR README.md --local_dir /home/wx/....

下载后,目录为:

3.3 源码下载
wget https://github.com/Tencent-Hunyuan/HunyuanOCR/archive/refs/heads/main.zip
下载好后使用unzip main.zip解压得到HuanyuanOCR-main文件夹,解压后目录为:

4. vllm安装
使用如下命令行安装:
pip install vllm==0.18.1 --timeout 300 -i https://pypi.tuna.tsinghua.edu.cn/simple --no-cache-dir

5. 参数设置与配置
在上面下载的源码中解压后,找到serve.sh。具体在main\HunyuanOCR-main\inference\vLLM\server.sh,打开会发现如下:需要配置模型路径

使用命令配置配置模型路径,根据自己的模型实际路径配置:
export MODEL_PATH=/data/.rootcache/modelscope/models/Tencent-Hunyuan--HunyuanOCR/snapshots/master
除了配置模型路径外,其他的参数也需要配置下(绿色字体标注的):

配置命令:
export GPU_MEM_UTIL=0.6 export MAX_MODEL_LEN=16384 VLLM_USE_FLASHINFER_SAMPLER=0 export VLLM_ATTENTION_BACKEND=TORCH_SDPA

参数设置解释:
GPU_MEM_UTIL=0.6:限制 vLLM 最多使用 60% 的 GPU 显存,RTX 3060 只有 12GB 显存,HunyuanOCR 模型加载、KV Cache、CUDA 图等都要占显存。如果不限制,vLLM 默认会尝试占满,可能和其他进程冲突或导致 OOM(显存不足)
MAX_MODEL_LEN=16384:设置模型能处理的最大上下文长度为16384个token。设置模型能处理的最大上下文长度为16384个token。单次请求的输入+输出总长度不能超过 16384 token。对于普通 OCR 任务(一张图片+一段识别结果),完全够用。
export VLLM_USE_FLASHINFER_SAMPLER=0:禁用FlashInfer采样器,改用PyTorch原生采样。FlashInfer是一个高性能采样库,但它需要 nvcc(CUDA 编译器)在运行时JIT编译。禁用后:vLLM 回退到 PyTorch 原生采样,功能完全正常,只是采样速度可能略慢一点点(对OCR影响很小)。
export VLLM_ATTENTION_BACKEND=TORCH_SDPA:指定注意力计算后端为TORCH_SDPA(PyTorch的Scaled Dot-Product Attention)。vLLM 默认会尝试用 FlashAttention 或 FlashInfer 等高性能后端,但这些同样可能需要 nvcc 编译或特定 CUDA 版本。TORCH_SDPA 的好处:这是 PyTorch 内置的原生注意力实现,完全不需要编译,兼容性最好,能绕过所有与 nvcc、CUDA 版本相关的坑。代价:速度比 FlashAttention 慢一些,但胜在稳定可靠。
6. 启动服务
进入到main.zip解压后得到的HunyuanOCR-main目录下执行:
bash inference/vLLM/serve.sh

7. 验证
验证模型是否启动成功。
向 vLLM 服务发送一个 HTTP 请求,查询当前已加载的模型信息,用来验证服务是否已经就绪并能正常响应。
curl -sf http://127.0.0.1:8000/v1/models
vLLM 启动后会暴露一个兼容 OpenAI API 的 HTTP 服务,/v1/models 是最基础的“健康检查”端点:服务还没加载完 → 端口没响应,curl 无输出服务已就绪 → 返回一个 JSON,包含模型名称、最大长度等信息服务启动失败 → 端口关闭,curl 报连接错误。如若正常,输出应该为:
{"object":"list","data":[{"id":"tencent/HunyuanOCR","object":"model","created":1789002890,"owned_by":"vllm","root":"/home/jingli/models/hunyuanocr_local","parent":null,"max_model_len":16384,"permission":[{"id":"modelperm-a268e2527d49eb81","object":"model_permission","created":1789002890,"allow_create_engine":false,"allow_sampling":true,"allow_logprobs":true,"allow_search_indices":false,"allow_view":true,"allow_fine_tuning":false,"organization":"*","group":null,"is_blocking":false}]}]}
8. 命令行测试模型识别文本
python inference/vLLM/infer_vllm_client.py --image /home/jingli/桌面/test.jpg --task-type doc_parse --model tencent/HunyuanOCR --port 8000 --max-tokens 2048
测试用图与识别效果截图:

测试图

文本识别结果
9. python代码调用
import requests import base64 import json import cv2 # 替换 PIL,导入 OpenCV # ================= 固定配置区域 ================= # API_URL = "http://192.168.0.121:8000/v1/chat/completions" API_URL="https://xxxx.xxx.com/v1/chat/completions" IMAGE_PATH = "./32.png" TASK_TYPE = "doc_parse" MODEL_NAME = "tencent/HunyuanOCR" MAX_TOKENS = 2048 # ================================================= def image_to_base64(image) -> str: """将 OpenCV 图片(numpy 数组)转换为 Base64 编码字符串""" # 对应原来的转灰度逻辑 img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 将灰度图编码为 PNG 格式进入内存 buffer success, buffer = cv2.imencode('.png', img_gray) if not success: raise ValueError("图片编码失败") return base64.b64encode(buffer).decode("utf-8") def call_hunyuan_ocr(): # 改为 image = cv2.imread 读入 image = cv2.imread(IMAGE_PATH) if image is None: print(f"❌ 无法读取图片: {IMAGE_PATH}") return img_b64 = image_to_base64(image) payload = { "model": MODEL_NAME, "messages": [ { "role": "user", "content": [ {"type": "text", "text": f"请执行 {TASK_TYPE} 任务,提取图片中的所有文本内"}, {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"}} ] } ], "max_tokens": MAX_TOKENS, "stream": False } headers = {"Content-Type": "application/json"} print(f"正在请求 vLLM OCR 服务,识别图片: {IMAGE_PATH} ...") try: resp = requests.post(API_URL, json=payload, headers=headers, timeout=60) resp.raise_for_status() result = resp.json() ocr_text = result["choices"][0]["message"]["content"] print("\n" + "=" * 30) print("✅ 识别成功,结果如下:") print(ocr_text) print("=" * 30) except Exception as e: print(f"请求出错: {e}") if 'resp' in locals(): print(f"服务器返回内容: {resp.text}") if __name__ == "__main__": call_hunyuan_ocr()
然后修改提示词,给一个带框的:
import requests import base64 import json import re import cv2 # ================= 固定配置区域 ================= API_URL = "https://xxx.xxx.com/v1/chat/completions" IMAGE_PATH = "./3_2.png" MODEL_NAME = "tencent/HunyuanOCR" MAX_TOKENS = 4096 def image_to_base64(image) -> str: """将 OpenCV 图片转换为灰度图并进行 PNG 编码,去除颜色噪点""" img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) success, buffer = cv2.imencode('.png', img_gray) if not success: raise ValueError("图片编码失败") return base64.b64encode(buffer).decode("utf-8") def call_api(image_b64: str, prompt: str, is_spotting: bool = False) -> str: """通用 API 请求函数""" # ⚠️ 关键魔法:强行使用你单独代码中成功的 jpeg 标头(即使底层是 png 编码) image_header = "data:image/jpeg;base64," payload = { "model": MODEL_NAME, "messages": [ { "role": "user", "content": [ {"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": f"{image_header}{image_b64}"}} ] } ], "max_tokens": MAX_TOKENS, "stream": False } # 如果是第二轨提取坐标,才加上额外的稳定控制参数 if is_spotting: payload["temperature"] = 0 payload["extra_body"] = {"top_k": 1, "repetition_penalty": 1.0} headers = {"Content-Type": "application/json"} resp = requests.post(API_URL, json=payload, headers=headers, timeout=120) resp.raise_for_status() return resp.json()["choices"][0]["message"]["content"] # ================= 核心双轨融合策略 ================= def get_perfect_text(image_b64: str) -> list: """ 第一轨:纯文本提取 (doc_parse) ⚠️ 关键魔法:完全使用你单独测试成功的原版 Prompt(故意保留“文本内”的断句) 这能触发大模型输出 100% 完美的文本,保留字母 A 和“鹤”字。 """ prompt = "请执行 doc_parse 任务,提取图片中的所有文本内" content = call_api(image_b64, prompt, is_spotting=False) # 按行拆分,过滤掉空行 return [line.strip() for line in content.split('\n') if line.strip()] def get_boxes_and_merge(image_b64: str) -> list: """第二轨:坐标提取 (spotting) 并执行完美的同行合并算法""" # ⚠️ 关键修改:加入了英文示例 (Part No.),防止模型在遇到纯英文图片时格式崩溃 prompt = ( "请检测并识别图片中的所有文字,必须同时输出文字和坐标。请严格按照以下格式输出:\n" "TEXT(x1,y1),(x2,y2)\n" "示例:\n" "合格证(100,50),(300,80)\n" "Part No.(120,90),(400,120)" ) content_str = call_api(image_b64, prompt, is_spotting=True) results = [] # 1. 官方推荐 Spotting 格式正则解析 TEXT(x1,y1),(x2,y2) pattern1 = r'(.*?)\((\d+),\s*(\d+)\),\s*\((\d+),\s*(\d+)\)' matches = re.findall(pattern1, content_str) for match in matches: text = match[0].strip() coords = (int(match[1]), int(match[2]), int(match[3]), int(match[4])) if text: results.append({"text": text, "coords": coords}) # 2. 备用正则:有些大模型在英文模式下喜欢输出 TEXT[x1,y1,x2,y2] 或者 TEXT(x1,y1,x2,y2) if not results: pattern2 = r'(.*?)[\(\[](\d+),\s*(\d+),\s*(\d+),\s*(\d+)[\)\]]' matches2 = re.findall(pattern2, content_str) for match in matches2: text = match[0].strip() coords = (int(match[1]), int(match[2]), int(match[3]), int(match[4])) if text: results.append({"text": text, "coords": coords}) # 3. 兜底 JSON 解析 if not results: try: start, end = content_str.find('['), content_str.rfind(']') if start != -1 and end != -1: json_data = json.loads(content_str[start:end + 1]) for item in json_data: if "box" in item: results.append({"text": item.get("text", ""), "coords": tuple(item["box"])}) except: pass if not results: # ⚠️ 关键修改:如果全部解析失败,必须打印它到底返回了什么鬼东西! print(f"\n❌ 坐标解析失败!大模型原始返回内容如下 (请检查格式):\n{'-' * 40}\n{content_str}\n{'-' * 40}\n") return [] # 4. 严谨的合并算法 for item in results: item["cy"] = (item["coords"][1] + item["coords"][3]) / 2.0 results.sort(key=lambda x: x["cy"]) lines = [] current_line = [results[0]] for box in results[1:]: if abs(box["cy"] - current_line[-1]["cy"]) < 15: # Y轴中心点容差 current_line.append(box) else: lines.append(current_line) current_line = [box] lines.append(current_line) merged_results = [] for line in lines: line.sort(key=lambda item: item["coords"][0]) current_box = line[0].copy() for next_box in line[1:]: c_x1, c_y1, c_x2, c_y2 = current_box["coords"] n_x1, n_y1, n_x2, n_y2 = next_box["coords"] if (n_x1 - c_x2) < 80: # X轴水平间距容差 current_box["coords"] = ( min(c_x1, n_x1), min(c_y1, n_y1), max(c_x2, n_x2), max(c_y2, n_y2) ) else: merged_results.append(current_box) current_box = next_box.copy() merged_results.append(current_box) return merged_results def draw_boxes(image, ocr_results): """仅在图片上绘制纯粹的绿色检测框,保持画面清爽""" if image is None or not ocr_results: return image img_copy = image.copy() h, w = img_copy.shape[:2] for item in ocr_results: box = item["coords"] x1 = max(0, min(int(box[0] / 1000 * w), w)) y1 = max(0, min(int(box[1] / 1000 * h), h)) x2 = max(0, min(int(box[2] / 1000 * w), w)) y2 = max(0, min(int(box[3] / 1000 * h), h)) cv2.rectangle(img_copy, (x1, y1), (x2, y2), (0, 255, 0), 2) return img_copy if __name__ == "__main__": image = cv2.imread(IMAGE_PATH) image=cv2.GaussianBlur(image, (5, 5), 0) if image is None: print(f"❌ 无法读取图片: {IMAGE_PATH}") exit() print(f"📐 图片尺寸: {image.shape[1]}x{image.shape[0]}") img_b64 = image_to_base64(image) try: print("正在执行 [轨1/2] 纯文本提取 (获取完美无漏字文本)...") perfect_texts = get_perfect_text(img_b64) print("正在执行 [轨2/2] 坐标提取 (获取精准合并框)...") merged_boxes = get_boxes_and_merge(img_b64) if not merged_boxes: print("⚠️ 未能获取到坐标信息。") exit() print("\n" + "=" * 40) print("🎉 最终融合结果 (纯净框 + 完美文本):") # 最终融合:将轨1获取的完美文本,塞入轨2合并好的框里! if len(perfect_texts) == len(merged_boxes): for i in range(len(merged_boxes)): merged_boxes[i]["text"] = perfect_texts[i] print(f" [{i}] {merged_boxes[i]['text']}") else: print(f"⚠️ 文本行数({len(perfect_texts)})与框数({len(merged_boxes)})不完全一致,采取尽力匹配...") for i in range(len(merged_boxes)): if i < len(perfect_texts): merged_boxes[i]["text"] = perfect_texts[i] print(f" [{i}] {merged_boxes[i]['text']}") print("=" * 40) # 绘制并保存图片 result_image = draw_boxes(image, merged_boxes) output_path = "05_ultimate_perfection.jpg" cv2.imwrite(output_path, result_image) print(f"\n✅ 最终完美带框图片已保存: {output_path}") except Exception as e: print(f"❌ 运行出错: {e}")
小结:简单介绍了hunyuanOCR模型,并在ubuntu上进行部署部署与测试,最后给出了python脚本调用模型识别文本。识别过程中,发现是右上角文本容易掉,修改提示词无效,改用四周背景填充解决。

浙公网安备 33010602011771号