手写文字 OCR 识别使用指南

功能概述

手写文字 OCR 识别功能允许用户上传图片,快速识别其中的手写文字内容。支持多种识别模式和语言选择。

访问路径

  • 前端页面:/workspace/ocr
  • API 端点:/api/ocr/handwriting

功能特性

1. 图片上传

  • 支持拖拽上传或点击选择文件
  • 支持格式:JPG、PNG、JPEG
  • 最大文件大小:10MB
  • 实时图片预览

2. 识别模式

  • 手写模式:专门识别手写文字,适合笔记、信件等
  • 印刷模式:识别印刷文字,适合文档、书籍等
  • 混合模式:同时识别手写和印刷文字

3. 语言选择

  • 中文:专门识别中文文字
  • 英文:专门识别英文文字
  • 自动:自动检测语言类型

4. 结果处理

  • 实时显示识别结果
  • 支持复制到剪贴板
  • 支持下载为文本文件
  • 显示处理时间和置信度

API 使用说明

POST /api/ocr/handwriting

上传图片并识别手写文字。

请求参数:

  • file (File, required): 图片文件
  • mode (string, optional): 识别模式,可选值:handwritingprintedmixed,默认:handwriting
  • language (string, optional): 语言,可选值:zhenauto,默认:zh

响应格式:

{
  "success": true,
  "text": "识别出的文字内容",
  "confidence": 0.95,
  "processing_time": 2.5,
  "error": null
}

错误响应:

{
  "success": false,
  "text": "",
  "error": "错误信息",
  "processing_time": 0.5
}

POST /api/ocr/handwriting-base64

使用 base64 编码的图片识别手写文字。

请求体:

{
  "image_base64": "base64编码的图片数据",
  "mode": "handwriting",
  "language": "zh"
}

GET /api/ocr/health

检查 OCR 服务健康状态。

响应:

{
  "status": "ok",
  "message": "OCR service is ready",
  "provider": "deepseek"
}

环境配置

后端配置

需要在环境变量中配置 DeepSeek API Key:

DEEPSEEK_API_KEY=your_api_key_here
DEEPSEEK_API_URL=https://api.deepseek.com/v1/chat/completions  # 可选,默认值

依赖安装

后端需要安装 Pillow 库:

pip install Pillow>=10.0.0

使用示例

前端使用

import { api } from '@/lib/api-client';

// 上传图片并识别
const file = // File 对象
const formData = new FormData();
formData.append('file', file);
formData.append('mode', 'handwriting');
formData.append('language', 'zh');

const result = await api.upload('/api/ocr/handwriting', file, {
  additionalData: {
    mode: 'handwriting',
    language: 'zh',
  },
  onProgress: (percent) => {
    console.log(`上传进度: ${percent}%`);
  },
});

console.log('识别结果:', result.text);

后端调用示例

import httpx

async def recognize_text(image_file):
    async with httpx.AsyncClient() as client:
        files = {'file': image_file}
        data = {
            'mode': 'handwriting',
            'language': 'zh'
        }
        response = await client.post(
            'http://localhost:8000/api/ocr/handwriting',
            files=files,
            data=data
        )
        return response.json()

技术实现

后端架构

  • 框架:FastAPI
  • 图像处理:Pillow (PIL)
  • OCR 服务:DeepSeek API
  • 异步处理:httpx

前端架构

  • 框架:Next.js 14
  • UI 组件:Radix UI + Tailwind CSS
  • 状态管理:React Hooks
  • 文件上传:XMLHttpRequest (支持进度)

注意事项

  1. API Key 配置:确保已正确配置 DEEPSEEK_API_KEY 环境变量
  2. 文件大小限制:单张图片最大 10MB,超过会自动压缩
  3. 图片格式:仅支持常见图片格式,不支持 PDF
  4. 识别准确度:手写文字识别准确度取决于图片质量和文字清晰度
  5. 处理时间:大图片或复杂内容可能需要较长时间处理

故障排查

1. API Key 未配置

错误信息DeepSeek API key not configured 解决方法:设置 DEEPSEEK_API_KEY 环境变量

2. 图片格式不支持

错误信息只支持图片文件格式(jpg, png, jpeg) 解决方法:确保上传的是图片文件

3. 文件过大

错误信息图片大小不能超过 10MB 解决方法:压缩图片或使用更小的图片

4. OCR API 调用失败

错误信息OCR API 调用失败 解决方法

  • 检查网络连接
  • 验证 API Key 是否有效
  • 检查 API 服务是否可用

未来改进

  1. 支持 PDF 文件处理
  2. 批量图片识别
  3. 识别结果编辑功能
  4. 多语言识别优化
  5. 离线 OCR 模型支持