h5页面实现扫码功能

2022-12-26 16:11:18 浏览数 (1)

目前在做一个移动端扫码功能,发现市面上h5实现扫码功能的案例很少,quagga.js 已经很久没有维护了,而且识别率低,根本用不了

使用webrtc和python 图片识别库实现 h5 页面扫码功能

  1. 使用getUserMedia 获取媒体流
  2. 使用video标签播放媒体流
  3. 使用canvas 将video 截图
  4. 使用定时器定时发送图片到 后端 Python 识别图片

代码 (本代码需要https 协议 getUserMedia(兼容查看) 和本地才能跑通 )

代码语言:javascript复制
var video = document.querySelector(".bar_video");
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 480;
var constraints = { video: { facingMode: "environment" } };
navigator.mediaDevices
  .getUserMedia(constraints)
  .then(function (mediaStream) {
    video.srcObject = mediaStream;
    video.onloadedmetadata = function (e) {
      video.play();
    };
  })
  .catch(function (err) {
    console.log(err.name   ": "   err.message);
  });
setInterval(function () {
  context.drawImage(
    video,
    0,
    0,
    (canvas.width = video.videoWidth),
    (canvas.height = video.videoHeight)
  );
  var image = canvas.toDataURL("image/png");
    $.ajax({
        url: "/product/code",
        type: "post",
        data:{
            phoneCode:image
        },
        success:function(res) {
         
          
        },
        error:function (err) {
           console.log(err) 
        }
      })
  
}, 5000);

后端代码

代码语言:javascript复制
            imgbase = kw.get("phoneCode")  # 接受的图片
            imgbase=imgbase.split(",")[1]
            imgdata = base64.b64decode(imgbase)#解码
            url =os.path.join(os.path.abspath(os.path.dirname(__file__)),"0.png")
            file = open(url, 'wb')#保存为0.png的图片
            file.write(imgdata)
            file.close()
            image=cv2.imread(url)
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            texts = pyzbar.decode(gray)
            print(texts)
            if texts == []:
               return json.dumps({"state": 400})
            for text in texts:
                code = text.data.decode("utf-8")
                print(code)

后端参考文章 https://blog.csdn.net/qq_37924224/article/details/109582507

0 人点赞