Coder Social home page Coder Social logo

ericblade / quagga2 Goto Github PK

View Code? Open in Web Editor NEW
731.0 19.0 84.0 135.05 MB

An advanced barcode-scanner written in Javascript and TypeScript - Continuation from https://github.com/serratus/quaggajs

License: MIT License

JavaScript 35.60% HTML 4.08% Ruby 0.22% CSS 2.19% Python 0.24% TypeScript 57.64% Dockerfile 0.02%
barcode barcode-scanner barcode-reader barcodes barcode-detection barcode-recognizer javascript node nodejs camera

quagga2's Introduction

quagga2

Rolling Versions

Join the chat at https://gitter.im/quaggaJS/Lobby

Rate on Openbase

This is a fork of the original QuaggaJS library, that will be maintained until such time as the original author and maintainer returns, or it has been completely replaced by built-in browser and node functionality.

Using React / Redux?

Please see also https://github.com/ericblade/quagga2-react-example/ and https://github.com/ericblade/quagga2-redux-middleware/

Using Angular?

Please see https://github.com/julienboulay/ngx-barcode-scanner or https://github.com/classycodeoss/mobile-scanning-demo

Using ThingWorx?

Please see https://github.com/ptc-iot-sharing/ThingworxBarcodeScannerWidget

Using Vue?

Please see https://github.com/DevinNorgarb/vue-quagga-2

What is QuaggaJS?

QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real-time localization and decoding of various types of barcodes such as EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93, CODE 32 and CODABAR. The library is also capable of using getUserMedia to get direct access to the user's camera stream. Although the code relies on heavy image-processing even recent smartphones are capable of locating and decoding barcodes in real-time.

Try some examples and check out the blog post (How barcode-localization works in QuaggaJS) if you want to dive deeper into this topic.

teaserteaser

Yet another barcode library?

This is not yet another port of the great zxing library, but more of an extension to it. This implementation features a barcode locator which is capable of finding a barcode-like pattern in an image resulting in an estimated bounding box including the rotation. Simply speaking, this reader is invariant to scale and rotation, whereas other libraries require the barcode to be aligned with the viewport.

Quagga makes use of many modern Web-APIs which are not implemented by all browsers yet. There are two modes in which Quagga operates:

  1. analyzing static images and
  2. using a camera to decode the images from a live-stream.

The latter requires the presence of the MediaDevices API. You can track the compatibility of the used Web-APIs for each mode:

Static Images

The following APIs need to be implemented in your browser:

Live Stream

In addition to the APIs mentioned above:

Important: Accessing getUserMedia requires a secure origin in most browsers, meaning that http:// can only be used on localhost. All other hostnames need to be served via https://. You can find more information in the Chrome M47 WebRTC Release Notes.

Feature-detection of getUserMedia

Every browser seems to differently implement the mediaDevices.getUserMedia API. Therefore it's highly recommended to include webrtc-adapter in your project.

Here's how you can test your browser's capabilities:

if (navigator.mediaDevices && typeof navigator.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

Quagga2 can be installed using npm, or by including it with the script tag.

NPM

> npm install --save @ericblade/quagga2

And then import it as dependency in your project:

import Quagga from '@ericblade/quagga2'; // ES6
const Quagga = require('@ericblade/quagga2').default; // Common JS (important: default)

Currently, the full functionality is only available through the browser. When using QuaggaJS within node, only file-based decoding is available. See the example for node_examples.

Using with script tag

You can simply include quagga.js in your project and you are ready to go. The script exposes the library on the global namespace under Quagga.

<script src="quagga.js"></script>

You can get the quagga.js file in the following ways:

By installing the npm module and copying the quagga.js file from the dist folder.

(OR)

You can also build the library yourself and copy quagga.js file from the dist folder(refer to the building section for more details)

(OR)

You can include the following script tags with CDN links:

a) quagga.js

<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.js"></script>

b) quagga.min.js (minified version)

<script src="https://cdn.jsdelivr.net/npm/@ericblade/quagga2/dist/quagga.min.js"></script>

Note: You can include a specific version of the library by including the version as shown below.

