利用JavaScript调用ChineseOCR API实现图片文字识别

张开发
2026/4/12 18:49:45 15 分钟阅读

分享文章

利用JavaScript调用ChineseOCR API实现图片文字识别
1. ChineseOCR API 简介ChineseOCR 是一款基于深度学习的开源 OCR光学字符识别引擎专注于中文文本识别。它提供了多种调用方式包括在线调用、JavaScript API 调用、cURL API 调用和 Python API 调用。对于前端开发者来说通过 JavaScript 调用 ChineseOCR API 可以快速将 OCR 功能集成到网页应用中实现图片中文字的识别。ChineseOCR 的优势在于对中文文本的高识别率特别是针对印刷体和手写体的中文文本。它支持多种图片格式包括 JPG、PNG 等并能处理不同背景和光照条件下的图片。2. 准备工作2.1 获取 API 访问权限在开始之前你需要确保拥有 ChineseOCR API 的访问权限。通常这包括注册开发者账号获取 API 密钥如果有了解 API 的调用限制和配额2.2 准备开发环境要使用 JavaScript 调用 ChineseOCR API你需要一个现代浏览器推荐 Chrome 或 Firefox基本的 HTML、JavaScript 知识可选一个代码编辑器如 VS Code2.3 了解 API 端点ChineseOCR API 的基本端点通常是固定的例如https://momodel.cn/pyapi/apps/run/5cd04ee51afd94639a492b8e这个端点可能会随着 API 版本的更新而变化因此建议查阅最新的官方文档。3. 图片预处理3.1 图片格式要求ChineseOCR API 通常要求图片以 Base64 编码的字符串形式传递。这意味着你需要将图片转换为 Base64 格式。常见的图片格式如 JPG、PNG 都支持。3.2 使用在线工具转换图片如果你需要快速测试可以使用在线 Base64 转换工具打开在线工具如 base64-image.de上传你的图片获取 Base64 编码字符串3.3 在 JavaScript 中转换图片在实际应用中你可以使用 JavaScript 将用户上传的图片转换为 Base64function convertImageToBase64(file) { return new Promise((resolve, reject) { const reader new FileReader(); reader.readAsDataURL(file); reader.onload () resolve(reader.result.split(,)[1]); reader.onerror error reject(error); }); } // 使用示例 const fileInput document.getElementById(file-input); fileInput.addEventListener(change, async (event) { const file event.target.files[0]; const base64Image await convertImageToBase64(file); // 现在可以使用 base64Image 调用 API });4. 调用 ChineseOCR API4.1 基本 API 调用结构以下是调用 ChineseOCR API 的基本 JavaScript 代码框架async function recognizeText(base64Image) { try { const url https://momodel.cn/pyapi/apps/run/5cd04ee51afd94639a492b8e; const input { img: { val: base64Image, type: img } }; const output { take_time: {type: float}, output: {type: str} }; const appVersion 0-2-0; const payload JSON.stringify({ app: {input: input, output: output}, version: appVersion }); const response await fetch(url, { headers: { content-type: application/json; charsetUTF-8 }, body: payload, method: POST }); const jsonData await response.json(); return jsonData; } catch (error) { console.error(识别失败:, error); throw error; } }4.2 处理 API 响应API 通常会返回一个 JSON 对象包含识别结果和处理时间{ take_time: 0.45, output: 识别出的文本内容 }你可以这样处理响应async function handleRecognition() { const base64Image await getBase64Image(); // 获取Base64图片 try { const result await recognizeText(base64Image); console.log(识别耗时:, result.take_time, 秒); console.log(识别结果:, result.output); // 在页面上显示结果 document.getElementById(result).textContent result.output; } catch (error) { console.error(识别过程中出错:, error); alert(识别失败请重试); } }5. 完整示例5.1 HTML 结构!DOCTYPE html html langzh-CN head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 titleChineseOCR 文字识别/title style body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; } #preview { max-width: 100%; margin: 20px 0; display: none; } #result { margin-top: 20px; padding: 15px; border: 1px solid #ddd; min-height: 100px; white-space: pre-wrap; } button { padding: 10px 15px; background-color: #4CAF50; color: white; border: none; cursor: pointer; } button:disabled { background-color: #cccccc; } /style /head body h1ChineseOCR 文字识别/h1 input typefile idfile-input acceptimage/* img idpreview alt图片预览 button idrecognize-btn disabled识别文字/button div idresult/div script srcapp.js/script /body /html5.2 JavaScript 实现// app.js document.addEventListener(DOMContentLoaded, () { const fileInput document.getElementById(file-input); const preview document.getElementById(preview); const recognizeBtn document.getElementById(recognize-btn); const resultDiv document.getElementById(result); let currentBase64Image null; // 监听文件选择 fileInput.addEventListener(change, async (event) { const file event.target.files[0]; if (!file) return; // 显示图片预览 const reader new FileReader(); reader.onload (e) { preview.src e.target.result; preview.style.display block; }; reader.readAsDataURL(file); // 转换为Base64 currentBase64Image await convertImageToBase64(file); recognizeBtn.disabled false; }); // 识别按钮点击事件 recognizeBtn.addEventListener(click, async () { if (!currentBase64Image) return; recognizeBtn.disabled true; resultDiv.textContent 识别中...; try { const result await recognizeText(currentBase64Image); resultDiv.textContent result.output; console.log(识别耗时:, result.take_time, 秒); } catch (error) { console.error(识别失败:, error); resultDiv.textContent 识别失败请重试; } finally { recognizeBtn.disabled false; } }); }); // 将图片转换为Base64 function convertImageToBase64(file) { return new Promise((resolve, reject) { const reader new FileReader(); reader.readAsDataURL(file); reader.onload () { // 移除data:image/png;base64,前缀 const base64String reader.result.split(,)[1]; resolve(base64String); }; reader.onerror error reject(error); }); } // 调用ChineseOCR API async function recognizeText(base64Image) { try { const url https://momodel.cn/pyapi/apps/run/5cd04ee51afd94639a492b8e; const input { img: { val: base64Image, type: img } }; const output { take_time: {type: float}, output: {type: str} }; const appVersion 0-2-0; const payload JSON.stringify({ app: {input: input, output: output}, version: appVersion }); const response await fetch(url, { headers: { content-type: application/json; charsetUTF-8 }, body: payload, method: POST }); if (!response.ok) { throw new Error(API请求失败: ${response.status}); } return await response.json(); } catch (error) { console.error(API调用错误:, error); throw error; } }6. 错误处理与优化6.1 常见错误处理在实际应用中你可能会遇到以下问题图片太大API可能有大小限制建议在上传前检查图片大小网络问题添加重试机制或超时处理API限制处理API调用频率限制改进后的错误处理async function recognizeTextWithRetry(base64Image, maxRetries 3) { let lastError null; for (let i 0; i maxRetries; i) { try { const result await recognizeText(base64Image); return result; } catch (error) { lastError error; console.warn(识别失败尝试 ${i 1}/${maxRetries}, error); // 等待一段时间后重试 await new Promise(resolve setTimeout(resolve, 1000 * (i 1))); } } throw lastError; }6.2 性能优化图片压缩在上传前压缩图片减少传输数据量缓存结果对相同图片的识别结果进行缓存批量处理如果需要处理多张图片考虑使用批量API如果提供图片压缩示例async function compressImage(file, maxWidth 1024, quality 0.8) { return new Promise((resolve) { const reader new FileReader(); reader.readAsDataURL(file); reader.onload (event) { const img new Image(); img.src event.target.result; img.onload () { const canvas document.createElement(canvas); const ctx canvas.getContext(2d); // 计算缩放比例 let width img.width; let height img.height; if (width maxWidth) { height (maxWidth / width) * height; width maxWidth; } canvas.width width; canvas.height height; ctx.drawImage(img, 0, 0, width, height); // 转换为JPG并压缩 canvas.toBlob((blob) { resolve(blob); }, image/jpeg, quality); }; }; }); }7. 高级应用7.1 处理复杂布局对于包含复杂布局的图片如多栏文本、表格等ChineseOCR 可能无法完美识别。你可以在客户端对图片进行预处理裁剪、旋转、增强对比度等将大图分割为多个小区域分别识别使用额外的算法对识别结果进行后处理7.2 与其他API集成ChineseOCR 可以与其他API结合使用例如翻译API识别中文后自动翻译为其他语言语音合成API将识别出的文本转换为语音自然语言处理API对识别出的文本进行进一步分析7.3 离线使用如果需要离线使用可以考虑使用ChineseOCR的本地部署版本如果有提供探索其他开源OCR引擎的WebAssembly版本开发浏览器扩展来集成OCR功能8. 安全与隐私考虑当处理用户上传的图片时需要注意数据隐私确保用户知道他们的图片将被上传处理敏感信息避免在客户端日志中记录完整的图片数据HTTPS始终通过HTTPS调用API防止中间人攻击内容审核如果应用允许用户上传任意图片考虑添加内容审核机制9. 替代方案虽然ChineseOCR是一个优秀的中文OCR解决方案但也有其他选择Tesseract.js开源的OCR引擎支持多种语言百度OCR API商业解决方案提供更高的准确率腾讯OCR API另一个商业选项有免费额度Google Cloud Vision支持多种语言的商业API选择哪种方案取决于你的具体需求、预算和技术栈。10. 总结通过JavaScript调用ChineseOCR API实现图片文字识别是一个相对简单的过程主要包括以下几个步骤获取图片并将其转换为Base64格式构建符合API要求的请求数据发送请求到ChineseOCR API端点处理返回的识别结果在界面上展示结果或进行后续处理在实际应用中你还需要考虑错误处理、性能优化、用户体验等方面。本文提供的完整示例代码可以作为一个起点你可以根据自己的需求进行扩展和定制。记住OCR技术虽然已经相当成熟但并非完美。对于关键应用建议添加人工审核环节或者结合其他技术手段来提高识别准确率。

更多文章