Posts 制作一个Node命令行图像识别工具
Post
Cancel

制作一个Node命令行图像识别工具

从 0 开始制作一个 NodeJS 命令行验证码识别工具。实现如下效果。

01.png

初始化项目

1
2
3
4
5
6
7
8
9
10
11
12
13
# 创建 recognition 项目
mkdir recognition
cd recognition
npm init -y

# 安装主依赖
yarn add images tesseract.js

# 安装工具依赖
yarn add chalk yargs

# 可选依赖
yarn add socks5-http-client

依赖说明

  • images:Node.js 轻量级跨平台图像编码库,用于处理下载下来的图片

  • tesseract.js:纯 JS 实现的 OCR(光学字符识别)工具,用于图像内容识别

  • chalk:让命令行内容样式好看

  • yargs:命令行参数解析器

  • socks5-http-client:SOCKS v5,用于设置代理,在需要拉取某些不能直接访问的资源时使用,request proxy 例子

项目准备

新建 cli.js

通常命令行工具入口名字为 cli.js,我们新建一个 cli.js 文件,并在开头写上:

1
#!/usr/bin/env node

这样,我们告诉 *nix 系统,JavaScript 文件的解释器应该是 /usr/bin/env node,它查找本地安装的 node

配置 bin

1
2
3
4
5
6
// package.json
{
  "bin": {
    "reg": "./cli.js"
  }
}

这样配置完成后,别人 npm install -g @chenng/recognition 的包,就可以直接通过命令行运行了:

1
reg --url=https://static.chenng.cn/imgs/test_img.png

我们如何能够在本地可以使用 rec 命令呢?只需要把本项目 link 即可:

1
yarn link

核心逻辑

主要逻辑在 cli.jsrecognize.js 中。这里有几个注意点:

  • request 图片的时候要设置 encoding: null,否则返回的是乱码
  • 初次使用的时候需要下载训练集,需要花点时间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const Tesseract = require("tesseract.js");
const images = require("images");
const requset = require("request");
const fs = require("fs");
const { promisify } = require("util");
const chalk = require("chalk");

const writeFile = promisify(fs.writeFile);
const rp = promisify(requset);

class Recognize {
  constructor(url) {
    Recognize.downloadDir = `${__dirname}/dist/`;
    Recognize.downloadFile = `${__dirname}/dist/temp.png`;
    this.url = url;
    this.start();
  }

  async start() {
    const data = await this.downloadImg();
    await writeFile(Recognize.downloadFile, data);
    this.recognize();
    const result = await Tesseract.recognize(Recognize.downloadFile, {
      lang: "eng",
      tessedit_char_blacklist:
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
    });

    console.log(`

      识别成功!
      识别结果为:${chalk.green(result.text)}
    `);
  }

  async downloadImg() {
    if (!fs.existsSync(Recognize.downloadDir)) {
      fs.mkdirSync(Recognize.downloadDir);
      console.log(`创建了 ${Recognize.downloadDir} 文件夹`);
    }

    const res = await rp({
      url: this.url,
      method: "GET",
      encoding: null,
    });
    return res.body;
  }

  recognize() {
    // 放大图片,并覆盖源文件
    images(Recognize.downloadFile).size(400).save(Recognize.downloadFile);
  }
}

module.exports = Recognize;

具体可以查看源码仓库:https://github.com/ringcrl/recognition

发布上线

1
2
3
4
5
6
7
8
9
10
# 新建代码仓库,git push

# 登录到 npm
npm adduser

# 发包
npm publish --access public

# 全局安装
npm install -g @chenng/recognition
This post is licensed under CC BY 4.0 by the author.
Trending Tags
Contents

Trending Tags