<!-- Link for Version 1.2.6 -->
<script src="https://cdn.jsdelivr.net/npm/@ericblade/[email protected]/dist/quagga.js"></script>

For starters, have a look at the examples to get an idea where to go from here.

There is a separate example for using quagga2 with ReactJS

New in Quagga2 is the ability to specify external reader modules. Please see quagga2-reader-qr. This repository includes a sample external reader that can read complete images, and decode QR codes. A test script is included to demonstrate how to use an external reader in your project.

Quagga2 exports the BarcodeReader prototype, which should also allow you to create new barcode reader implementations using the base BarcodeReader implementation inside Quagga2. The QR reader does not make use of this functionality, as QR is not picked up as a barcode in BarcodeReader.

You can build the library yourself by simply cloning the repo and typing:

> npm install
> npm run build

or using Docker:

> docker build --tag quagga2/build .
> docker run -v $(pwd):/quagga2 quagga2/build npm install
> docker run -v $(pwd):/quagga2 quagga2/build npm run build

it's also possible to use docker-compose:

> docker-compose run nodejs npm install
> docker-compose run nodejs npm run build

Note: when using Docker or docker-compose the build artifacts will end up in dist/ as usual thanks to the bind-mount.

This npm script builds a non optimized version quagga.js and a minified version quagga.min.js and places both files in the dist folder. Additionally, a quagga.map source-map is placed alongside these files. This file is only valid for the non-uglified version quagga.js because the minified version is altered after compression and does not align with the map file any more.

If you are working on a project that includes quagga, but you need to use a development version of quagga, then you can run from the quagga directory:

npm install && npm run build && npm link

then from the other project directory that needs this quagga, do

npm link @ericblade/quagga2

When linking is successful, all future runs of 'npm run build' will update the version that is linked in the project. When combined with an application using webpack-dev-server or some other hot-reload system, you can do very rapid iteration this way.

Node

The code in the dist folder is only targeted to the browser and won't work in node due to the dependency on the DOM. For the use in node, the build command also creates a quagga.js file in the lib folder.

You can check out the examples to get an idea of how to use QuaggaJS. Basically the library exposes the following API:

This method initializes the library for a given configuration config (see below) and invokes the callback(err) when Quagga has finished its bootstrapping phase. The initialization process also requests for camera access if real-time detection is configured. In case of an error, the err parameter is set and contains information about the cause. A potential cause may be the inputStream.type is set to LiveStream, but the browser does not support this API, or simply if the user denies the permission to use the camera.

If you do not specify a target, QuaggaJS would look for an element that matches the CSS selector #interactive.viewport (for backwards compatibility). target can be a string (CSS selector matching one of your DOM node) or a DOM node.

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();
  });

Quagga.start()

When the library is initialized, the start() method starts the video-stream and begins locating and decoding the images.

Quagga.stop()

If the decoder is currently running, after calling stop() the decoder does not process any more images. Additionally, if a camera-stream was requested upon initialization, this operation also disconnects the camera.

Quagga.onProcessed(callback)

This method registers a callback(data) function that is called for each frame after the processing is done. The data object contains detailed information about the success/failure of the operation. The output varies, depending whether the detection and/or decoding were successful or not.

Quagga.onDetected(callback)

Registers a callback(data) function which is triggered whenever a barcode- pattern has been located and decoded successfully. The passed data object contains information about the decoding process including the detected code which can be obtained by calling data.codeResult.code.

Quagga.decodeSingle(config, callback)

In contrast to the calls described above, this method does not rely on getUserMedia and operates on a single image instead. The provided callback is the same as in onDetected and contains the result data object.

Quagga.offProcessed(handler)

In case the onProcessed event is no longer relevant, offProcessed removes the given handler from the event-queue. When no handler is passed, all handlers are removed.

Quagga.offDetected(handler)

In case the onDetected event is no longer relevant, offDetected removes the given handler from the event-queue. When no handler is passed, all handlers are removed.

The callbacks passed into onProcessed, onDetected and decodeSingle receive a data object upon execution. The data object contains the following information. Depending on the success, some fields may be undefined or just empty.

{
  "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]
    ]
  ]
}

