- Notifications
You must be signed in to change notification settings - Fork982
An advanced barcode-scanner written in JavaScript
License
serratus/quaggaJS
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real-time localization and decoding of various types of barcodes such asEAN,CODE 128,CODE 39,EAN 8,UPC-A,UPC-C,I2of5,2of5,CODE 93 andCODABAR. The library is also capable of usinggetUserMedia
to get direct access to the user's camera stream. Although thecode relies on heavy image-processing even recent smartphones are capable oflocating and decoding barcodes in real-time.
Try someexamples and check outthe blog post (How barcode-localization works in QuaggaJS)if you want to dive deeper into this topic.
This is not yet another port of the greatzxing library, butmore of an extension to it. This implementation features a barcode locator whichis capable of finding a barcode-like pattern in an image resulting in anestimated bounding box including the rotation. Simply speaking, this reader isinvariant to scale and rotation, whereas other libraries require the barcode tobe aligned with the viewport.
Quagga makes use of many modern Web-APIs which are not implemented by allbrowsers yet. There are two modes in which Quagga operates: 1. analyzing staticimages and 2. using a camera to decode the images from a live-stream. The latterrequires the presence of the MediaDevices API. You can track the compatibilityof the used Web-APIs for each mode:
The following APIs need to be implemented in your browser:
In addition to the APIs mentioned above:
Important: AccessinggetUserMedia
requires a secure origin in mostbrowsers, meaning thathttp://
can only be used onlocalhost
. All otherhostnames need to be served viahttps://
. You can find more information in theChrome M47 WebRTC Release Notes.
Every browser seems to differently implement themediaDevices.getUserMedia
API. Therefore it's highly recommended to includewebrtc-adapter in your project.
Here's how you can test your browser's capabilities:
if(navigator.mediaDevices&&typeofnavigator.mediaDevices.getUserMedia==='function'){// safely access `navigator.mediaDevices.getUserMedia`}
The above condition evaluates to:
Browser | result |
---|---|
Edge | true |
Chrome | true |
Firefox | true |
IE 11 | false |
Safari iOS | true |
QuaggaJS can be installed usingnpm,bower, or by including it withthescript tag.
>npm install quagga
And then import it as dependency in your project:
importQuaggafrom'quagga';// ES6constQuagga=require('quagga').default;// Common JS (important: default)
Currently, the full functionality is only available through the browser. Whenusing QuaggaJS withinnode, only file-based decoding is available. See theexample fornode_examples.
You can also install QuaggaJS throughbower:
>bower install quagga
You can simply includedist/quagga.min.js
in your project and you are readyto go. The script exposes the library on the global namespace underQuagga
.
For starters, have a look at theexamples to get an ideawhere to go from here.
You can build the library yourself by simply cloning the repo and typing:
>npm install>npm run build
This npm script builds a non optimized versionquagga.js
and a minifiedversionquagga.min.js
and places both files in thedist
folder.Additionally, aquagga.map
source-map is placed alongside these files. Thisfile is only valid for the non-uglified versionquagga.js
because theminified version is altered after compression and does not align with the mapfile any more.
The code in thedist
folder is only targeted to the browser and won't work innode due to the dependency on the DOM. For the use in node, thebuild
commandalso creates aquagga.js
file in thelib
folder.
You can check out theexamples to get an idea of how touse QuaggaJS. Basically the library exposes the following API:
This method initializes the library for a given configurationconfig
(seebelow) and invokes thecallback(err)
when Quagga has finished itsbootstrapping phase. The initialization process also requests for cameraaccess if real-time detection is configured. In case of an error, theerr
parameter is set and contains information about the cause. A potential causemay be theinputStream.type
is set toLiveStream
, but the browser doesnot support this API, or simply if the user denies the permission to use thecamera.
If you do not specify a target, QuaggaJS would look for an element that matchesthe CSS selector#interactive.viewport
(for backwards compatibility).target
can be a string (CSS selector matching one of your DOM node) or a DOMnode.
Quagga.init({inputStream :{name :"Live",type :"LiveStream",target:document.querySelector('#yourElement')// Or '#yourElement' (optional)},decoder :{readers :["code_128_reader"]}},function(err){if(err){console.log(err);return}console.log("Initialization finished. Ready to start");Quagga.start();});
When the library is initialized, thestart()
method starts the video-streamand begins locating and decoding the images.
If the decoder is currently running, after callingstop()
the decoder does notprocess any more images. Additionally, if a camera-stream was requested uponinitialization, this operation also disconnects the camera.
This method registers acallback(data)
function that is called for each frameafter the processing is done. Thedata
object contains detailed informationabout the success/failure of the operation. The output varies, depending whetherthe detection and/or decoding were successful or not.
Registers acallback(data)
function which is triggered whenever a barcode-pattern has been located and decoded successfully. The passeddata
objectcontains information about the decoding process including the detected codewhich can be obtained by callingdata.codeResult.code
.
In contrast to the calls described above, this method does not rely ongetUserMedia
and operates on a single image instead. The provided callbackis the same as inonDetected
and contains the resultdata
object.
In case theonProcessed
event is no longer relevant,offProcessed
removesthe givenhandler
from the event-queue.
In case theonDetected
event is no longer relevant,offDetected
removesthe givenhandler
from the event-queue.
The callbacks passed intoonProcessed
,onDetected
anddecodeSingle
receive adata
object upon execution. Thedata
object contains the followinginformation. Depending on the success, some fields may beundefined
or justempty.
{"codeResult":{"code":"FANAVF1461710",// the decoded code as a string"format":"code_128",// or code_39, codabar, ean_13, ean_8, upc_a, upc_e"start":355,"end":26,"codeset":100,"startInfo":{"error":1.0000000000000002,"code":104,"start":21,"end":41},"decodedCodes":[{"code":104,"start":21,"end":41},// stripped for brevity{"error":0.8888888888888893,"code":106,"start":328,"end":350}],"endInfo":{"error":0.8888888888888893,"code":106,"start":328,"end":350},"direction":-1},"line":[{"x":25.97278706156836,"y":360.5616435369468},{"x":401.9220519377024,"y":70.87524989906444}],"angle":-0.6565217179979483,"pattern":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,/* ... */1],"box":[[77.4074243622672,410.9288668804402],[0.050203235235130705,310.53619724086366],[360.15706727788256,33.05711026051813],[437.5142884049146,133.44977990009465]],"boxes":[[[77.4074243622672,410.9288668804402],[0.050203235235130705,310.53619724086366],[360.15706727788256,33.05711026051813],[437.5142884049146,133.44977990009465]],[[248.90769330706507,415.2041489551161],[198.9532321622869,352.62160512937635],[339.546160777576,240.3979259789976],[389.5006219223542,302.98046980473737]]]}
The configuration that ships with QuaggaJS covers the default use-cases and canbe fine-tuned for specific requirements.
The configuration is managed by theconfig
object defining the followinghigh-level properties:
{numOfWorkers:4,locate:true,inputStream:{...},frequency:10,decoder:{...},locator:{...},debug:false,}
QuaggaJS supports web-workers out of the box and runs with4
workers in itsdefault configuration. The number should align with the number of coresavailable in your targeted devices.
In case you don't know the number upfront, or if the variety of devices istoo big, you can either usenavigator.hardwareConcurrency
(seehere) where availableor make use ofcore-estimator.
One of the main features of QuaggaJS is its ability to locate a barcode in agiven image. Thelocate
property controls whether this feature is turned on(default) or off.
Why would someone turn this feature off? Localizing a barcode is acomputationally expensive operation and might not work properly on somedevices. Another reason would be the lack of auto-focus producing blurryimages which makes the localization feature very unstable.
However, even if none of the above apply, there is one more case where it mightbe useful to disablelocate
: If the orientation, and/or the approximateposition of the barcode is known, or if you want to guide the user through arectangular outline. This can increase performance and robustness at the sametime.
TheinputStream
property defines the sources of images/videos within QuaggaJS.
{name:"Live",type:"LiveStream",constraints:{width:640,height:480,facingMode:"environment",deviceId:"7832475934759384534"},area:{// defines rectangle of the detection/localization areatop:"0%",// top offsetright:"0%",// right offsetleft:"0%",// left offsetbottom:"0%"// bottom offset},singleChannel:false// true: only the red color-channel is read}
First, thetype
property can be set to three different values:ImageStream
,VideoStream
, orLiveStream
(default) and should be selecteddepending on the use-case. Most probably, the default value is sufficient.
Second, theconstraint
key defines the physical dimensions of the input imageand additional properties, such asfacingMode
which sets the source of theuser's camera in case of multiple attached devices. Additionally, if required,thedeviceId
can be set if the selection of the camera is given to the user.This can be easily achieved viaMediaDevices.enumerateDevices()
Thirdly, thearea
prop restricts the decoding area of the image. The valuesare given in percentage, similar to the CSS style property when usingposition: absolute
. Thisarea
is also useful in cases thelocate
propertyis set tofalse
, defining the rectangle for the user.
The last keysingleChannel
is only relevant in cases someone wants to debugerroneous behavior of the decoder. If set totrue
the input image's redcolor-channel is read instead of calculating the gray-scale values of thesource's RGB. This is useful in combination with theResultCollector
wherethe gray-scale representations of the wrongly identified images are saved.
This top-level property controls the scan-frequency of the video-stream. It'soptional and defines the maximum number of scans per second. This rendersuseful for cases where the scan-session is long-running and resources such asCPU power are of concern.
QuaggaJS usually runs in a two-stage manner (locate
is set totrue
) where,after the barcode is located, the decoding process starts. Decoding is theprocess of converting the bars into its true meaning. Most of the configurationoptions within thedecoder
are for debugging/visualization purposes only.
{readers:['code_128_reader'],debug:{drawBoundingBox:false,showFrequency:false,drawScanline:false,showPattern:false}multiple:false}
The most important property isreaders
which takes an array of types ofbarcodes which should be decoded during the session. Possible values are:
- code_128_reader (default)
- ean_reader
- ean_8_reader
- code_39_reader
- code_39_vin_reader
- codabar_reader
- upc_reader
- upc_e_reader
- i2of5_reader
- 2of5_reader
- code_93_reader
Why are not all types activated by default? Simply because one shouldexplicitly define the set of barcodes for their use-case. More decoders meansmore possible clashes, or false-positives. One should take care of the orderthe readers are given, since some might return a value even though it is notthe correct type (EAN-13 vs. UPC-A).
Themultiple
property tells the decoder if it should continue decoding afterfinding a valid barcode. If multiple is set totrue
, the results will bereturned as an array of result objects. Each object in the array will have abox
, and may have acodeResult
depending on the success of decoding theindividual box.
The remaining propertiesdrawBoundingBox
,showFrequency
,drawScanline
andshowPattern
are mostly of interest during debugging and visualization.
The default setting forean_reader
is not capable of reading extensions suchasEAN-2 orEAN-5. In order to activate thosesupplements you have to provide them in the configuration as followed:
decoder:{readers:[{format:"ean_reader",config:{supplements:['ean_5_reader','ean_2_reader']}}]}
Beware that the order of thesupplements
matters in such that the reader stopsdecoding when the first supplement was found. So if you are interested in EAN-2and EAN-5 extensions, use the order depicted above.
It's important to mention that, if supplements are supplied, regular EAN-13codes cannot be read any more with the same reader. If you want to read EAN-13with and without extensions you have to add anotherean_reader
reader to theconfiguration.
Thelocator
config is only relevant if thelocate
flag is set totrue
.It controls the behavior of the localization-process and needs to be adjustedfor each specific use-case. The default settings are simply a combination ofvalues which worked best during development.
Only two properties are relevant for the use in Quagga (halfSample
andpatchSize
) whereas the rest is only needed for development and debugging.
{halfSample:true,patchSize:"medium",// x-small, small, medium, large, x-largedebug:{showCanvas:false,showPatches:false,showFoundPatches:false,showSkeleton:false,showLabels:false,showPatchLabels:false,showRemainingPatchLabels:false,boxFromPatches:{showTransformed:false,showTransformedBox:false,showBB:false}}}
ThehalfSample
flag tells the locator-process whether it should operate on animage scaled down (half width/height, quarter pixel-count ) or not. TurninghalfSample
on reduces the processing-time significantly and also helpsfinding a barcode pattern due to implicit smoothing.It should be turned off in cases where the barcode is really small and the fullresolution is needed to find the position. It's recommended to keep it turnedon and use a higher resolution video-image if needed.
The second propertypatchSize
defines the density of the search-grid. Theproperty accepts strings of the valuex-small
,small
,medium
,large
andx-large
. ThepatchSize
is proportional to the size of the scanned barcodes.If you have really large barcodes which can be read close-up, then the use oflarge
orx-large
is recommended. In cases where the barcode is further awayfrom the camera lens (lack of auto-focus, or small barcodes) then it's advisedto set the size tosmall
or evenx-small
. For the latter it's alsorecommended to crank up the resolution in order to find a barcode.
The following example takes an imagesrc
as input and prints the result on theconsole. The decoder is configured to detectCode128 barcodes and enables thelocating-mechanism for more robust results.
Quagga.decodeSingle({decoder:{readers:["code_128_reader"]// List of active readers},locate:true,// try to locate the barcode in the imagesrc:'/test/fixtures/code_128/image-001.jpg'// or 'data:image/jpg;base64,' + data},function(result){if(result.codeResult){console.log("result",result.codeResult.code);}else{console.log("not detected");}});
The following example illustrates the use of QuaggaJS within a nodeenvironment. It's almost identical to the browser version with the differencethat node does not support web-workers out of the box. Therefore the configpropertynumOfWorkers
must be explicitly set to0
.
varQuagga=require('quagga').default;Quagga.decodeSingle({src:"image-abc-123.jpg",numOfWorkers:0,// Needs to be 0 when used within nodeinputStream:{size:800// restrict input-size to be 800px in width (long-side)},decoder:{readers:["code_128_reader"]// List of active readers},},function(result){if(result.codeResult){console.log("result",result.codeResult.code);}else{console.log("not detected");}});
A growing collection of tips & tricks to improve the various aspects of Quagga.
Barcodes too far away from the camera, or a lens too close to the objectresult in poor recognition rates and Quagga might respond with a lot offalse-positives.
Starting in Chrome 59 you can now make use ofcapabilities
and directlycontrol the zoom of the camera. Head over to theweb-cam demoand check out theZoom feature.
You can read more about thosecapabilities
inLet's light a torch and explore MediaStreamTrack's capabilities
Dark environments usually result in noisy images and therefore mess with therecognition logic.
Since Chrome 59 you can turn on/off theTorch of our device and vastlyimprove the quality of the images. Head over to theweb-cam demoand check out theTorch feature.
To find out more about this featureread on.
Unit Tests can be run withKarma and written usingMocha,Chai andSinonJS. Coverage reports areautomatically generated in the coverage/ folder.
>npm install>npm runtest
In case you want to take a deeper dive into the inner workings of Quagga, get toknow thedebugging capabilities of the current implementation. The variousflags exposed through theconfig
object give you the abilily to visualizealmost every step in the processing. Because of the introduction of theweb-workers, and their restriction not to have access to the DOM, theconfiguration must be explicitly set toconfig.numOfWorkers = 0
in order towork.
Quagga is not perfect by any means and may produce false positives from timeto time. In order to find out which images produced those false positives,the built-inResultCollector
will support you and me helping squashingbugs in the implementation.
You can easily create a newResultCollector
by calling itscreate
method with a configuration.
varresultCollector=Quagga.ResultCollector.create({capture:true,// keep track of the image producing this resultcapacity:20,// maximum number of results to storeblacklist:[// list containing codes which should not be recorded{code:"3574660239843",format:"ean_13"}],filter:function(codeResult){// only store results which match this constraint// returns true/false// e.g.: return codeResult.format === "ean_13";returntrue;}});
After creating aResultCollector
you have to attach it to Quagga bycallingQuagga.registerResultCollector(resultCollector)
.
After a test/recording session, you can now print the collected results whichdo not fit into a certain schema. CallinggetResults
on theresultCollector
returns anArray
containing objects with:
{codeResult:{},// same as in onDetected eventframe:"data:image/png;base64,iVBOR..."// dataURL of the gray-scaled image}
Theframe
property is an internal representation of the image andtherefore only available in gray-scale. The dataURL representation allowseasy saving/rendering of the image.
Now, having the frames available on disk, you can load each single image bycallingdecodeSingle
with the same configuration as used during recording. In order to reproduce the exact same result, you have to make sure to turnon thesingleChannel
flag in the configuration when usingdecodeSingle
.
- Improvements
- added
muted
andplaysinline
to<video/>
to make it work for Safari 11Beta (even iOS)
- added
- Fixes
- Features
- Support for Standard 2of5 barcodes (See#194)
- Support for Code 93 barcodes (See#194)
- Exposing
Quagga.CameraAccess.getActiveTrack()
to get access to thecurrently usedMediaStreamTrack
- Example can be viewed here:example/live_w_locator.js and ademo
Take a look at the release-notes (0.12.0)
- Improvements
- Exposing
CameraAccess
module to get access to methods likeenumerateVideoDevices
andgetActiveStreamLabel
(seeexample/live_w_locator
) - Update to webpack 2.2 (API is still unstable)
- Exposing
- Fixes
- Fixed
facingMode
issue with Chrome >= 53 (see#128)
- Fixed
- Features
- Proper handling of EXIF orientation when using
Quagga.decodeSingle
(see#121)
- Proper handling of EXIF orientation when using
- Features
- EAN-13 extended codes can now be decoded (See#71)
Take a look at the release-notes (0.11.0)
- Improvements
- Reducing false-positives for Code 128 barcodes (addresses#104)
Take a look at the release-notes (0.10.0)
- Internal Changes
- Restructuring into meaningful folders
- Removing debug-code in production build
Take a look at the release-notes (0.9.0)
- Fixes
- Fixed inconsistencies for Code 128 decoding (See#76)
- Fixes
- Fixed inconsistency in Code 39 decoding
- added inline-source-map to quagga.js file
Take a look at the release-notes ([0.8.0](https://github.com/serratus/quaggaJS/releases/tag/v0.8.0))
- Improvements
- Replaced RequireJS with webpack
Take a look at the release-notes ([0.7.0](https://github.com/serratus/quaggaJS/releases/tag/v0.7.0))
- Features
- Added basic support for running QuaggaJS insidenode (see [example](#node-example))
- Improvements
- Added support for Internet Explorer (only Edge+ supports
getUserMedia
)
- Added support for Internet Explorer (only Edge+ supports
- Improvements
- Added
offProcessed
andoffDetected
methods for detaching event-listeners from the event-queue.
- Added
- Features
- Added basic support forITF barcodes (
i2of5_reader
)
- Added basic support forITF barcodes (
- Improvements
- Parameter tweaking to reduce false-positives significantly (for theentire EAN and UPC family)
- Fixing bug in parity check for UPC-E codes
- Fixing bug in alignment for EAN-8 codes
- Improvements
- Added
err
parameter toQuagga.init() callbackfunction
- Added
- Features
- Added
singleChannel
configuration toinputStream
(in [config](#configobject)) - Added
ResultCollector
functionality (see [ResultCollector](#resultcollector))
- Added
- Improvements
- Added
format
property tocodeResult
(inresult)
- Added
- Improvements
- Added fixes for
Code39Reader
(trailing whitespace was missing)
- Added fixes for
- Features
- Introduced the
area
property - Ability to define a rectangle where localization/decoding should be applied
- Introduced the
- Improvements
- Making EAN and UPC readers even more restrictive
- Added example using requirejs
- Improvements
- Making EAN and UPC readers more restrictive
- Added integration-tests for all barcode-readers
- Improvements
- Odd image dimensions no longer cause problems
- Features
- Added support forUPC-A and UPC-E barcodes
- Added support forEAN-8 barcodes
- Improvements
- Added extended configuration to the live-video example
- Releasing resources when calling
Quagga.stop()
- Improvements
- Added extended configuration to the file-input example
- Configurable
patchSize
for better adjustment to small/medium/largebarcodes
- Features
- Added support forCodabar barcodes
- Improvements
- now includes minified version (23.3KB gzipped)
- No need for configuration of script-name any more
- Improvements
- removed dependency on async.js
- Features
- Added support forCode 39 barcodes
- Features
- Added support for web-worker (using 4 workers as default, can be changedthrough
config.numOfWorkers
) - Due to the way how web-workers are created, the name of the script file(
config.scriptName
) should be kept in sync with your actual filename - Removed canvas-overlay for decoding (boxes & scanline) which can now beeasily implemented using the existing API (see example)
- Added support for web-worker (using 4 workers as default, can be changedthrough
- API ChangesIn the course of implementing web-workers some breaking changes wereintroduced to the API.
- The
Quagga.init
function no longer receives the callback as part of theconfig but rather as a second argument:Quagga.init(config, cb)
- The callback to
Quagga.onDetected
now receives an object containingmuch more information in addition to the decoded code.(seedata) - Added
Quagga.onProcessed(callback)
which provides a way to get informationfor each image processed. The callback receives the samedata
object asQuagga.onDetected
does. Depending on the success of the process thedata
object might not contain anyresultCode
and/orbox
properties.
- The
About
An advanced barcode-scanner written in JavaScript