惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
博客园 - 叶小钗
WordPress大学
WordPress大学
N
Netflix TechBlog - Medium
M
MIT News - Artificial intelligence
美团技术团队
aimingoo的专栏
aimingoo的专栏
博客园_首页
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Microsoft Security Blog
Microsoft Security Blog
Last Week in AI
Last Week in AI
The GitHub Blog
The GitHub Blog
小众软件
小众软件
T
Tailwind CSS Blog
Martin Fowler
Martin Fowler
B
Blog RSS Feed
月光博客
月光博客
量子位
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家
Y
Y Combinator Blog
B
Blog
MyScale Blog
MyScale Blog

博客园 - Zion0707

Codex接入DeepSeek token实现对话与操作,so easy! Openclaw只能聊天不能操作解决方案 Ubuntu从零搭建Openclaw Openclaw安装问题记录 React数字滚动,增加或减少效果 react hooks实现对元素拖拽及鼠标滚轮缩放 ECharts实现两条曲线数据比较,数据高出区域高亮显示 canvas实现视频播放并支持自动播放 fabricjs实现虚线流动动画效果 React国际化方案及示例 fabricjs如何导入echarts fabricjs元素对齐方式实现 萤石云视频监控和回放方案 React仿photoshop参考线功能 react-router-dom v6 使用 “DatePicker”不能用作 JSX 组件。 Element plus的tree组件实现单选和搜索功能 16进制相关操作方法 js 版 AES-128 算法加解密 js 版 React 下拉多选,全选/全不选功能组件
前端实现图片文字识别并提取
Zion0707 · 2023-08-13 · via 博客园 - Zion0707

需求:

其实这个需求还是挺常见的,经常会看到一些app或网页拍一张图片或者上传一张图片则需要提取图片中的数字或文字,这里我采用了 tesseract.js 实现。这个前端插件的好处是字母和数字的识别率挺高,但对中文的识别略差,根据需求可进行取舍。

物料:

一张带有数字的图片。

 效果:

代码:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tesseract.js 示例</title>
</head>
<body>
  <input type="file" id="imageInput" accept="image/*">
  <pre id="outputText"></pre>

  <script src="https://cdn.jsdelivr.net/npm/tesseract.js"></script>
  <script src="./index.js"></script>
</body>
</html>

index.js

// 获取元素
const imageInput = document.getElementById('imageInput');
const outputText = document.getElementById('outputText');

// 当选择图片时
imageInput.addEventListener('change', handleImageUpload);

function handleImageUpload(event) {
  const file = event.target.files[0];

  if (file) {
    const reader = new FileReader();
    reader.onload = function(e) {
      const img = new Image();
      img.src = e.target.result;
      img.onload = function() {
        extractTextFromImage(img);
      };
    };
    reader.readAsDataURL(file);
  }
}

function extractTextFromImage(image) {
  Tesseract.recognize(
    image,
    'chi_sim', // 设置语言为中文
    { logger: info => console.log(info) } // 日志输出,可选
  ).then(({ data: { text } }) => {
    console.log(text);
    outputText.textContent = '提取的文字:\n\n' + text;
  }).catch(error => {
    console.error('发生错误:', error);
  });
}