Quagga2 exposes a CameraAccess API that is available for performing some shortcut access to commonly used camera functions. This API is available as Quagga.CameraAccess and is documented below.

CameraAccess.request(HTMLVideoElement | null, MediaTrackConstraints?)

Will attempt to initialize the camera and start playback given the specified video element. Camera is selected by the browser based on the MediaTrackConstraints supplied. If no video element is supplied, the camera will be initialized but invisible. This is mostly useful for probing that the camera is available, or probing to make sure that permissions are granted by the user. This function will return a Promise that resolves when completed, or rejects on error.

CameraAccess.release()

If a video element is known to be running, this will pause the video element, then return a Promise that when resolved will have stopped all tracks in the video element, and released all resources.

CameraAccess.enumerateVideoDevices()

This will send out a call to navigator.mediaDevices.enumerateDevices(), filter out any mediadevices that do not have a kind of 'videoinput', and resolve the promise with an array of MediaDeviceInfo.

CameraAccess.getActiveStreamLabel()

Returns the label for the active video track

CameraAccess.getActiveTrack()

Returns the MediaStreamTrack for the active video track

CameraAccess.disableTorch()

Turns off Torch. (Camera Flash) Resolves when complete, throws on error. Does not work on iOS devices of at least version 16.4 and earlier. May or may not work on later versions.

CameraAccess

Turns on Torch. (Camera Flash) Resolves when complete, throws on error. Does not work on iOS devices of at least version 16.4 and earlier. May or may not work on later versions.

The configuration that ships with QuaggaJS covers the default use-cases and can be fine-tuned for specific requirements.

The configuration is managed by the config object defining the following high-level properties:

{
  locate: true,
  inputStream: {...},
  frequency: 10,
  decoder:{...},
  locator: {...},
  debug: false,
}

locate

One of the main features of QuaggaJS is its ability to locate a barcode in a given image. The locate property controls whether this feature is turned on (default) or off.

Why would someone turn this feature off? Localizing a barcode is a computationally expensive operation and might not work properly on some devices. Another reason would be the lack of auto-focus producing blurry images which makes the localization feature very unstable.

However, even if none of the above apply, there is one more case where it might be useful to disable locate: If the orientation, and/or the approximate position of the barcode is known, or if you want to guide the user through a rectangular outline. This can increase performance and robustness at the same time.

inputStream

The inputStream 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 area
    top: "0%",    // top offset
    right: "0%",  // right offset
    left: "0%",   // left offset
    bottom: "0%"  // bottom offset
  },
  singleChannel: false // true: only the red color-channel is read
}

First, the type property can be set to three different values: ImageStream, VideoStream, or LiveStream (default) and should be selected depending on the use-case. Most probably, the default value is sufficient.

Second, the constraint key defines the physical dimensions of the input image and additional properties, such as facingMode which sets the source of the user's camera in case of multiple attached devices. Additionally, if required, the deviceId can be set if the selection of the camera is given to the user. This can be easily achieved via MediaDevices.enumerateDevices()

Thirdly, the area prop restricts the decoding area of the image. The values are given in percentage, similar to the CSS style property when using position: absolute. This area is also useful in cases the locate property is set to false, defining the rectangle for the user.

The last key singleChannel is only relevant in cases someone wants to debug erroneous behavior of the decoder. If set to true the input image's red color-channel is read instead of calculating the gray-scale values of the source's RGB. This is useful in combination with the ResultCollector where the gray-scale representations of the wrongly identified images are saved.

frequency

This top-level property controls the scan-frequency of the video-stream. It's optional and defines the maximum number of scans per second. This renders useful for cases where the scan-session is long-running and resources such as CPU power are of concern.

decoder

QuaggaJS usually runs in a two-stage manner (locate is set to true) where, after the barcode is located, the decoding process starts. Decoding is the process of converting the bars into their true meaning. Most of the configuration options within the decoder 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 is readers which takes an array of types of barcodes 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
  • code_32_reader

Why are not all types activated by default? Simply because one should explicitly define the set of barcodes for their use-case. More decoders means more possible clashes, or false-positives. One should take care of the order the readers are given, since some might return a value even though it is not the correct type (EAN-13 vs. UPC-A).

The multiple property tells the decoder if it should continue decoding after finding a valid barcode. If multiple is set to true, the results will be returned as an array of result objects. Each object in the array will have a box, and may have a codeResult depending on the success of decoding the individual box.

The remaining properties drawBoundingBox, showFrequency, drawScanline and showPattern are mostly of interest during debugging and visualization.

The default setting for ean_reader is not capable of reading extensions such as EAN-2 or EAN-5. In order to activate those supplements 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 the supplements matters in such that the reader stops decoding when the first supplement was found. So if you are interested in EAN-2 and EAN-5 extensions, use the order depicted above.

It's important to mention that, if supplements are supplied, regular EAN-13 codes cannot be read any more with the same reader. If you want to read EAN-13 with and without extensions you have to add another ean_reader reader to the configuration.

locator

The locator config is only relevant if the locate flag is set to true. It controls the behavior of the localization-process and needs to be adjusted for each specific use-case. The default settings are simply a combination of values which worked best during development.

Only two properties are relevant for the use in Quagga (halfSample and patchSize) whereas the rest is only needed for development and debugging.

{
  halfSample: true,
  patchSize: "medium", // x-small, small, medium, large, x-large
  debug: {
    showCanvas: false,
    showPatches: false,
    showFoundPatches: false,
    showSkeleton: false,
    showLabels: false,
    showPatchLabels: false,
    showRemainingPatchLabels: false,
    boxFromPatches: {
      showTransformed: false,
      showTransformedBox: false,
      showBB: false
    }
  }
}

The halfSample flag tells the locator-process whether it should operate on an image scaled down (half width/height, quarter pixel-count ) or not. Turning halfSample on reduces the processing-time significantly and also helps finding a barcode pattern due to implicit smoothing. It should be turned off in cases where the barcode is really small and the full resolution is needed to find the position. It's recommended to keep it turned on and use a higher resolution video-image if needed.

The second property patchSize defines the density of the search-grid. The property accepts strings of the value x-small, small, medium, large and x-large. The patchSize is proportional to the size of the scanned barcodes. If you have really large barcodes which can be read close-up, then the use of large or x-large is recommended. In cases where the barcode is further away from the camera lens (lack of auto-focus, or small barcodes) then it's advised to set the size to small or even x-small. For the latter it's also recommended to crank up the resolution in order to find a barcode.

Examples

The following example takes an image src as input and prints the result on the console. The decoder is configured to detect Code128 barcodes and enables the locating-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 image
    src: '/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 node environment. It's almost identical to the browser version with the difference that node does not support web-workers out of the box. Therefore the config property numOfWorkers must be explicitly set to 0.

var Quagga = require('quagga').default;

