@shencom/wechat-opencv
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

@shencom/wechat-opencv

二维码解析 - 基于 OpenCV 和微信二维码引擎的 WebAssembly 实现

简介

@shencom/wechat-opencv 是一个基于 OpenCV.js 和微信二维码引擎的二维码解析库,采用 WebAssembly 技术实现,可以在浏览器环境中高效地检测和解码二维码。本库特别适用于需要识别微信二维码的 Web 应用程序。

特性

  • 支持微信二维码的检测和解码
  • 基于 WebAssembly 技术,性能优异
  • 简单易用的 API 接口
  • 支持图像中多个二维码的同时识别
  • 可视化二维码检测结果

Demo

-> Demo

安装

使用 pnpm:

pnpm add @shencom/wechat-opencv

或者使用 yarn:

yarn add @shencom/wechat-opencv

基本用法

初始化 OpenCV 和 使用 WeChatQRCode

import { opencvInit } from '@shencom/wechat-opencv';

async function init() {
  try {
    const cv = await opencvInit();
    //  OpenCV 的 WeChatQRCode 模块:
    // detect.prototxt 和 detect.caffemodel: 用于二维码检测的网络模型文件。prototxt 文件定义网络结构,caffemodel 包含预训练的权重参数。
    // sr.prototxt 和 sr.caffemodel: 用于超分辨率(Super Resolution)处理的网络模型文件,提高低分辨率二维码图像的清晰度,增强识别成功率。
    const wr = new cv.wechat_qrcode_WeChatQRCode(
      'wechat_qrcode/detect.prototxt',
      'wechat_qrcode/detect.caffemodel',
      'wechat_qrcode/sr.prototxt',
      'wechat_qrcode/sr.caffemodel',
    );

    const img = document.createElement('img');
    img.src = url;
    img.setAttribute('crossOrigin', 'Anonymous');
    img.addEventListener('load', (e) => {
      // 从图像创建 OpenCV Mat 对象
      const inputImg = cv.imread(img);
      // 创建输出向量
      const out = new cv.MatVector();
      // 检测和解码二维码
      const results = wr.detectAndDecode(inputImg, out);
      // 收集结果
      let i = 0;
      const arr = [];

      while (i < results.size()) {
        arr.push(results.get(i++));
      }
      // 解析结果
      console.log('%c [arr.push]-70', 'font-size:13px; background:#336699; color:#fff;', arr);


      // 获取二维码边界框
      const rects = [];
      for (let j = 0; j < out.size(); j++) {
        const rect = cv.boundingRect(out.get(j));
        rects.push(rect);
        
        // 可以在图像上绘制边界框
        const point1 = new cv.Point(rect.x, rect.y);
        const point2 = new cv.Point(rect.x + rect.width, rect.y + rect.height);
        const rectangleColor = new cv.Scalar(255, 0, 0);
        cv.rectangle(inputImg, point1, point2, rectangleColor, 2, cv.LINE_AA, 0);
      }
      
      // 在画布上显示结果图像
      cv.imshow('canvas-id', inputImg);

        
      // 释放内存
      inputImg.delete();
      out.delete();
      results.delete();
    });
  } catch (error) {
    console.error('OpenCV 初始化失败:', error);
  }
}

init();

Package Sidebar

Install

npm i @shencom/wechat-opencv

Weekly Downloads

43

Version

1.0.0

License

ISC

Unpacked Size

7.97 MB

Total Files

17

Last publish

Collaborators

  • shencom