This commit is contained in:
12600k-rog-d4
2026-06-11 08:12:45 +08:00
parent 014cffd51a
commit 327f019d42
226 changed files with 323 additions and 164 deletions

View File

@@ -0,0 +1,103 @@
---
name: "ocr-extract"
description: "OCR文字识别工具使用RapidOCR从图片中提取文字。Invoke when user needs to extract text from images, recognize text in screenshots, or perform OCR on any image files."
---
# OCR 文字识别工具
使用 RapidOCR (rapidocr-onnxruntime) 对图片进行文字识别支持中英文混合识别无需GPU。
## 前提条件
- Python 环境
- 依赖包:`rapidocr-onnxruntime`, `Pillow`
- 安装命令:`pip install rapidocr-onnxruntime Pillow`
## 基本用法
### 单张图片OCR
```python
from rapidocr_onnxruntime import RapidOCR
ocr = RapidOCR()
result, _ = ocr("image_path.png")
if result:
for line in result:
print(line[1]) # line[1] 是识别的文字
```
### 长图分段识别(推荐)
对于高度超过2000像素的长截图建议分段识别以提高速度和准确度
```python
from rapidocr_onnxruntime import RapidOCR
from PIL import Image
import os, time
ocr = RapidOCR()
img_path = r"长图路径.png"
img = Image.open(img_path)
height = img.size[1]
chunk_size = 1200 # 每段1200像素约1-2秒/段
all_text = []
for i in range(0, height, chunk_size):
bottom = min(i + chunk_size, height)
chunk = img.crop((0, i, img.size[0], bottom))
tmp_path = os.path.join(os.environ['TEMP'], f'ocr_chunk_{i}.png')
chunk.save(tmp_path)
result, _ = ocr(tmp_path)
if result:
for line in result:
all_text.append(line[1])
if os.path.exists(tmp_path):
os.remove(tmp_path)
for t in all_text:
print(t)
```
### 批量图片OCR
```python
from rapidocr_onnxruntime import RapidOCR
import os
ocr = RapidOCR()
img_dir = r"图片目录路径"
images = sorted([f for f in os.listdir(img_dir) if f.lower().endswith(('.jpeg', '.jpg', '.png'))])
for img_name in images:
img_path = os.path.join(img_dir, img_name)
result, _ = ocr(img_path)
print(f"\n=== {img_name} ===")
if result:
for line in result:
print(line[1])
```
## 性能参考
| 图片尺寸 | 分段大小 | 耗时 |
|---------|---------|------|
| 1731x1200 | 不分段 | ~1.5秒 |
| 1731x4896 | 1200px/段 | ~6秒 |
| 1731x20824 | 1200px/段 | ~26秒 |
## 返回结果格式
`result` 是一个列表,每个元素格式为 `[bbox, text, confidence]`
- `bbox`: 文字位置坐标 `[[x1,y1], [x2,y2], [x3,y3], [x4,y4]]`
- `text`: 识别的文字内容
- `confidence`: 置信度(字符串类型)
## 注意事项
- 临时文件使用 `os.environ['TEMP']` 目录,用后需清理
- `os.remove()` 前务必用 `os.path.exists()` 检查文件是否存在
- Windows PowerShell 中避免使用 `&&` 连接命令,改用 `;` 或分行
- 对于非常长的截图(>10000px建议 chunk_size 设为 1200-1500
- 识别中文效果良好,支持中英文混合