Quagga.decodeSingle({
    src: "image-abc-123.jpg",
    numOfWorkers: 0,  // Needs to be 0 when used within node
    inputStream: {
        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.

Working with Cordova / PhoneGap?

If you're having issues getting a mobile device to run Quagga using Cordova, you might try the code here: Original Repo Issue #94 Comment

let permissions = cordova.plugins.permissions; permissions.checkPermission(permissions.CAMERA,
(res) => { if (!res.hasPermission) { permissions.requestPermission(permissions.CAMERA, open());

Thanks, @chrisrodriguezmbww !

Barcodes too small?

Barcodes too far away from the camera, or a lens too close to the object result in poor recognition rates and Quagga might respond with a lot of false-positives.

Starting in Chrome 59 you can now make use of capabilities and directly control the zoom of the camera. Head over to the web-cam demo and check out the Zoom feature.

You can read more about those capabilities in Let's light a torch and explore MediaStreamTrack's capabilities

Video too dark?

Dark environments usually result in noisy images and therefore mess with the recognition logic.

Since Chrome 59 you can turn on/off the Torch of your device and vastly improve the quality of the images. Head over to the web-cam demo and check out the Torch feature.

To find out more about this feature read on.

Handling false positives

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.

If you choose to explore check-digit validation, you might find barcode-validator a useful library.

Tests

Tests are performed with Cypress for browser testing, and Mocha, Chai, and SinonJS 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)

Coverage reports are generated in the coverage/ folder.

> npm install
> npm run test

Using Docker:

> docker build --tag quagga2/build .
> docker run -v $(pwd):/quagga2 npm install
> docker run -v $(pwd):/quagga2 npm run test

or using docker-compose:

> docker-compose run nodejs npm install
> docker-compose run nodejs npm run test

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 .

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.

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.

Image Debugging

In case you want to take a deeper dive into the inner workings of Quagga, get to know the debugging capabilities of the current implementation. The various flags exposed through the config object give you the ability to visualize almost every step in the processing. Because of the introduction of the web-workers, and their restriction not to have access to the DOM, the configuration must be explicitly set to config.numOfWorkers = 0 in order to work.

Quagga is not perfect by any means and may produce false positives from time to time. In order to find out which images produced those false positives, the built-in ResultCollector will support you and me helping squashing bugs in the implementation.

Creating a ResultCollector

You can easily create a new ResultCollector by calling its create method with a configuration.

var resultCollector = Quagga.ResultCollector.create({
    capture: true, // keep track of the image producing this result
    capacity: 20,  // maximum number of results to store
    blacklist: [   // 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";
        return true;
    }
});

Using a ResultCollector

After creating a ResultCollector you have to attach it to Quagga by calling Quagga.registerResultCollector(resultCollector).

Reading results

After a test/recording session, you can now print the collected results which do not fit into a certain schema. Calling getResults on the resultCollector returns an Array containing objects with:

{
    codeResult: {}, // same as in onDetected event
    frame: "data:image/png;base64,iVBOR..." // dataURL of the gray-scaled image
}

The frame property is an internal representation of the image and therefore only available in gray-scale. The dataURL representation allows easy saving/rendering of the image.

Comparing results

Now, having the frames available on disk, you can load each single image by calling decodeSingle with the same configuration as used during recording . In order to reproduce the exact same result, you have to make sure to turn on the singleChannel flag in the configuration when using decodeSingle.

quagga2's People

Contributors

aihowes avatar andyedinborough avatar benk-lastyard avatar benmorel avatar danmana avatar davincho avatar dependabot[bot] avatar dgreif avatar elsigh avatar ericblade avatar forbeslindesay avatar greenkeeper[bot] avatar hadrien-f avatar imgbotapp avatar jpsfs avatar kevinpapst avatar lasserafn avatar mtillmann avatar nedac-sorbo avatar nicolashenry avatar oidualc avatar serratus avatar snyk-bot avatar stefanocali avatar sudhamjayanthi avatar tomashubelbauer avatar twsouthwick avatar uzitech avatar yadlamani avatar zupzup avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

quagga2's Issues

Failed to run demo: Cannot read property 'ImageWrapper' of undefined

I'm trying to run this demo in React, but always got error:

image

import React, { useState, FC, useRef, useEffect, isValidElement } from "react";

import { QuaggaJSStatic } from "@ericblade/quagga2";
import QuaggaLib from "@ericblade/quagga2/lib/quagga";

let Quagga: QuaggaJSStatic = QuaggaLib;

let BarcodeArea: FC<{}> = (props) => {
  let videoElementRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    Quagga.init(
      {
        inputStream: {
          type: "LiveStream",
          target: videoElementRef.current,
          constraints: {
            width: 400,
            height: 400,
          },
        },
        locate: false,
        numOfWorkers: 2,
        frequency: 10,
        decoder: {
          readers: ["code_128_reader"],
        },
      },
      (err) => {
        if (err) {
          console.error(err);
          return;
        }

        console.log("started");
        Quagga.start();
      }
    );

    Quagga.onDetected((result) => {
      console.log("detect", result);
    });

    Quagga.onProcessed((result) => {
      console.log("process", result);
    });

    return () => {
      Quagga.stop();
    };
  }, []);

  return <div className={styleVideo} ref={videoElementRef}></div>;
};

Also I tried to run the demo at http://localhost:8080/example/live_w_locator.html by fixing the paths and adding Quagga = quagga.default. Turned out the problem remains.

Is there a fix for that?

update to typescript

serratus/quaggaJS#385

I'm totally interested in doing TypeScript. I haven't done anything with TS before, so not exactly my forte, but I'm very interested in picking it up. There's been a lot of interest by others in the past, and with the pull request referenced above, it'd be a fantastic point to get started with.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

tests fail in windows, phantomjs not starting

Not sure if this is an issue with how we're using it, or phantomjs itself, but it's not starting when running in Windows. (it does work fine in WSL1 and WSL2 in Windows, so i'm not entirely worried about it, but it's something that should be fixed probably)

anyone know what "box" and "boxes" results represent?

... I'm slightly confused as to what the "box" and "boxes" results represent. 'box' appears to be a 4 length array of 2-length arrays, but i'd expect a box would just be a single point pair.. rather than 4 of them. 'boxes' just seems to be an array of that array, though that might be different if multiples are encountered.

remove unnecessary bower tooling

The world pretty much uses npm or yarn to install javascript modules, I don't think we need to continue supporting bower for that. I'm not yet sure if grunt is used in any way inside the project, or just as an alternative packaging/distribution method to npm. The commit here serratus/quaggaJS@05e6b46#diff-b9cfc7f2cdf78a7f4b91a753d10865a2 seems to include removal of bower/grunt, and unless someone has a good reason for us to keep it, i say we don't.

  • edit: this task originally said grunt not bower. it looks like grunt is used in the build system presently, particularly to run "uglyasm" , though it might be simple to remove the dependency on grunt there too, i just haven't looked to see how that works

An in-range update of snyk is breaking the build 🚨

The dependency snyk was updated from 1.230.5 to 1.230.6.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

snyk is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v1.230.6

1.230.6 (2019-10-04)

Bug Fixes

  • add packed dependency to prevent download from git (c918814)
Commits

The new version differs by 4 commits.

  • e6568ec Merge pull request #797 from snyk/test/remove-bad-test
  • f365660 test: skip test that uses previous bad version
  • 0c6026e Merge pull request #795 from snyk/fix/https-agent-vuln
  • c918814 fix: add packed dependency to prevent download from git

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Having a hard time activating debug functionalities

Working with NPM version of quagga2, I'm trying to activate debugging but nothing works

My configs

 Quagga.init({
      numOfWorkers: 0,
      frequency: 15,
      debug: true,
      locate: true,

      inputStream: {
        name: 'Live',
        type: 'LiveStream',
        target: '#liveStream',
        constraints: {
          width: 640,
          height: 480,
          facingMode: 'environment' // or user
        },
      },

      locator: {
        patchSize: 'x-large',
        halfSample: false,
        debug: {
          showCanvas: true,
          showPatches: true,
          showFoundPatches: true,
          showSkeleton: true,
          showLabels: true,
          showPatchLabels: true,
          showRemainingPatchLabels: true,
          boxFromPatches: {
            showTransformed: true,
            showTransformedBox: true,
            showBB: true
          }
        }
      },

      decoder: {
        readers: [
          "code_128_reader",
          "code_39_reader",
          "code_39_vin_reader",
          "code_qr_reader",
        ],
        debug: {
          drawBoundingBox: true,
          showFrequency: true,
          drawScanline: true,
          showPattern: true
        },
        multiple: false,
      },

I'm not sure what I'm doing wrong. Is debugging only available when working directly with sources? I do see a lot of if (ENV.development) in quagga code.

get tests working

Here's a pull req I made about a year ago to deal with some of the issues with testing

#1

If anyone has any more insight into how to get the tests fully functioning, that'd be great. It'd be fantastic to have a fully running test environment before getting into any meaty changes.

Document dist file creation

#27 has instructions on how to get a precompiled file that can later be included in a script tag. While I don't approve of this approach, if the compiled JS file will never be published, it should be documented in the README. Right now README tells to include a file from a dist/ folder, which is gone.

I would propose to include .js/.min.js files within the release though.

need to confirm that release 0.0.1 works as a node package

I've already tested that quagga2 0.0.1 works in browser, at least with my application's installation, simply by changing all instances of import Quagga from 'quagga'; to import Quagga from '@ericblade/quagga2';. I have not validated yet that it is working when used in a node environment, as I don't presently use it in a node environment for anything.

Organisation

Hello, maybe you should create a github organisation so if you also stop to work on this, others can still support ?

I do this for all my projects. see: https://github.com/node-projects

I also use quagga and will switch to your fork.

Major: rebuild testsuite using more modern configurations

The existing test setup is .. quite.. dated. I've been working with Cypress on some of my other projects, and I have suspicions that using it here could be quite advantageous compared to the older methods of browser testing that the current setup is using.

Should set numOfWorkers to 0 automatically when Blob isn't available

In the present version of the code, numOfWorkers > 0 fails in node due to (at the very least) Blob not being available. While Node probably can support the workers system now (probably with some changes), it would need to be fairly significantly overhauled to use Buffer instead of Blob, and then that would create browser issues, so we'd need to shim some sort of Buffer/Blob compatibility thing, or just re-do the worker part.

THEREFORE, I believe we should have the code basically check if (typeof Blob) { config.numOfWorkers = 0 } instead of allowing you to attempt to use it where it can't work, and getting failures that don't make sense.

dist/quagga.min.js file gone

Hi, I would like to use this project using the script tag as written in readme but the dist/quagga.min.js file is missing.

I am not familiar with NPM.

Maybe you have an updated version of the quagga.min.js I could use?

Thanks for continuing this project!

external readers don't work where numOfWorkers > 0

It appears that the READERS var the threads are referencing doesn't get updated, and I'm a bit overall confused about why. Attempting to debug through some of these processes has just presented me with DOM errors. :-S

should attempt to protect onDetected and other events from being called with null/undefined/etc handlers

On Android I experienced a problem where my in development re-write of my app would not open the camera. It turns out that I hadn't provided an onDetected method, but my app was calling onDetected(undefined) on it. This lead to a failure when attempting to open the camera on Android. I don't understand why it only affects Chrome on Android, and not Chrome on desktop.

Anyway, calling onDetected(undefined) should probably be a no-op with a warning logged so you know your code is doing something you didn't intend, without totally breaking it in an inexplicable fashion.

add function to ImageWrapper to get RGBA data

ImageWrapper.prototype.show converts the wrapped image data from 1-channel greyscale to RGBA. Also, quagga2-reader-qr needs RGBA image data. Therefore, I propose a utility function to return RGBA data should be accessible to external readers, and also used internally where necessary.

all barcode tests fail on extremely slow CPU

... I just tried to run npm test on a laptop that is presently throttling to minimum CPU speed thanks to having either a bad or incorrect charger.

All barcode decoding tests failed. This is hopefully just a need to adjust the timeout on tests, but it could be a sign of something that is very cpu dependent occurring, which is worth investigating.

Anyone interested in digging through the Forks?

There's over 600 forks of the original repo, and I think most anyone would be surprised if more than half had any commits in them, but the ones that do might have some very good things that were never PR'd to the original repo. Anyone know of any scripts that are good to dig through that sort of thing? Or interested in doing it? (i mean, i am interested in doing it, but if there's anyone else that wants to help, maybe we can split the task up some)

Major restructuring of quagga.js main module required to fix decodeSingle, numOfWorkers, etc

Related to:
#103 (workers are completely broken after typescript due to removal of the custom UMD module generator that does not work with webpack v4) -- restructure so webpack worker-loader works correctly

#5 (parallel decoding with decodeSingle() is totally broken)

#78 (external reader plugins fail due to using workers) - workers need to be able to receive readers from external sources, or workers must be disabled for using external sources.

The answer to these problems is to restructure the main Quagga library so that it is able to create multiple instances of the reader/decoder system, and handle those instances inside a static module that basically looks like the current interface.

Closing related issues in favor of this one.

update module dependencies

many, many of the dependencies are significantly outdated.

an npm install in the base directory at the time of starting this fork results in:

D:\src\quaggajs>npm install --save
npm WARN deprecated [email protected]: Package is deprecated, use https://github.com/deepsweet/istanbul-instrumenter-loader
npm WARN deprecated [email protected]: Package is deprecated, use https://github.com/deepsweet/istanbul-instrumenter-loader
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: CoffeeScript on NPM has moved to "coffeescript" (no hyphen)
npm WARN deprecated [email protected]: This package is unmaintained. Use @sinonjs/formatio instead
npm WARN deprecated [email protected]: Jade has been renamed to pug, please install the latest version of pug instead of jade
npm WARN deprecated [email protected]: to-iso-string has been deprecated, use @segment/to-iso-string instead.
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: please upgrade to graceful-fs 4 for compatibility with current and future versions of Node.js
npm WARN deprecated [email protected]: This module is no longer maintained, try this instead:
npm WARN deprecated   npm i nyc
npm WARN deprecated Visit https://istanbul.js.org/integrations for other alternatives.
npm WARN deprecated [email protected]: Use uuid module instead
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: ReDoS vulnerability parsing Set-Cookie https://nodesecurity.io/advisories/130

> [email protected] install D:\src\quaggajs\node_modules\phantomjs
> node install.js

PhantomJS not found on PATH
Downloading https://github.com/Medium/phantomjs/releases/download/v1.9.19/phantomjs-1.9.8-windows.zip
Saving to C:\Users\Eric\AppData\Local\Temp\phantomjs\phantomjs-1.9.8-windows.zip
Receiving...
  [----------------------------------------] 0%
Received 7292K total.
Extracting zip contents
Removing D:\src\quaggajs\node_modules\phantomjs\lib\phantom
Copying extracted folder C:\Users\Eric\AppData\Local\Temp\phantomjs\phantomjs-1.9.8-windows.zip-extract-1565737401317\phantomjs-1.9.8-windows -> D:\src\quaggajs\node_modules\phantomjs\lib\phantom
Writing location.js file
Done. Phantomjs binary available at D:\src\quaggajs\node_modules\phantomjs\lib\phantom\phantomjs.exe

> [email protected] postinstall D:\src\quaggajs\node_modules\core-js
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
> https://opencollective.com/core-js 
> https://www.patreon.com/zloirock 

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN [email protected] requires a peer of sinon@>=2.1.0 <5 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

added 1193 packages from 1485 contributors and audited 9721 packages in 240.834s
found 137 vulnerabilities (45 low, 26 moderate, 65 high, 1 critical)
  run `npm audit fix` to fix them, or `npm audit` for details

drawingBuffer canvas should probably be inside the video element, not below

CSS positioning is a nightmare. It works much easier having the drawingBuffer canvas inside the video element, so it inherits the same box.

As Quagga does support sending in a previously created container, as well as giving it a proper video and canvas element (as well as a "imgBuffer" tagged canvas, which I'm not sure what that is used for just yet), I'm using a sample that looks like

            <div className={css.scannerContainer} ref={scannerRef}>
                <video style={{width: window.innerWidth, height: 480}}>
                    <canvas className="drawingBuffer" width="640" height="480" />
                </video>
                <Scanner scannerRef={scannerOpen && scannerRef} onScannerReady={onScannerReady} onDetected={() => console.warn('* onDetected')} />
            </div>

This allows me to get proper canvas positioning, without having to resort to bizarre CSS tricks, so I'm pretty sure that this should be the default method for creating it when you don't provide a custom video and canvas element

Not detecting barcodes without successful scan

Thank you for taking over maintainership of this package!

I noticed the live_w_locator example has changed behavior between versions 0.0.2 and 0.0.3. Earlier, the scanner was painting green squares when it started noticing barcodes without successfully scanning them, i.e., onDetected callback is not called. Now, the green squares are only painted when a barcode is successfully scanned. So it seems the content of result.boxes for the Quagga.onProcessed callback behaves differently after version 0.0.3. Is this a regression?

To reproduce

do we need src/common/typedefs.js

Looks like a utility lib of polyfills. The typescript branch has some magic from the babel packages that probably covers it, so I wonder if removing it is ok to do there.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Who has a modern iOS device that can test for iOS issues?

One of the things that we routinely saw a ton of on the other repo was people having issues with iOS. Unfortunately, the only iOS device I have is an iPad mini 2, which will not receive a version of iOS that provides getUserMedia . . . so I am completely useless on helping to track down any issues, or write any workarounds, or really provide any help at all with iOS.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.