Skip to content

Instantly share code, notes, and snippets.

@3p3r
Last active July 4, 2016 21:03
Show Gist options
  • Save 3p3r/0b636942406a385097cbd5bcd1130b52 to your computer and use it in GitHub Desktop.
Save 3p3r/0b636942406a385097cbd5bcd1130b52 to your computer and use it in GitHub Desktop.
Zebra Crossing Unity3D WebCam QR Decoder (multi-threaded)
using ZXing;
using ZXing.Common;
using UnityEngine;
using System;
using System.Threading;
using System.Collections.Generic;
/// <summary>
/// Extremely basic usage of BarcodeDecoder in ZXing
/// library to actively decode QR codes from WebCam.
/// You may download ZXing C# binaries from:
/// http://zxingnet.codeplex.com/
/// This is tested with Unity3D 5.3.5f1
///
/// A Single threaded version of this class is available at:
/// https://gist.github.com/sepehr-laal/d52d0ee173c5c28d1f324729b35cb96a
///
/// Attach this script to an object in your scene and
/// hit play. If you hold a QR code in front of your
/// WebCam, its decoded string appears in "decodedResult"
/// </summary>
public class ZXingScanner : MonoBehaviour
{
internal class Data
{
public Color32[] image;
public int imageHeight;
public int imageWidth;
}
public string decodedResult;
WebCamTexture webCamTexture;
BarcodeReader barcodeReader;
Thread barcodeDecoderThread;
TimeSpan barcodeThreadDelay;
volatile bool stopSignal;
volatile bool dataSignal;
volatile Data data;
void Start()
{
var formats = new List<BarcodeFormat>();
formats.Add(BarcodeFormat.QR_CODE);
barcodeReader = new BarcodeReader
{
AutoRotate = false,
Options = new DecodingOptions
{
PossibleFormats = formats,
TryHarder = true,
}
};
webCamTexture = new WebCamTexture();
webCamTexture.Play();
data = new Data { image = null };
dataSignal = true;
stopSignal = false;
barcodeThreadDelay = TimeSpan.FromMilliseconds(1);
barcodeDecoderThread = new Thread(DecodeQR);
barcodeDecoderThread.Start();
}
void Update()
{
if (webCamTexture != null && webCamTexture.isPlaying && dataSignal)
{
data.image = webCamTexture.GetPixels32();
data.imageHeight = webCamTexture.height;
data.imageWidth = webCamTexture.width;
dataSignal = false;
}
}
void DecodeQR()
{
while (!stopSignal)
{
if (!dataSignal)
{
Result result = barcodeReader.Decode(
data.image,
data.imageWidth,
data.imageHeight);
if (result != null)
decodedResult = result.Text;
dataSignal = true;
}
Thread.Sleep(barcodeThreadDelay);
}
}
void OnDestroy()
{
if (webCamTexture != null)
webCamTexture.Stop();
stopSignal = true;
barcodeDecoderThread.Join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment