@ericblade/quagga2 1.5.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,842 +1,860 @@
1
- quagga2
2
- =======
3
-
4
- [![Rolling Versions](https://img.shields.io/badge/Rolling%20Versions-Enabled-brightgreen)](https://rollingversions.com/ericblade/quagga2)
5
-
6
- [![Join the chat at https://gitter.im/quaggaJS/Lobby](https://badges.gitter.im/quaggaJS/Lobby.svg)](https://gitter.im/quaggaJS/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
7
-
8
- [![Rate on Openbase](https://badges.openbase.io/js/rating/@ericblade/quagga2.svg)](https://openbase.io/js/@ericblade/quagga2?utm_source=embedded&utm_medium=badge&utm_campaign=rate-badge)
9
-
10
- This is a fork of the original QuaggaJS library, that will be maintained until such time as the
11
- original author and maintainer returns, or it has been completely replaced by built-in browser and
12
- node functionality.
13
-
14
- - [Changelog](CHANGELOG.md)
15
- - [Browser Support](#browser-support)
16
- - [Installing](#installing)
17
- - [Getting Started](#gettingstarted)
18
- - [Using with React](#usingwithreact)
19
- - [Using External Readers](#usingexternalreaders)
20
- - [API](#api)
21
- - [Configuration](#configobject)
22
- - [Tips & Tricks](#tipsandtricks)
23
-
24
- ## Using React / Redux?
25
-
26
- Please see also https://github.com/ericblade/quagga2-react-example/ and https://github.com/ericblade/quagga2-redux-middleware/
27
-
28
- ## What is QuaggaJS?
29
-
30
- QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real-
31
- time localization and decoding of various types of barcodes such as __EAN__,
32
- __CODE 128__, __CODE 39__, __EAN 8__, __UPC-A__, __UPC-C__, __I2of5__,
33
- __2of5__, __CODE 93__, __CODE 32__ and __CODABAR__. The library is also capable of using
34
- `getUserMedia` to get direct access to the user's camera stream. Although the
35
- code relies on heavy image-processing even recent smartphones are capable of
36
- locating and decoding barcodes in real-time.
37
-
38
- Try some [examples](https://serratus.github.io/quaggaJS/examples) and check out
39
- the blog post ([How barcode-localization works in QuaggaJS][oberhofer_co_how])
40
- if you want to dive deeper into this topic.
41
-
42
- ![teaser][teaser_left]![teaser][teaser_right]
43
-
44
- ## Yet another barcode library?
45
-
46
- This is not yet another port of the great [zxing][zxing_github] library, but
47
- more of an extension to it. This implementation features a barcode locator which
48
- is capable of finding a barcode-like pattern in an image resulting in an
49
- estimated bounding box including the rotation. Simply speaking, this reader is
50
- invariant to scale and rotation, whereas other libraries require the barcode to
51
- be aligned with the viewport.
52
-
53
- ## <a name="browser-support">Browser Support</a>
54
-
55
- Quagga makes use of many modern Web-APIs which are not implemented by all
56
- browsers yet. There are two modes in which Quagga operates:
57
- 1. analyzing static images and
58
- 2. using a camera to decode the images from a live-stream.
59
-
60
- The latter requires the presence of the MediaDevices API. You can track the compatibility
61
- of the used Web-APIs for each mode:
62
-
63
- - [Static Images](http://caniuse.com/#feat=webworkers,canvas,typedarrays,bloburls,blobbuilder)
64
- - [Live Stream](http://caniuse.com/#feat=webworkers,canvas,typedarrays,bloburls,blobbuilder,stream)
65
-
66
- ### Static Images
67
-
68
- The following APIs need to be implemented in your browser:
69
- - [webworkers](http://caniuse.com/#feat=webworkers)
70
- - [canvas](http://caniuse.com/#feat=canvas)
71
- - [typedarrays](http://caniuse.com/#feat=typedarrays)
72
- - [bloburls](http://caniuse.com/#feat=bloburls)
73
- - [blobbuilder](http://caniuse.com/#feat=blobbuilder)
74
-
75
- ### Live Stream
76
-
77
- In addition to the APIs mentioned above:
78
- - [MediaDevices](http://caniuse.com/#feat=stream)
79
-
80
- __Important:__ Accessing `getUserMedia` requires a secure origin in most
81
- browsers, meaning that `http://` can only be used on `localhost`. All other
82
- hostnames need to be served via `https://`. You can find more information in the
83
- [Chrome M47 WebRTC Release Notes](https://groups.google.com/forum/#!topic/discuss-webrtc/sq5CVmY69sc).
84
-
85
- ### Feature-detection of getUserMedia
86
-
87
- Every browser seems to differently implement the `mediaDevices.getUserMedia`
88
- API. Therefore it's highly recommended to include
89
- [webrtc-adapter](https://github.com/webrtc/adapter) in your project.
90
-
91
- Here's how you can test your browser's capabilities:
92
-
93
- ```javascript
94
- if (navigator.mediaDevices && typeof navigator.mediaDevices.getUserMedia === 'function') {
95
- // safely access `navigator.mediaDevices.getUserMedia`
96
- }
97
- ```
98
-
99
- The above condition evaluates to:
100
-
101
- | Browser | result |
102
- | ------------- |:-------:|
103
- | Edge | `true` |
104
- | Chrome | `true` |
105
- | Firefox | `true` |
106
- | IE 11 | `false` |
107
- | Safari iOS | `true` |
108
-
109
- ## <a name="installing">Installing</a>
110
-
111
- Quagga2 can be installed using __npm__, or by including it with the __script__ tag.
112
-
113
- ### NPM
114
-
115
- ```console
116
- > npm install --save @ericblade/quagga2
117
- ```
118
-
119
- And then import it as dependency in your project:
120
-
121
- ```javascript
122
- import Quagga from '@ericblade/quagga2'; // ES6
123
- const Quagga = require('@ericblade/quagga2').default; // Common JS (important: default)
124
- ```
125
-
126
- Currently, the full functionality is only available through the browser. When
127
- using QuaggaJS within __node__, only file-based decoding is available. See the
128
- example for [node_examples](#node-example).
129
-
130
- ### Using with script tag
131
-
132
- You can simply include `quagga.js` in your project and you are ready
133
- to go. The script exposes the library on the global namespace under `Quagga`.
134
-
135
- ```html
136
- <script src="quagga.js"></script>
137
- ```
138
-
139
- You can get the `quagga.js` file in the following ways:
140
-
141
- By [installing the npm module](https://github.com/ericblade/quagga2#npm) and copying the `quagga.js` file from the `dist` folder.
142
-
143
- <p align="center">(OR)</p>
144
-
145
- You can also build the library yourself and copy `quagga.js` file from the `dist` folder(refer to the [building](https://github.com/ericblade/quagga2#building) section for more details)
146
-
147
- <p align="center">(OR)</p>
148
-
149
- You can include the following script tags with CDN links:
150
-
151
- a) `quagga.js`
152
- ```html
153
- <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>
154
- ```
155
- b) `quagga.min.js` (minified version)
156
- ```html
157
- <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.min.js"></script>
158
- ```
159
- *Note: You can include a specific version of the library by including the version as shown below.*
160
- ```html
161
- <!-- Link for Version 1.2.6 -->
162
- <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2@1.2.6/dist/quagga.js"></script>
163
- ```
164
-
165
- ## <a name="gettingstarted">Getting Started</a>
166
-
167
- For starters, have a look at the [examples][github_examples] to get an idea
168
- where to go from here.
169
-
170
- ## <a name="usingwithreact">Using with React</a>
171
-
172
- There is a separate [example][reactExample] for using quagga2 with ReactJS
173
-
174
- ## <a name="usingwithexternalreaders">Using with External Readers</a>
175
-
176
- New in Quagga2 is the ability to specify external reader modules. Please see [quagga2-reader-qr](https://github.com/ericblade/quagga2-reader-qr). This repository includes a sample external reader that can
177
- read complete images, and decode QR codes. A test script is included to demonstrate how to use an
178
- external reader in your project.
179
-
180
- Quagga2 exports the BarcodeReader prototype, which should also allow you to create new barcode
181
- reader implementations using the base BarcodeReader implementation inside Quagga2. The QR reader
182
- does not make use of this functionality, as QR is not picked up as a barcode in BarcodeReader.
183
-
184
- ## <a name="Building">Building</a>
185
-
186
- You can build the library yourself by simply cloning the repo and typing:
187
-
188
- ```console
189
- > npm install
190
- > npm run build
191
- ```
192
-
193
- or using Docker:
194
-
195
- ```console
196
- > docker build --tag quagg2/build .
197
- > docker run -v $(pwd):/quagga2 quagga2/build npm install
198
- > docker run -v $(pwd):/quagga2 quagga2/build npm run build
199
- ```
200
-
201
- it's also possible to use docker-compose:
202
-
203
- ```console
204
- > docker-compose run nodejs npm install
205
- > docker-compose run nodejs npm run build
206
- ```
207
-
208
- *Note: when using Docker or docker-compose the build artifacts will end up in `dist/` as usual thanks to the bind-mount.*
209
-
210
- This npm script builds a non optimized version `quagga.js` and a minified
211
- version `quagga.min.js` and places both files in the `dist` folder.
212
- Additionally, a `quagga.map` source-map is placed alongside these files. This
213
- file is only valid for the non-uglified version `quagga.js` because the
214
- minified version is altered after compression and does not align with the map
215
- file any more.
216
-
217
- ## <a name="WorkingWithDev">Working with a development version from another project</a>
218
-
219
- If you are working on a project that includes quagga, but you need to use a development version of
220
- quagga, then you can run from the quagga directory:
221
-
222
- ```
223
- npm install && npm run build && npm link
224
- ```
225
- then from the other project directory that needs this quagga, do
226
- ```
227
- npm link @ericblade/quagga2
228
- ```
229
- When linking is successful, all future runs of 'npm run build' will update the version that is
230
- linked in the project. When combined with an application using webpack-dev-server or some other
231
- hot-reload system, you can do very rapid iteration this way.
232
-
233
- ### Node
234
-
235
- The code in the `dist` folder is only targeted to the browser and won't work in
236
- node due to the dependency on the DOM. For the use in node, the `build` command
237
- also creates a `quagga.js` file in the `lib` folder.
238
-
239
- ## <a name="api">API</a>
240
-
241
- You can check out the [examples][github_examples] to get an idea of how to
242
- use QuaggaJS. Basically the library exposes the following API:
243
-
244
- ### <a name="quaggainit">Quagga.init(config, callback)</a>
245
-
246
- This method initializes the library for a given configuration `config` (see
247
- below) and invokes the `callback(err)` when Quagga has finished its
248
- bootstrapping phase. The initialization process also requests for camera
249
- access if real-time detection is configured. In case of an error, the `err`
250
- parameter is set and contains information about the cause. A potential cause
251
- may be the `inputStream.type` is set to `LiveStream`, but the browser does
252
- not support this API, or simply if the user denies the permission to use the
253
- camera.
254
-
255
- If you do not specify a target, QuaggaJS would look for an element that matches
256
- the CSS selector `#interactive.viewport` (for backwards compatibility).
257
- `target` can be a string (CSS selector matching one of your DOM node) or a DOM
258
- node.
259
-
260
- ```javascript
261
- Quagga.init({
262
- inputStream : {
263
- name : "Live",
264
- type : "LiveStream",
265
- target: document.querySelector('#yourElement') // Or '#yourElement' (optional)
266
- },
267
- decoder : {
268
- readers : ["code_128_reader"]
269
- }
270
- }, function(err) {
271
- if (err) {
272
- console.log(err);
273
- return
274
- }
275
- console.log("Initialization finished. Ready to start");
276
- Quagga.start();
277
- });
278
- ```
279
-
280
- ### Quagga.start()
281
-
282
- When the library is initialized, the `start()` method starts the video-stream
283
- and begins locating and decoding the images.
284
-
285
- ### Quagga.stop()
286
-
287
- If the decoder is currently running, after calling `stop()` the decoder does not
288
- process any more images. Additionally, if a camera-stream was requested upon
289
- initialization, this operation also disconnects the camera.
290
-
291
- ### Quagga.onProcessed(callback)
292
-
293
- This method registers a `callback(data)` function that is called for each frame
294
- after the processing is done. The `data` object contains detailed information
295
- about the success/failure of the operation. The output varies, depending whether
296
- the detection and/or decoding were successful or not.
297
-
298
- ### Quagga.onDetected(callback)
299
-
300
- Registers a `callback(data)` function which is triggered whenever a barcode-
301
- pattern has been located and decoded successfully. The passed `data` object
302
- contains information about the decoding process including the detected code
303
- which can be obtained by calling `data.codeResult.code`.
304
-
305
- ### Quagga.decodeSingle(config, callback)
306
-
307
- In contrast to the calls described above, this method does not rely on
308
- `getUserMedia` and operates on a single image instead. The provided callback
309
- is the same as in `onDetected` and contains the result `data` object.
310
-
311
- ### Quagga.offProcessed(handler)
312
-
313
- In case the `onProcessed` event is no longer relevant, `offProcessed` removes
314
- the given `handler` from the event-queue. When no handler is passed, all handlers are removed.
315
-
316
- ### Quagga.offDetected(handler)
317
-
318
- In case the `onDetected` event is no longer relevant, `offDetected` removes
319
- the given `handler` from the event-queue. When no handler is passed, all handlers are removed.
320
-
321
- ## <a name="resultobject">The result object</a>
322
-
323
- The callbacks passed into `onProcessed`, `onDetected` and `decodeSingle`
324
- receive a `data` object upon execution. The `data` object contains the following
325
- information. Depending on the success, some fields may be `undefined` or just
326
- empty.
327
-
328
- ```javascript
329
- {
330
- "codeResult": {
331
- "code": "FANAVF1461710", // the decoded code as a string
332
- "format": "code_128", // or code_39, codabar, ean_13, ean_8, upc_a, upc_e
333
- "start": 355,
334
- "end": 26,
335
- "codeset": 100,
336
- "startInfo": {
337
- "error": 1.0000000000000002,
338
- "code": 104,
339
- "start": 21,
340
- "end": 41
341
- },
342
- "decodedCodes": [{
343
- "code": 104,
344
- "start": 21,
345
- "end": 41
346
- },
347
- // stripped for brevity
348
- {
349
- "error": 0.8888888888888893,
350
- "code": 106,
351
- "start": 328,
352
- "end": 350
353
- }],
354
- "endInfo": {
355
- "error": 0.8888888888888893,
356
- "code": 106,
357
- "start": 328,
358
- "end": 350
359
- },
360
- "direction": -1
361
- },
362
- "line": [{
363
- "x": 25.97278706156836,
364
- "y": 360.5616435369468
365
- }, {
366
- "x": 401.9220519377024,
367
- "y": 70.87524989906444
368
- }],
369
- "angle": -0.6565217179979483,
370
- "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],
371
- "box": [
372
- [77.4074243622672, 410.9288668804402],
373
- [0.050203235235130705, 310.53619724086366],
374
- [360.15706727788256, 33.05711026051813],
375
- [437.5142884049146, 133.44977990009465]
376
- ],
377
- "boxes": [
378
- [
379
- [77.4074243622672, 410.9288668804402],
380
- [0.050203235235130705, 310.53619724086366],
381
- [360.15706727788256, 33.05711026051813],
382
- [437.5142884049146, 133.44977990009465]
383
- ],
384
- [
385
- [248.90769330706507, 415.2041489551161],
386
- [198.9532321622869, 352.62160512937635],
387
- [339.546160777576, 240.3979259789976],
388
- [389.5006219223542, 302.98046980473737]
389
- ]
390
- ]
391
- }
392
- ```
393
-
394
- ## <a name="configobject">Configuration</a>
395
-
396
- The configuration that ships with QuaggaJS covers the default use-cases and can
397
- be fine-tuned for specific requirements.
398
-
399
- The configuration is managed by the `config` object defining the following
400
- high-level properties:
401
-
402
- ```javascript
403
- {
404
- numOfWorkers: 4,
405
- locate: true,
406
- inputStream: {...},
407
- frequency: 10,
408
- decoder:{...},
409
- locator: {...},
410
- debug: false,
411
- }
412
- ```
413
-
414
- ### numOfWorkers
415
-
416
- NOTE: As of quagga2 v0.0.13, numOfWorkers has been *disabled*. The library needs a major restructuring
417
- to properly handle Worker threads, and that restructuring is on-going at the moment, to solve other
418
- problems as well. It will be re-enabled in the future. As a result, the numOfWorkers setting is ALWAYS 0.
419
-
420
- ~~QuaggaJS supports web-workers out of the box and runs with `4` workers in its
421
- default configuration. The number should align with the number of cores
422
- available in your targeted devices.~~
423
-
424
- ~~In case you don't know the number upfront, or if the variety of devices is
425
- too big, you can either use `navigator.hardwareConcurrency` (see
426
- [here](https://wiki.whatwg.org/wiki/Navigator_HW_Concurrency)) where available
427
- or make use of [core-estimator](https://github.com/oftn/core-estimator).~~
428
-
429
- ### locate
430
-
431
- One of the main features of QuaggaJS is its ability to locate a barcode in a
432
- given image. The `locate` property controls whether this feature is turned on
433
- (default) or off.
434
-
435
- Why would someone turn this feature off? Localizing a barcode is a
436
- computationally expensive operation and might not work properly on some
437
- devices. Another reason would be the lack of auto-focus producing blurry
438
- images which makes the localization feature very unstable.
439
-
440
- However, even if none of the above apply, there is one more case where it might
441
- be useful to disable `locate`: If the orientation, and/or the approximate
442
- position of the barcode is known, or if you want to guide the user through a
443
- rectangular outline. This can increase performance and robustness at the same
444
- time.
445
-
446
- ### inputStream
447
-
448
- The `inputStream` property defines the sources of images/videos within QuaggaJS.
449
-
450
- ```javascript
451
- {
452
- name: "Live",
453
- type: "LiveStream",
454
- constraints: {
455
- width: 640,
456
- height: 480,
457
- facingMode: "environment",
458
- deviceId: "7832475934759384534"
459
- },
460
- area: { // defines rectangle of the detection/localization area
461
- top: "0%", // top offset
462
- right: "0%", // right offset
463
- left: "0%", // left offset
464
- bottom: "0%" // bottom offset
465
- },
466
- singleChannel: false // true: only the red color-channel is read
467
- }
468
- ```
469
-
470
- First, the `type` property can be set to three different values:
471
- `ImageStream`, `VideoStream`, or `LiveStream` (default) and should be selected
472
- depending on the use-case. Most probably, the default value is sufficient.
473
-
474
- Second, the `constraint` key defines the physical dimensions of the input image
475
- and additional properties, such as `facingMode` which sets the source of the
476
- user's camera in case of multiple attached devices. Additionally, if required,
477
- the `deviceId` can be set if the selection of the camera is given to the user.
478
- This can be easily achieved via
479
- [MediaDevices.enumerateDevices()][enumerateDevices]
480
-
481
- Thirdly, the `area` prop restricts the decoding area of the image. The values
482
- are given in percentage, similar to the CSS style property when using
483
- `position: absolute`. This `area` is also useful in cases the `locate` property
484
- is set to `false`, defining the rectangle for the user.
485
-
486
- The last key `singleChannel` is only relevant in cases someone wants to debug
487
- erroneous behavior of the decoder. If set to `true` the input image's red
488
- color-channel is read instead of calculating the gray-scale values of the
489
- source's RGB. This is useful in combination with the `ResultCollector` where
490
- the gray-scale representations of the wrongly identified images are saved.
491
-
492
- ### frequency
493
-
494
- This top-level property controls the scan-frequency of the video-stream. It's
495
- optional and defines the maximum number of scans per second. This renders
496
- useful for cases where the scan-session is long-running and resources such as
497
- CPU power are of concern.
498
-
499
- ### decoder
500
-
501
- QuaggaJS usually runs in a two-stage manner (`locate` is set to `true`) where,
502
- after the barcode is located, the decoding process starts. Decoding is the
503
- process of converting the bars into its true meaning. Most of the configuration
504
- options within the `decoder` are for debugging/visualization purposes only.
505
-
506
- ```javascript
507
- {
508
- readers: [
509
- 'code_128_reader'
510
- ],
511
- debug: {
512
- drawBoundingBox: false,
513
- showFrequency: false,
514
- drawScanline: false,
515
- showPattern: false
516
- }
517
- multiple: false
518
- }
519
- ```
520
-
521
- The most important property is `readers` which takes an array of types of
522
- barcodes which should be decoded during the session. Possible values are:
523
-
524
- - code_128_reader (default)
525
- - ean_reader
526
- - ean_8_reader
527
- - code_39_reader
528
- - code_39_vin_reader
529
- - codabar_reader
530
- - upc_reader
531
- - upc_e_reader
532
- - i2of5_reader
533
- - 2of5_reader
534
- - code_93_reader
535
- - code_32_reader
536
-
537
- Why are not all types activated by default? Simply because one should
538
- explicitly define the set of barcodes for their use-case. More decoders means
539
- more possible clashes, or false-positives. One should take care of the order
540
- the readers are given, since some might return a value even though it is not
541
- the correct type (EAN-13 vs. UPC-A).
542
-
543
- The `multiple` property tells the decoder if it should continue decoding after
544
- finding a valid barcode. If multiple is set to `true`, the results will be
545
- returned as an array of result objects. Each object in the array will have a
546
- `box`, and may have a `codeResult` depending on the success of decoding the
547
- individual box.
548
-
549
- The remaining properties `drawBoundingBox`, `showFrequency`, `drawScanline` and
550
- `showPattern` are mostly of interest during debugging and visualization.
551
-
552
- #### <a name="ean_extended">Enabling extended EAN</a>
553
-
554
- The default setting for `ean_reader` is not capable of reading extensions such
555
- as [EAN-2](https://en.wikipedia.org/wiki/EAN_2) or
556
- [EAN-5](https://en.wikipedia.org/wiki/EAN_5). In order to activate those
557
- supplements you have to provide them in the configuration as followed:
558
-
559
- ```javascript
560
- decoder: {
561
- readers: [{
562
- format: "ean_reader",
563
- config: {
564
- supplements: [
565
- 'ean_5_reader', 'ean_2_reader'
566
- ]
567
- }
568
- }]
569
- }
570
- ```
571
-
572
- Beware that the order of the `supplements` matters in such that the reader stops
573
- decoding when the first supplement was found. So if you are interested in EAN-2
574
- and EAN-5 extensions, use the order depicted above.
575
-
576
- It's important to mention that, if supplements are supplied, regular EAN-13
577
- codes cannot be read any more with the same reader. If you want to read EAN-13
578
- with and without extensions you have to add another `ean_reader` reader to the
579
- configuration.
580
-
581
- ### locator
582
-
583
- The `locator` config is only relevant if the `locate` flag is set to `true`.
584
- It controls the behavior of the localization-process and needs to be adjusted
585
- for each specific use-case. The default settings are simply a combination of
586
- values which worked best during development.
587
-
588
- Only two properties are relevant for the use in Quagga (`halfSample` and
589
- `patchSize`) whereas the rest is only needed for development and debugging.
590
-
591
-
592
- ```javascript
593
- {
594
- halfSample: true,
595
- patchSize: "medium", // x-small, small, medium, large, x-large
596
- debug: {
597
- showCanvas: false,
598
- showPatches: false,
599
- showFoundPatches: false,
600
- showSkeleton: false,
601
- showLabels: false,
602
- showPatchLabels: false,
603
- showRemainingPatchLabels: false,
604
- boxFromPatches: {
605
- showTransformed: false,
606
- showTransformedBox: false,
607
- showBB: false
608
- }
609
- }
610
- }
611
- ```
612
-
613
- The `halfSample` flag tells the locator-process whether it should operate on an
614
- image scaled down (half width/height, quarter pixel-count ) or not. Turning
615
- `halfSample` on reduces the processing-time significantly and also helps
616
- finding a barcode pattern due to implicit smoothing.
617
- It should be turned off in cases where the barcode is really small and the full
618
- resolution is needed to find the position. It's recommended to keep it turned
619
- on and use a higher resolution video-image if needed.
620
-
621
- The second property `patchSize` defines the density of the search-grid. The
622
- property accepts strings of the value `x-small`, `small`, `medium`, `large` and
623
- `x-large`. The `patchSize` is proportional to the size of the scanned barcodes.
624
- If you have really large barcodes which can be read close-up, then the use of
625
- `large` or `x-large` is recommended. In cases where the barcode is further away
626
- from the camera lens (lack of auto-focus, or small barcodes) then it's advised
627
- to set the size to `small` or even `x-small`. For the latter it's also
628
- recommended to crank up the resolution in order to find a barcode.
629
-
630
- ## Examples
631
-
632
- The following example takes an image `src` as input and prints the result on the
633
- console. The decoder is configured to detect _Code128_ barcodes and enables the
634
- locating-mechanism for more robust results.
635
-
636
- ```javascript
637
- Quagga.decodeSingle({
638
- decoder: {
639
- readers: ["code_128_reader"] // List of active readers
640
- },
641
- locate: true, // try to locate the barcode in the image
642
- src: '/test/fixtures/code_128/image-001.jpg' // or 'data:image/jpg;base64,' + data
643
- }, function(result){
644
- if(result.codeResult) {
645
- console.log("result", result.codeResult.code);
646
- } else {
647
- console.log("not detected");
648
- }
649
- });
650
- ```
651
-
652
- ### <a name="node-example">Using node</a>
653
-
654
- The following example illustrates the use of QuaggaJS within a node
655
- environment. It's almost identical to the browser version with the difference
656
- that node does not support web-workers out of the box. Therefore the config
657
- property `numOfWorkers` must be explicitly set to `0`.
658
-
659
- ```javascript
660
- var Quagga = require('quagga').default;
661
-
662
- Quagga.decodeSingle({
663
- src: "image-abc-123.jpg",
664
- numOfWorkers: 0, // Needs to be 0 when used within node
665
- inputStream: {
666
- size: 800 // restrict input-size to be 800px in width (long-side)
667
- },
668
- decoder: {
669
- readers: ["code_128_reader"] // List of active readers
670
- },
671
- }, function(result) {
672
- if(result.codeResult) {
673
- console.log("result", result.codeResult.code);
674
- } else {
675
- console.log("not detected");
676
- }
677
- });
678
- ```
679
-
680
- ## <a name="tipsandtricks">Tips & Tricks</a>
681
-
682
- A growing collection of tips & tricks to improve the various aspects of Quagga.
683
-
684
- ### Working with Cordova / PhoneGap?
685
-
686
- If you're having issues getting a mobile device to run Quagga using Cordova, you might try the code
687
- here: [Original Repo Issue #94 Comment][https://github.com/serratus/quaggaJS/issues/94#issuecomment-571478711]
688
-
689
- ```javascript
690
- let permissions = cordova.plugins.permissions; permissions.checkPermission(permissions.CAMERA,
691
- (res) => { if (!res.hasPermission) { permissions.requestPermission(permissions.CAMERA, open());
692
- ```
693
-
694
- Thanks, @chrisrodriguezmbww !
695
-
696
- ### Barcodes too small?
697
-
698
- Barcodes too far away from the camera, or a lens too close to the object
699
- result in poor recognition rates and Quagga might respond with a lot of
700
- false-positives.
701
-
702
- Starting in Chrome 59 you can now make use of `capabilities` and directly
703
- control the zoom of the camera. Head over to the
704
- [web-cam demo](https://serratus.github.io/quaggaJS/examples/live_w_locator.html)
705
- and check out the __Zoom__ feature.
706
-
707
- You can read more about those `capabilities` in
708
- [Let's light a torch and explore MediaStreamTrack's capabilities](https://www.oberhofer.co/mediastreamtrack-and-its-capabilities)
709
-
710
- ### Video too dark?
711
-
712
- Dark environments usually result in noisy images and therefore mess with the
713
- recognition logic.
714
-
715
- Since Chrome 59 you can turn on/off the __Torch__ of your device and vastly
716
- improve the quality of the images. Head over to the
717
- [web-cam demo](https://serratus.github.io/quaggaJS/examples/live_w_locator.html)
718
- and check out the __Torch__ feature.
719
-
720
- To find out more about this feature [read on](https://www.oberhofer.co/mediastreamtrack-and-its-capabilities).
721
-
722
- ### Handling false positives
723
-
724
- Most readers provide an error object that describes the confidence of the reader in it's accuracy. There are strategies you can implement in your application to improve what your application accepts as acceptable input from the barcode scanner, [in this thread](https://github.com/serratus/quaggaJS/issues/237).
725
-
726
- If you choose to explore check-digit validation, you might find [barcode-validator](https://github.com/ericblade/barcode-validator) a useful library.
727
-
728
- ## Tests
729
-
730
- Tests are performed with [Cypress][cypressUrl] for browser testing, and [Mocha][mochaUrl], [Chai][chaiUrl], and [SinonJS][sinonUrl] for Node.JS testing. (note that Cypress also uses Mocha, Chai, and Sinon, so tests that are not browser specific can be run virtually identically in node without duplication of code)
731
-
732
- Coverage reports are generated in the coverage/ folder.
733
-
734
- ```console
735
- > npm install
736
- > npm run test
737
- ```
738
-
739
- Using Docker:
740
-
741
- ```console
742
- > docker build --tag quagga2/build .
743
- > docker run -v $(pwd):/quagga2 npm install
744
- > docker run -v $(pwd):/quagga2 npm run test
745
- ```
746
-
747
- or using docker-compose:
748
-
749
- ```console
750
- > docker-compose run nodejs npm install
751
- > docker-compose run nodejs npm run test
752
- ```
753
-
754
- We prefer that Unit tests be located near the unit being tested -- the src/quagga/transform module, for example, has it's test suite located at src/quagga/test/transform.spec.ts. Likewise, src/locator/barcode_locator test is located at src/locator/test/barcode_locator.spec.ts .
755
-
756
- If you have browser or node specific tests, that must be written differently per platform, or do not apply to one platform, then you may add them to src/{filelocation}/test/browser or .../test/node. See also src/analytics/test/browser/result_collector.spec.ts, which contains browser specific code.
757
-
758
- If you add a new test file, you should also make sure to import it in either cypress/integration/browser.spec.ts, for browser-specific tests, or cypress/integration/universal.spec.ts, for tests that can be run both in node and in browser. Node.JS testing is performed using the power of file globbing, and will pick up your tests, so long as they conform to the existing test file directory and name patterns.
759
-
760
- ## Image Debugging
761
-
762
- In case you want to take a deeper dive into the inner workings of Quagga, get to
763
- know the _debugging_ capabilities of the current implementation. The various
764
- flags exposed through the `config` object give you the ability to visualize
765
- almost every step in the processing. Because of the introduction of the
766
- web-workers, and their restriction not to have access to the DOM, the
767
- configuration must be explicitly set to `config.numOfWorkers = 0` in order to
768
- work.
769
-
770
- ## <a name="resultcollector">ResultCollector</a>
771
-
772
- Quagga is not perfect by any means and may produce false positives from time
773
- to time. In order to find out which images produced those false positives,
774
- the built-in ``ResultCollector`` will support you and me helping squashing
775
- bugs in the implementation.
776
-
777
- ### Creating a ``ResultCollector``
778
-
779
- You can easily create a new ``ResultCollector`` by calling its ``create``
780
- method with a configuration.
781
-
782
- ```javascript
783
- var resultCollector = Quagga.ResultCollector.create({
784
- capture: true, // keep track of the image producing this result
785
- capacity: 20, // maximum number of results to store
786
- blacklist: [ // list containing codes which should not be recorded
787
- {code: "3574660239843", format: "ean_13"}],
788
- filter: function(codeResult) {
789
- // only store results which match this constraint
790
- // returns true/false
791
- // e.g.: return codeResult.format === "ean_13";
792
- return true;
793
- }
794
- });
795
- ```
796
-
797
- ### Using a ``ResultCollector``
798
-
799
- After creating a ``ResultCollector`` you have to attach it to Quagga by
800
- calling ``Quagga.registerResultCollector(resultCollector)``.
801
-
802
- ### Reading results
803
-
804
- After a test/recording session, you can now print the collected results which
805
- do not fit into a certain schema. Calling ``getResults`` on the
806
- ``resultCollector`` returns an ``Array`` containing objects with:
807
-
808
- ```javascript
809
- {
810
- codeResult: {}, // same as in onDetected event
811
- frame: "data:image/png;base64,iVBOR..." // dataURL of the gray-scaled image
812
- }
813
- ```
814
-
815
- The ``frame`` property is an internal representation of the image and
816
- therefore only available in gray-scale. The dataURL representation allows
817
- easy saving/rendering of the image.
818
-
819
- ### Comparing results
820
-
821
- Now, having the frames available on disk, you can load each single image by
822
- calling ``decodeSingle`` with the same configuration as used during recording
823
- . In order to reproduce the exact same result, you have to make sure to turn
824
- on the ``singleChannel`` flag in the configuration when using ``decodeSingle``.
825
-
826
- [zxing_github]: https://github.com/zxing/zxing
827
- [teaser_left]: https://raw.githubusercontent.com/serratus/quaggaJS/master/doc/img/mobile-located.png
828
- [teaser_right]: https://raw.githubusercontent.com/serratus/quaggaJS/master/doc/img/mobile-detected.png
829
- [caniuse_getusermedia]: http://caniuse.com/#feat=stream
830
- [cypressUrl]: https://www.cypress.io/
831
- [sinonUrl]: http://sinonjs.org/
832
- [chaiUrl]: http://chaijs.com/
833
- [mochaUrl]: https://github.com/mochajs/mocha
834
- [code39_wiki]: http://en.wikipedia.org/wiki/Code_39
835
- [codabar_wiki]: http://en.wikipedia.org/wiki/Codabar
836
- [upc_wiki]: http://en.wikipedia.org/wiki/Universal_Product_Code
837
- [ean_8_wiki]: http://en.wikipedia.org/wiki/EAN-8
838
- [oberhofer_co_how]: http://www.oberhofer.co/how-barcode-localization-works-in-quaggajs/
839
- [github_examples]: https://serratus.github.io/quaggaJS/examples
840
- [i2of5_wiki]: https://en.wikipedia.org/wiki/Interleaved_2_of_5
841
- [enumerateDevices]: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices
842
- [reactExample]: https://github.com/ericblade/quagga2-react-example
1
+ quagga2
2
+ =======
3
+
4
+ [![Rolling Versions](https://img.shields.io/badge/Rolling%20Versions-Enabled-brightgreen)](https://rollingversions.com/ericblade/quagga2)
5
+
6
+ [![Join the chat at https://gitter.im/quaggaJS/Lobby](https://badges.gitter.im/quaggaJS/Lobby.svg)](https://gitter.im/quaggaJS/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
7
+
8
+ [![Rate on Openbase](https://badges.openbase.io/js/rating/@ericblade/quagga2.svg)](https://openbase.io/js/@ericblade/quagga2?utm_source=embedded&utm_medium=badge&utm_campaign=rate-badge)
9
+
10
+ This is a fork of the original QuaggaJS library, that will be maintained until such time as the
11
+ original author and maintainer returns, or it has been completely replaced by built-in browser and
12
+ node functionality.
13
+
14
+ - [Changelog](CHANGELOG.md)
15
+ - [Browser Support](#browser-support)
16
+ - [Installing](#installing)
17
+ - [Getting Started](#gettingstarted)
18
+ - [Using with React](#usingwithreact)
19
+ - [Using External Readers](#usingexternalreaders)
20
+ - [API](#api)
21
+ - [Configuration](#configobject)
22
+ - [Tips & Tricks](#tipsandtricks)
23
+
24
+ ## Using React / Redux?
25
+
26
+ Please see also <https://github.com/ericblade/quagga2-react-example/> and <https://github.com/ericblade/quagga2-redux-middleware/>
27
+
28
+ ## Using Angular?
29
+
30
+ Please see <https://github.com/julienboulay/ngx-barcode-scanner> or <https://github.com/classycodeoss/mobile-scanning-demo>
31
+
32
+ ## Using ThingWorx?
33
+
34
+ Please see <https://github.com/ptc-iot-sharing/ThingworxBarcodeScannerWidget>
35
+
36
+ ## What is QuaggaJS?
37
+
38
+ QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real-
39
+ time localization and decoding of various types of barcodes such as __EAN__,
40
+ __CODE 128__, __CODE 39__, __EAN 8__, __UPC-A__, __UPC-C__, __I2of5__,
41
+ __2of5__, __CODE 93__, __CODE 32__ and __CODABAR__. The library is also capable of using
42
+ `getUserMedia` to get direct access to the user's camera stream. Although the
43
+ code relies on heavy image-processing even recent smartphones are capable of
44
+ locating and decoding barcodes in real-time.
45
+
46
+ Try some [examples](https://serratus.github.io/quaggaJS/examples) and check out
47
+ the blog post ([How barcode-localization works in QuaggaJS][oberhofer_co_how])
48
+ if you want to dive deeper into this topic.
49
+
50
+ ![teaser][teaser_left]![teaser][teaser_right]
51
+
52
+ ## Yet another barcode library?
53
+
54
+ This is not yet another port of the great [zxing][zxing_github] library, but
55
+ more of an extension to it. This implementation features a barcode locator which
56
+ is capable of finding a barcode-like pattern in an image resulting in an
57
+ estimated bounding box including the rotation. Simply speaking, this reader is
58
+ invariant to scale and rotation, whereas other libraries require the barcode to
59
+ be aligned with the viewport.
60
+
61
+ ## <a name="browser-support">Browser Support</a>
62
+
63
+ Quagga makes use of many modern Web-APIs which are not implemented by all
64
+ browsers yet. There are two modes in which Quagga operates:
65
+
66
+ 1. analyzing static images and
67
+ 2. using a camera to decode the images from a live-stream.
68
+
69
+ The latter requires the presence of the MediaDevices API. You can track the compatibility
70
+ of the used Web-APIs for each mode:
71
+
72
+ - [Static Images](http://caniuse.com/#feat=webworkers,canvas,typedarrays,bloburls,blobbuilder)
73
+ - [Live Stream](http://caniuse.com/#feat=webworkers,canvas,typedarrays,bloburls,blobbuilder,stream)
74
+
75
+ ### Static Images
76
+
77
+ The following APIs need to be implemented in your browser:
78
+
79
+ - [webworkers](http://caniuse.com/#feat=webworkers)
80
+ - [canvas](http://caniuse.com/#feat=canvas)
81
+ - [typedarrays](http://caniuse.com/#feat=typedarrays)
82
+ - [bloburls](http://caniuse.com/#feat=bloburls)
83
+ - [blobbuilder](http://caniuse.com/#feat=blobbuilder)
84
+
85
+ ### Live Stream
86
+
87
+ In addition to the APIs mentioned above:
88
+
89
+ - [MediaDevices](http://caniuse.com/#feat=stream)
90
+
91
+ __Important:__ Accessing `getUserMedia` requires a secure origin in most
92
+ browsers, meaning that `http://` can only be used on `localhost`. All other
93
+ hostnames need to be served via `https://`. You can find more information in the
94
+ [Chrome M47 WebRTC Release Notes](https://groups.google.com/forum/#!topic/discuss-webrtc/sq5CVmY69sc).
95
+
96
+ ### Feature-detection of getUserMedia
97
+
98
+ Every browser seems to differently implement the `mediaDevices.getUserMedia`
99
+ API. Therefore it's highly recommended to include
100
+ [webrtc-adapter](https://github.com/webrtc/adapter) in your project.
101
+
102
+ Here's how you can test your browser's capabilities:
103
+
104
+ ```javascript
105
+ if (navigator.mediaDevices && typeof navigator.mediaDevices.getUserMedia === 'function') {
106
+ // safely access `navigator.mediaDevices.getUserMedia`
107
+ }
108
+ ```
109
+
110
+ The above condition evaluates to:
111
+
112
+ | Browser | result |
113
+ | ------------- |:-------:|
114
+ | Edge | `true` |
115
+ | Chrome | `true` |
116
+ | Firefox | `true` |
117
+ | IE 11 | `false` |
118
+ | Safari iOS | `true` |
119
+
120
+ ## <a name="installing">Installing</a>
121
+
122
+ Quagga2 can be installed using __npm__, or by including it with the __script__ tag.
123
+
124
+ ### NPM
125
+
126
+ ```console
127
+ > npm install --save @ericblade/quagga2
128
+ ```
129
+
130
+ And then import it as dependency in your project:
131
+
132
+ ```javascript
133
+ import Quagga from '@ericblade/quagga2'; // ES6
134
+ const Quagga = require('@ericblade/quagga2').default; // Common JS (important: default)
135
+ ```
136
+
137
+ Currently, the full functionality is only available through the browser. When
138
+ using QuaggaJS within __node__, only file-based decoding is available. See the
139
+ example for [node_examples](#node-example).
140
+
141
+ ### Using with script tag
142
+
143
+ You can simply include `quagga.js` in your project and you are ready
144
+ to go. The script exposes the library on the global namespace under `Quagga`.
145
+
146
+ ```html
147
+ <script src="quagga.js"></script>
148
+ ```
149
+
150
+ You can get the `quagga.js` file in the following ways:
151
+
152
+ By [installing the npm module](https://github.com/ericblade/quagga2#npm) and copying the `quagga.js` file from the `dist` folder.
153
+
154
+ <p align="center">(OR)</p>
155
+
156
+ You can also build the library yourself and copy `quagga.js` file from the `dist` folder(refer to the [building](https://github.com/ericblade/quagga2#building) section for more details)
157
+
158
+ <p align="center">(OR)</p>
159
+
160
+ You can include the following script tags with CDN links:
161
+
162
+ a) `quagga.js`
163
+
164
+ ```html
165
+ <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>
166
+ ```
167
+
168
+ b) `quagga.min.js` (minified version)
169
+
170
+ ```html
171
+ <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.min.js"></script>
172
+ ```
173
+
174
+ *Note: You can include a specific version of the library by including the version as shown below.*
175
+
176
+ ```html
177
+ <!-- Link for Version 1.2.6 -->
178
+ <script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2@1.2.6/dist/quagga.js"></script>
179
+ ```
180
+
181
+ ## <a name="gettingstarted">Getting Started</a>
182
+
183
+ For starters, have a look at the [examples][github_examples] to get an idea
184
+ where to go from here.
185
+
186
+ ## <a name="usingwithreact">Using with React</a>
187
+
188
+ There is a separate [example][reactExample] for using quagga2 with ReactJS
189
+
190
+ ## <a name="usingwithexternalreaders">Using with External Readers</a>
191
+
192
+ New in Quagga2 is the ability to specify external reader modules. Please see [quagga2-reader-qr](https://github.com/ericblade/quagga2-reader-qr). This repository includes a sample external reader that can
193
+ read complete images, and decode QR codes. A test script is included to demonstrate how to use an
194
+ external reader in your project.
195
+
196
+ Quagga2 exports the BarcodeReader prototype, which should also allow you to create new barcode
197
+ reader implementations using the base BarcodeReader implementation inside Quagga2. The QR reader
198
+ does not make use of this functionality, as QR is not picked up as a barcode in BarcodeReader.
199
+
200
+ ## <a name="Building">Building</a>
201
+
202
+ You can build the library yourself by simply cloning the repo and typing:
203
+
204
+ ```console
205
+ > npm install
206
+ > npm run build
207
+ ```
208
+
209
+ or using Docker:
210
+
211
+ ```console
212
+ > docker build --tag quagg2/build .
213
+ > docker run -v $(pwd):/quagga2 quagga2/build npm install
214
+ > docker run -v $(pwd):/quagga2 quagga2/build npm run build
215
+ ```
216
+
217
+ it's also possible to use docker-compose:
218
+
219
+ ```console
220
+ > docker-compose run nodejs npm install
221
+ > docker-compose run nodejs npm run build
222
+ ```
223
+
224
+ *Note: when using Docker or docker-compose the build artifacts will end up in `dist/` as usual thanks to the bind-mount.*
225
+
226
+ This npm script builds a non optimized version `quagga.js` and a minified
227
+ version `quagga.min.js` and places both files in the `dist` folder.
228
+ Additionally, a `quagga.map` source-map is placed alongside these files. This
229
+ file is only valid for the non-uglified version `quagga.js` because the
230
+ minified version is altered after compression and does not align with the map
231
+ file any more.
232
+
233
+ ## <a name="WorkingWithDev">Working with a development version from another project</a>
234
+
235
+ If you are working on a project that includes quagga, but you need to use a development version of
236
+ quagga, then you can run from the quagga directory:
237
+
238
+ ```
239
+ npm install && npm run build && npm link
240
+ ```
241
+
242
+ then from the other project directory that needs this quagga, do
243
+
244
+ ```
245
+ npm link @ericblade/quagga2
246
+ ```
247
+
248
+ When linking is successful, all future runs of 'npm run build' will update the version that is
249
+ linked in the project. When combined with an application using webpack-dev-server or some other
250
+ hot-reload system, you can do very rapid iteration this way.
251
+
252
+ ### Node
253
+
254
+ The code in the `dist` folder is only targeted to the browser and won't work in
255
+ node due to the dependency on the DOM. For the use in node, the `build` command
256
+ also creates a `quagga.js` file in the `lib` folder.
257
+
258
+ ## <a name="api">API</a>
259
+
260
+ You can check out the [examples][github_examples] to get an idea of how to
261
+ use QuaggaJS. Basically the library exposes the following API:
262
+
263
+ ### <a name="quaggainit">Quagga.init(config, callback)</a>
264
+
265
+ This method initializes the library for a given configuration `config` (see
266
+ below) and invokes the `callback(err)` when Quagga has finished its
267
+ bootstrapping phase. The initialization process also requests for camera
268
+ access if real-time detection is configured. In case of an error, the `err`
269
+ parameter is set and contains information about the cause. A potential cause
270
+ may be the `inputStream.type` is set to `LiveStream`, but the browser does
271
+ not support this API, or simply if the user denies the permission to use the
272
+ camera.
273
+
274
+ If you do not specify a target, QuaggaJS would look for an element that matches
275
+ the CSS selector `#interactive.viewport` (for backwards compatibility).
276
+ `target` can be a string (CSS selector matching one of your DOM node) or a DOM
277
+ node.
278
+
279
+ ```javascript
280
+ Quagga.init({
281
+ inputStream : {
282
+ name : "Live",
283
+ type : "LiveStream",
284
+ target: document.querySelector('#yourElement') // Or '#yourElement' (optional)
285
+ },
286
+ decoder : {
287
+ readers : ["code_128_reader"]
288
+ }
289
+ }, function(err) {
290
+ if (err) {
291
+ console.log(err);
292
+ return
293
+ }
294
+ console.log("Initialization finished. Ready to start");
295
+ Quagga.start();
296
+ });
297
+ ```
298
+
299
+ ### Quagga.start()
300
+
301
+ When the library is initialized, the `start()` method starts the video-stream
302
+ and begins locating and decoding the images.
303
+
304
+ ### Quagga.stop()
305
+
306
+ If the decoder is currently running, after calling `stop()` the decoder does not
307
+ process any more images. Additionally, if a camera-stream was requested upon
308
+ initialization, this operation also disconnects the camera.
309
+
310
+ ### Quagga.onProcessed(callback)
311
+
312
+ This method registers a `callback(data)` function that is called for each frame
313
+ after the processing is done. The `data` object contains detailed information
314
+ about the success/failure of the operation. The output varies, depending whether
315
+ the detection and/or decoding were successful or not.
316
+
317
+ ### Quagga.onDetected(callback)
318
+
319
+ Registers a `callback(data)` function which is triggered whenever a barcode-
320
+ pattern has been located and decoded successfully. The passed `data` object
321
+ contains information about the decoding process including the detected code
322
+ which can be obtained by calling `data.codeResult.code`.
323
+
324
+ ### Quagga.decodeSingle(config, callback)
325
+
326
+ In contrast to the calls described above, this method does not rely on
327
+ `getUserMedia` and operates on a single image instead. The provided callback
328
+ is the same as in `onDetected` and contains the result `data` object.
329
+
330
+ ### Quagga.offProcessed(handler)
331
+
332
+ In case the `onProcessed` event is no longer relevant, `offProcessed` removes
333
+ the given `handler` from the event-queue. When no handler is passed, all handlers are removed.
334
+
335
+ ### Quagga.offDetected(handler)
336
+
337
+ In case the `onDetected` event is no longer relevant, `offDetected` removes
338
+ the given `handler` from the event-queue. When no handler is passed, all handlers are removed.
339
+
340
+ ## <a name="resultobject">The result object</a>
341
+
342
+ The callbacks passed into `onProcessed`, `onDetected` and `decodeSingle`
343
+ receive a `data` object upon execution. The `data` object contains the following
344
+ information. Depending on the success, some fields may be `undefined` or just
345
+ empty.
346
+
347
+ ```javascript
348
+ {
349
+ "codeResult": {
350
+ "code": "FANAVF1461710", // the decoded code as a string
351
+ "format": "code_128", // or code_39, codabar, ean_13, ean_8, upc_a, upc_e
352
+ "start": 355,
353
+ "end": 26,
354
+ "codeset": 100,
355
+ "startInfo": {
356
+ "error": 1.0000000000000002,
357
+ "code": 104,
358
+ "start": 21,
359
+ "end": 41
360
+ },
361
+ "decodedCodes": [{
362
+ "code": 104,
363
+ "start": 21,
364
+ "end": 41
365
+ },
366
+ // stripped for brevity
367
+ {
368
+ "error": 0.8888888888888893,
369
+ "code": 106,
370
+ "start": 328,
371
+ "end": 350
372
+ }],
373
+ "endInfo": {
374
+ "error": 0.8888888888888893,
375
+ "code": 106,
376
+ "start": 328,
377
+ "end": 350
378
+ },
379
+ "direction": -1
380
+ },
381
+ "line": [{
382
+ "x": 25.97278706156836,
383
+ "y": 360.5616435369468
384
+ }, {
385
+ "x": 401.9220519377024,
386
+ "y": 70.87524989906444
387
+ }],
388
+ "angle": -0.6565217179979483,
389
+ "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],
390
+ "box": [
391
+ [77.4074243622672, 410.9288668804402],
392
+ [0.050203235235130705, 310.53619724086366],
393
+ [360.15706727788256, 33.05711026051813],
394
+ [437.5142884049146, 133.44977990009465]
395
+ ],
396
+ "boxes": [
397
+ [
398
+ [77.4074243622672, 410.9288668804402],
399
+ [0.050203235235130705, 310.53619724086366],
400
+ [360.15706727788256, 33.05711026051813],
401
+ [437.5142884049146, 133.44977990009465]
402
+ ],
403
+ [
404
+ [248.90769330706507, 415.2041489551161],
405
+ [198.9532321622869, 352.62160512937635],
406
+ [339.546160777576, 240.3979259789976],
407
+ [389.5006219223542, 302.98046980473737]
408
+ ]
409
+ ]
410
+ }
411
+ ```
412
+
413
+ ## <a name="configobject">Configuration</a>
414
+
415
+ The configuration that ships with QuaggaJS covers the default use-cases and can
416
+ be fine-tuned for specific requirements.
417
+
418
+ The configuration is managed by the `config` object defining the following
419
+ high-level properties:
420
+
421
+ ```javascript
422
+ {
423
+ numOfWorkers: 4,
424
+ locate: true,
425
+ inputStream: {...},
426
+ frequency: 10,
427
+ decoder:{...},
428
+ locator: {...},
429
+ debug: false,
430
+ }
431
+ ```
432
+
433
+ ### numOfWorkers
434
+
435
+ NOTE: As of quagga2 v0.0.13, numOfWorkers has been *disabled*. The library needs a major restructuring
436
+ to properly handle Worker threads, and that restructuring is on-going at the moment, to solve other
437
+ problems as well. It will be re-enabled in the future. As a result, the numOfWorkers setting is ALWAYS 0.
438
+
439
+ ~~QuaggaJS supports web-workers out of the box and runs with `4` workers in its
440
+ default configuration. The number should align with the number of cores
441
+ available in your targeted devices.~~
442
+
443
+ ~~In case you don't know the number upfront, or if the variety of devices is
444
+ too big, you can either use `navigator.hardwareConcurrency` (see
445
+ [here](https://wiki.whatwg.org/wiki/Navigator_HW_Concurrency)) where available
446
+ or make use of [core-estimator](https://github.com/oftn/core-estimator).~~
447
+
448
+ ### locate
449
+
450
+ One of the main features of QuaggaJS is its ability to locate a barcode in a
451
+ given image. The `locate` property controls whether this feature is turned on
452
+ (default) or off.
453
+
454
+ Why would someone turn this feature off? Localizing a barcode is a
455
+ computationally expensive operation and might not work properly on some
456
+ devices. Another reason would be the lack of auto-focus producing blurry
457
+ images which makes the localization feature very unstable.
458
+
459
+ However, even if none of the above apply, there is one more case where it might
460
+ be useful to disable `locate`: If the orientation, and/or the approximate
461
+ position of the barcode is known, or if you want to guide the user through a
462
+ rectangular outline. This can increase performance and robustness at the same
463
+ time.
464
+
465
+ ### inputStream
466
+
467
+ The `inputStream` property defines the sources of images/videos within QuaggaJS.
468
+
469
+ ```javascript
470
+ {
471
+ name: "Live",
472
+ type: "LiveStream",
473
+ constraints: {
474
+ width: 640,
475
+ height: 480,
476
+ facingMode: "environment",
477
+ deviceId: "7832475934759384534"
478
+ },
479
+ area: { // defines rectangle of the detection/localization area
480
+ top: "0%", // top offset
481
+ right: "0%", // right offset
482
+ left: "0%", // left offset
483
+ bottom: "0%" // bottom offset
484
+ },
485
+ singleChannel: false // true: only the red color-channel is read
486
+ }
487
+ ```
488
+
489
+ First, the `type` property can be set to three different values:
490
+ `ImageStream`, `VideoStream`, or `LiveStream` (default) and should be selected
491
+ depending on the use-case. Most probably, the default value is sufficient.
492
+
493
+ Second, the `constraint` key defines the physical dimensions of the input image
494
+ and additional properties, such as `facingMode` which sets the source of the
495
+ user's camera in case of multiple attached devices. Additionally, if required,
496
+ the `deviceId` can be set if the selection of the camera is given to the user.
497
+ This can be easily achieved via
498
+ [MediaDevices.enumerateDevices()][enumerateDevices]
499
+
500
+ Thirdly, the `area` prop restricts the decoding area of the image. The values
501
+ are given in percentage, similar to the CSS style property when using
502
+ `position: absolute`. This `area` is also useful in cases the `locate` property
503
+ is set to `false`, defining the rectangle for the user.
504
+
505
+ The last key `singleChannel` is only relevant in cases someone wants to debug
506
+ erroneous behavior of the decoder. If set to `true` the input image's red
507
+ color-channel is read instead of calculating the gray-scale values of the
508
+ source's RGB. This is useful in combination with the `ResultCollector` where
509
+ the gray-scale representations of the wrongly identified images are saved.
510
+
511
+ ### frequency
512
+
513
+ This top-level property controls the scan-frequency of the video-stream. It's
514
+ optional and defines the maximum number of scans per second. This renders
515
+ useful for cases where the scan-session is long-running and resources such as
516
+ CPU power are of concern.
517
+
518
+ ### decoder
519
+
520
+ QuaggaJS usually runs in a two-stage manner (`locate` is set to `true`) where,
521
+ after the barcode is located, the decoding process starts. Decoding is the
522
+ process of converting the bars into its true meaning. Most of the configuration
523
+ options within the `decoder` are for debugging/visualization purposes only.
524
+
525
+ ```javascript
526
+ {
527
+ readers: [
528
+ 'code_128_reader'
529
+ ],
530
+ debug: {
531
+ drawBoundingBox: false,
532
+ showFrequency: false,
533
+ drawScanline: false,
534
+ showPattern: false
535
+ }
536
+ multiple: false
537
+ }
538
+ ```
539
+
540
+ The most important property is `readers` which takes an array of types of
541
+ barcodes which should be decoded during the session. Possible values are:
542
+
543
+ - code_128_reader (default)
544
+ - ean_reader
545
+ - ean_8_reader
546
+ - code_39_reader
547
+ - code_39_vin_reader
548
+ - codabar_reader
549
+ - upc_reader
550
+ - upc_e_reader
551
+ - i2of5_reader
552
+ - 2of5_reader
553
+ - code_93_reader
554
+ - code_32_reader
555
+
556
+ Why are not all types activated by default? Simply because one should
557
+ explicitly define the set of barcodes for their use-case. More decoders means
558
+ more possible clashes, or false-positives. One should take care of the order
559
+ the readers are given, since some might return a value even though it is not
560
+ the correct type (EAN-13 vs. UPC-A).
561
+
562
+ The `multiple` property tells the decoder if it should continue decoding after
563
+ finding a valid barcode. If multiple is set to `true`, the results will be
564
+ returned as an array of result objects. Each object in the array will have a
565
+ `box`, and may have a `codeResult` depending on the success of decoding the
566
+ individual box.
567
+
568
+ The remaining properties `drawBoundingBox`, `showFrequency`, `drawScanline` and
569
+ `showPattern` are mostly of interest during debugging and visualization.
570
+
571
+ #### <a name="ean_extended">Enabling extended EAN</a>
572
+
573
+ The default setting for `ean_reader` is not capable of reading extensions such
574
+ as [EAN-2](https://en.wikipedia.org/wiki/EAN_2) or
575
+ [EAN-5](https://en.wikipedia.org/wiki/EAN_5). In order to activate those
576
+ supplements you have to provide them in the configuration as followed:
577
+
578
+ ```javascript
579
+ decoder: {
580
+ readers: [{
581
+ format: "ean_reader",
582
+ config: {
583
+ supplements: [
584
+ 'ean_5_reader', 'ean_2_reader'
585
+ ]
586
+ }
587
+ }]
588
+ }
589
+ ```
590
+
591
+ Beware that the order of the `supplements` matters in such that the reader stops
592
+ decoding when the first supplement was found. So if you are interested in EAN-2
593
+ and EAN-5 extensions, use the order depicted above.
594
+
595
+ It's important to mention that, if supplements are supplied, regular EAN-13
596
+ codes cannot be read any more with the same reader. If you want to read EAN-13
597
+ with and without extensions you have to add another `ean_reader` reader to the
598
+ configuration.
599
+
600
+ ### locator
601
+
602
+ The `locator` config is only relevant if the `locate` flag is set to `true`.
603
+ It controls the behavior of the localization-process and needs to be adjusted
604
+ for each specific use-case. The default settings are simply a combination of
605
+ values which worked best during development.
606
+
607
+ Only two properties are relevant for the use in Quagga (`halfSample` and
608
+ `patchSize`) whereas the rest is only needed for development and debugging.
609
+
610
+ ```javascript
611
+ {
612
+ halfSample: true,
613
+ patchSize: "medium", // x-small, small, medium, large, x-large
614
+ debug: {
615
+ showCanvas: false,
616
+ showPatches: false,
617
+ showFoundPatches: false,
618
+ showSkeleton: false,
619
+ showLabels: false,
620
+ showPatchLabels: false,
621
+ showRemainingPatchLabels: false,
622
+ boxFromPatches: {
623
+ showTransformed: false,
624
+ showTransformedBox: false,
625
+ showBB: false
626
+ }
627
+ }
628
+ }
629
+ ```
630
+
631
+ The `halfSample` flag tells the locator-process whether it should operate on an
632
+ image scaled down (half width/height, quarter pixel-count ) or not. Turning
633
+ `halfSample` on reduces the processing-time significantly and also helps
634
+ finding a barcode pattern due to implicit smoothing.
635
+ It should be turned off in cases where the barcode is really small and the full
636
+ resolution is needed to find the position. It's recommended to keep it turned
637
+ on and use a higher resolution video-image if needed.
638
+
639
+ The second property `patchSize` defines the density of the search-grid. The
640
+ property accepts strings of the value `x-small`, `small`, `medium`, `large` and
641
+ `x-large`. The `patchSize` is proportional to the size of the scanned barcodes.
642
+ If you have really large barcodes which can be read close-up, then the use of
643
+ `large` or `x-large` is recommended. In cases where the barcode is further away
644
+ from the camera lens (lack of auto-focus, or small barcodes) then it's advised
645
+ to set the size to `small` or even `x-small`. For the latter it's also
646
+ recommended to crank up the resolution in order to find a barcode.
647
+
648
+ ## Examples
649
+
650
+ The following example takes an image `src` as input and prints the result on the
651
+ console. The decoder is configured to detect *Code128* barcodes and enables the
652
+ locating-mechanism for more robust results.
653
+
654
+ ```javascript
655
+ Quagga.decodeSingle({
656
+ decoder: {
657
+ readers: ["code_128_reader"] // List of active readers
658
+ },
659
+ locate: true, // try to locate the barcode in the image
660
+ src: '/test/fixtures/code_128/image-001.jpg' // or 'data:image/jpg;base64,' + data
661
+ }, function(result){
662
+ if(result.codeResult) {
663
+ console.log("result", result.codeResult.code);
664
+ } else {
665
+ console.log("not detected");
666
+ }
667
+ });
668
+ ```
669
+
670
+ ### <a name="node-example">Using node</a>
671
+
672
+ The following example illustrates the use of QuaggaJS within a node
673
+ environment. It's almost identical to the browser version with the difference
674
+ that node does not support web-workers out of the box. Therefore the config
675
+ property `numOfWorkers` must be explicitly set to `0`.
676
+
677
+ ```javascript
678
+ var Quagga = require('quagga').default;
679
+
680
+ Quagga.decodeSingle({
681
+ src: "image-abc-123.jpg",
682
+ numOfWorkers: 0, // Needs to be 0 when used within node
683
+ inputStream: {
684
+ size: 800 // restrict input-size to be 800px in width (long-side)
685
+ },
686
+ decoder: {
687
+ readers: ["code_128_reader"] // List of active readers
688
+ },
689
+ }, function(result) {
690
+ if(result.codeResult) {
691
+ console.log("result", result.codeResult.code);
692
+ } else {
693
+ console.log("not detected");
694
+ }
695
+ });
696
+ ```
697
+
698
+ ## <a name="tipsandtricks">Tips & Tricks</a>
699
+
700
+ A growing collection of tips & tricks to improve the various aspects of Quagga.
701
+
702
+ ### Working with Cordova / PhoneGap?
703
+
704
+ If you're having issues getting a mobile device to run Quagga using Cordova, you might try the code
705
+ here: [Original Repo Issue #94 Comment][https://github.com/serratus/quaggaJS/issues/94#issuecomment-571478711]
706
+
707
+ ```javascript
708
+ let permissions = cordova.plugins.permissions; permissions.checkPermission(permissions.CAMERA,
709
+ (res) => { if (!res.hasPermission) { permissions.requestPermission(permissions.CAMERA, open());
710
+ ```
711
+
712
+ Thanks, @chrisrodriguezmbww !
713
+
714
+ ### Barcodes too small?
715
+
716
+ Barcodes too far away from the camera, or a lens too close to the object
717
+ result in poor recognition rates and Quagga might respond with a lot of
718
+ false-positives.
719
+
720
+ Starting in Chrome 59 you can now make use of `capabilities` and directly
721
+ control the zoom of the camera. Head over to the
722
+ [web-cam demo](https://serratus.github.io/quaggaJS/examples/live_w_locator.html)
723
+ and check out the __Zoom__ feature.
724
+
725
+ You can read more about those `capabilities` in
726
+ [Let's light a torch and explore MediaStreamTrack's capabilities](https://www.oberhofer.co/mediastreamtrack-and-its-capabilities)
727
+
728
+ ### Video too dark?
729
+
730
+ Dark environments usually result in noisy images and therefore mess with the
731
+ recognition logic.
732
+
733
+ Since Chrome 59 you can turn on/off the __Torch__ of your device and vastly
734
+ improve the quality of the images. Head over to the
735
+ [web-cam demo](https://serratus.github.io/quaggaJS/examples/live_w_locator.html)
736
+ and check out the __Torch__ feature.
737
+
738
+ To find out more about this feature [read on](https://www.oberhofer.co/mediastreamtrack-and-its-capabilities).
739
+
740
+ ### Handling false positives
741
+
742
+ Most readers provide an error object that describes the confidence of the reader in it's accuracy. There are strategies you can implement in your application to improve what your application accepts as acceptable input from the barcode scanner, [in this thread](https://github.com/serratus/quaggaJS/issues/237).
743
+
744
+ If you choose to explore check-digit validation, you might find [barcode-validator](https://github.com/ericblade/barcode-validator) a useful library.
745
+
746
+ ## Tests
747
+
748
+ Tests are performed with [Cypress][cypressUrl] for browser testing, and [Mocha][mochaUrl], [Chai][chaiUrl], and [SinonJS][sinonUrl] for Node.JS testing. (note that Cypress also uses Mocha, Chai, and Sinon, so tests that are not browser specific can be run virtually identically in node without duplication of code)
749
+
750
+ Coverage reports are generated in the coverage/ folder.
751
+
752
+ ```console
753
+ > npm install
754
+ > npm run test
755
+ ```
756
+
757
+ Using Docker:
758
+
759
+ ```console
760
+ > docker build --tag quagga2/build .
761
+ > docker run -v $(pwd):/quagga2 npm install
762
+ > docker run -v $(pwd):/quagga2 npm run test
763
+ ```
764
+
765
+ or using docker-compose:
766
+
767
+ ```console
768
+ > docker-compose run nodejs npm install
769
+ > docker-compose run nodejs npm run test
770
+ ```
771
+
772
+ We prefer that Unit tests be located near the unit being tested -- the src/quagga/transform module, for example, has it's test suite located at src/quagga/test/transform.spec.ts. Likewise, src/locator/barcode_locator test is located at src/locator/test/barcode_locator.spec.ts .
773
+
774
+ If you have browser or node specific tests, that must be written differently per platform, or do not apply to one platform, then you may add them to src/{filelocation}/test/browser or .../test/node. See also src/analytics/test/browser/result_collector.spec.ts, which contains browser specific code.
775
+
776
+ If you add a new test file, you should also make sure to import it in either cypress/integration/browser.spec.ts, for browser-specific tests, or cypress/integration/universal.spec.ts, for tests that can be run both in node and in browser. Node.JS testing is performed using the power of file globbing, and will pick up your tests, so long as they conform to the existing test file directory and name patterns.
777
+
778
+ ## Image Debugging
779
+
780
+ In case you want to take a deeper dive into the inner workings of Quagga, get to
781
+ know the *debugging* capabilities of the current implementation. The various
782
+ flags exposed through the `config` object give you the ability to visualize
783
+ almost every step in the processing. Because of the introduction of the
784
+ web-workers, and their restriction not to have access to the DOM, the
785
+ configuration must be explicitly set to `config.numOfWorkers = 0` in order to
786
+ work.
787
+
788
+ ## <a name="resultcollector">ResultCollector</a>
789
+
790
+ Quagga is not perfect by any means and may produce false positives from time
791
+ to time. In order to find out which images produced those false positives,
792
+ the built-in ``ResultCollector`` will support you and me helping squashing
793
+ bugs in the implementation.
794
+
795
+ ### Creating a ``ResultCollector``
796
+
797
+ You can easily create a new ``ResultCollector`` by calling its ``create``
798
+ method with a configuration.
799
+
800
+ ```javascript
801
+ var resultCollector = Quagga.ResultCollector.create({
802
+ capture: true, // keep track of the image producing this result
803
+ capacity: 20, // maximum number of results to store
804
+ blacklist: [ // list containing codes which should not be recorded
805
+ {code: "3574660239843", format: "ean_13"}],
806
+ filter: function(codeResult) {
807
+ // only store results which match this constraint
808
+ // returns true/false
809
+ // e.g.: return codeResult.format === "ean_13";
810
+ return true;
811
+ }
812
+ });
813
+ ```
814
+
815
+ ### Using a ``ResultCollector``
816
+
817
+ After creating a ``ResultCollector`` you have to attach it to Quagga by
818
+ calling ``Quagga.registerResultCollector(resultCollector)``.
819
+
820
+ ### Reading results
821
+
822
+ After a test/recording session, you can now print the collected results which
823
+ do not fit into a certain schema. Calling ``getResults`` on the
824
+ ``resultCollector`` returns an ``Array`` containing objects with:
825
+
826
+ ```javascript
827
+ {
828
+ codeResult: {}, // same as in onDetected event
829
+ frame: "data:image/png;base64,iVBOR..." // dataURL of the gray-scaled image
830
+ }
831
+ ```
832
+
833
+ The ``frame`` property is an internal representation of the image and
834
+ therefore only available in gray-scale. The dataURL representation allows
835
+ easy saving/rendering of the image.
836
+
837
+ ### Comparing results
838
+
839
+ Now, having the frames available on disk, you can load each single image by
840
+ calling ``decodeSingle`` with the same configuration as used during recording
841
+ . In order to reproduce the exact same result, you have to make sure to turn
842
+ on the ``singleChannel`` flag in the configuration when using ``decodeSingle``.
843
+
844
+ [zxing_github]: https://github.com/zxing/zxing
845
+ [teaser_left]: https://raw.githubusercontent.com/serratus/quaggaJS/master/doc/img/mobile-located.png
846
+ [teaser_right]: https://raw.githubusercontent.com/serratus/quaggaJS/master/doc/img/mobile-detected.png
847
+ [caniuse_getusermedia]: http://caniuse.com/#feat=stream
848
+ [cypressUrl]: https://www.cypress.io/
849
+ [sinonUrl]: http://sinonjs.org/
850
+ [chaiUrl]: http://chaijs.com/
851
+ [mochaUrl]: https://github.com/mochajs/mocha
852
+ [code39_wiki]: http://en.wikipedia.org/wiki/Code_39
853
+ [codabar_wiki]: http://en.wikipedia.org/wiki/Codabar
854
+ [upc_wiki]: http://en.wikipedia.org/wiki/Universal_Product_Code
855
+ [ean_8_wiki]: http://en.wikipedia.org/wiki/EAN-8
856
+ [oberhofer_co_how]: http://www.oberhofer.co/how-barcode-localization-works-in-quaggajs/
857
+ [github_examples]: https://serratus.github.io/quaggaJS/examples
858
+ [i2of5_wiki]: https://en.wikipedia.org/wiki/Interleaved_2_of_5
859
+ [enumerateDevices]: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices
860
+ [reactExample]: https://github.com/ericblade/quagga2-react-example