Hololens 二维码识别

Unity+Hololens二维码识别

文章下方附带zxing.unity.dll文件和Unity项目源码

进行二维码识别之前,需要对Hololens的开发环境进行配置,以及Unity开发Hololens需要的一些设置,介绍文章很多,不多说了。

开发环境
Unity 2018.4.14 (IL2CPP模式下)
Hololens 1代
VS 2019

识别二维码是基于zxing.unity.dll,需要放在Plugins文件夹下,并设置为所有平台通用
Hololens 二维码识别_第1张图片

上代码

using UnityEngine;
using System.Collections;
using ZXing;
using UnityEngine.UI;
using System.Threading;
using System;

public class QRcode : MonoBehaviour
{
    ///  包含RGBA 
    private Color32[] data;
    ///  相机捕捉到的图像 
    private WebCamTexture webCameraTexture;
    ///  ZXing中的方法,可读取二维码中的内容 
    private BarcodeReader barcodeReader;
    ///  计时,0.5s扫描一次 
    private int timer = 500;

    public Text QRcodeText;
    public Animation scanAni;
    public AudioSource audio;
    public RawImage cameraTexture;

    Thread thread;

    public System.Collections.Concurrent.ConcurrentQueue<System.Action> _MainThreadQueue =
         new System.Collections.Concurrent.ConcurrentQueue<Action>();

    /// 
    /// 初始化
    /// 
    /// 
    IEnumerator Start()
    {
        barcodeReader = new BarcodeReader();
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//请求授权使用摄像头
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;//获取摄像头设备
            string devicename = devices[0].name;
            webCameraTexture = new WebCamTexture(devicename, 400, 300);//获取摄像头捕捉到的画面

            cameraTexture.enabled = true;
            cameraTexture.texture = webCameraTexture;

            webCameraTexture.Play();
            scanAni.Play();

            thread = new Thread(ScanQRcode);
            thread.Start();
        }

    }

    void Update()
    {
        while (_MainThreadQueue.Count > 0)
        {
            if (_MainThreadQueue.TryDequeue(out Action func))
            {
                func?.Invoke();
            }
        }
    }

    private void OnDisable()
    {
        thread.Abort();
    }

    /// 
    /// 子线程
    /// 
    private void ScanQRcode()
    {
        while (true)
        {
            _MainThreadQueue.Enqueue(() =>
             {
                 data = webCameraTexture.GetPixels32();//相机捕捉到的纹理
                 DecodeQR(webCameraTexture.width, webCameraTexture.height);
             });
            Thread.Sleep(timer);
        }
    }

    /// 
    /// 识别二维码并显示其中包含的文字、URL等信息
    /// 
    /// 相机捕捉到的纹理的宽度
    /// 相机捕捉到的纹理的高度
    private void DecodeQR(int width, int height)
    {
        var br = barcodeReader.Decode(data, width, height);
        if (br != null)
        {
            QRcodeText.text = br.Text;
            audio.Play();
        }
        else
        {
            QRcodeText.text = "";
        }
    }
}

效果展示
(这是电脑上测试,Hololens 1代亲测OK)
Hololens 二维码识别_第2张图片

文章参考

zxing.unity.dll 提取码:881g

Unity项目源码 提取码:ju0k

你可能感兴趣的:(Unity+Hololens)