Skip to content

Commit

Permalink
Rewrite readme
Browse files Browse the repository at this point in the history
  • Loading branch information
cozmo committed Dec 16, 2017
1 parent bdf11a0 commit 0f218a3
Show file tree
Hide file tree
Showing 9 changed files with 2,124 additions and 170 deletions.
188 changes: 48 additions & 140 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,184 +2,92 @@

[![Build Status](https://travis-ci.org/cozmo/jsQR.svg?branch=master)](https://travis-ci.org/cozmo/jsQR)

A pure javascript port of the [ZXing](https://github.com/zxing/zxing) QR parsing library.
A pure javascript QR code reading library.
This library takes in raw images and will locate, extract and parse any QR codes found within.
It also exposes methods to do each step of the process individually.
This allows piecemeal use and custom extension, for example you can use this library to parse pure QR codes (without extracting from an image), or to locate QR codes within an image without parsing them.

[See a demo](https://s3-us-west-2.amazonaws.com/templaedhel/jsQR/features.html)
[Demo](https://cozmo.github.io/jsQR)

## Motivation

This library was written because there were no javascript QR code parsing libraries that were well maintained and capable of parsing any reasonably complex QR codes.
## Installation

[See how jsQR compares to other JS QR code decoders](https://s3-us-west-2.amazonaws.com/templaedhel/jsQR/comparison.html)

[ZXing](https://github.com/zxing/zxing) is the best QR code library, and had been ported to many languages, but not to Javascript.
jsQR is a fully featured port of the QR code portions of the zxing library, with the goal of growing into a maintainable and extendable QR parsing library in pure javascript.

## Documentation

### Installation

#### NodeJS
### NodeJS

```
npm install jsqr --save
```

```javascript
jsQR = require("jsqr");
// ES6 import
import jsQR from "jsqr";

// CommonJS require
const jsQR = require("jsqr");

jsQR(...);
```

#### Browser
### Browser

Include [`jsQR.js`](./dist/jsQR.js).

```html
<script src="jsQR.js"></script>
<script>
jsQR(...);
</script>
```

You can also use module loaders such as [requireJS](http://requirejs.org/) or [browserify](http://browserify.org/)
## Usage

### Usage

qrJS exports methods for each step in the QR recognition, extraction and decoding process, as well as a convenience wrapper method.

#### Examples

Using the wrapper method
```javascript
var decoded = jsQR.decodeQRFromImage(data, width, height);
```
jsQR exports a method that takes in 3 arguments representing the image data you wish to decode.

Using the individual methods
```javascript
var binarizedImage = binarizeImage(data, width, height);
var location = locateQRInBinaryImage(binarizedImage);
if (!location) {
return;
}
var rawQR = extractQRFromBinaryImage(binarizedImage, location);
if (!rawQR) {
return;
}

console.log(decodeQR(rawQR));
```

[Working example of parsing a webcam feed](https://s3-us-west-2.amazonaws.com/templaedhel/jsQR/example.html)

### Methods

#### qrJS.decodeQRFromImage(data, width, height)

`decodeQRFromImage` is a wrapper method for the different steps of the QR decoding process.
It takes in a RGBA image and returns a string representation of the data encoded within any detected QR codes.

##### Arguments
- `data` - An 1d array of numbers representing an RGBA image in the form `r1, g1, b1, a1, r2, g2, b2, a2,...`. This is the same form as the [`ImageData`](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) type returned by the `.getImageData()` call when reading data from a canvas element.
- `width` - The width of the image.
- `height` The height of the image.

`data.length` should always be equal to `width * height * 4`.

#### qrJS.binarizeImage(data, width, height)
const code = jsQR(imageData, width, height);

Binarizing an image (converting it to an image where pixels are either back or white, not grey) is the first step of the process.
binarizeImage takes in a RGBA image and returns a [`BitMatrix`](#bitmatrices) representing the binarized form of that image.

##### Arguments
- `data` - An 1d array of numbers representing an RGBA image in the form `r1, g1, b1, a1, r2, g2, b2, a2,...`. This is the same form as the [`ImageData`](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) type returned by the `.getImageData()` call when reading data from a canvas element.
- `width` - The width of the image.
- `height` The height of the image.

`data.length` should always be equal to `width * height * 4`.

#### qrJS.locateQRInBinaryImage(image)

`locateQRInBinaryImage` takes in a [`BitMatrix`](#bitmatrices) representing a binary image (as output by [`binarizeImage`](#qrjsbinarizeimagedata-width-height)) and returns the location of a QR code if one is detected.

##### Arguments
- `image` - a [`BitMatrix`](#bitmatrices) representing a binary image (as output by [`binarizeImage`](#qrjsbinarizeimagedata-width-height))

##### Returns
`locateQRInBinaryImage` returns `null` if no QR is found, else it returns an object with the following structure

```javascript
{
bottomLeft: {
x: number,
y: number
},
topLeft: {
x: number,
y: number
},
topRight: {
x: number,
y: number
}
if (code) {
console.log("Found QR code", code);
}
```
The coordinates represent the pixel locations of the QR's corner points.

#### qrJS.extractQRFromBinaryImage(image, location)

`extractQRFromBinaryImage` takes in a [`BitMatrix`](#bitmatrices) representing a binary image (as output by [`binarizeImage`](#qrjsbinarizeimagedata-width-height)) and the location of a QR code. It returns a [`BitMatrix`](#bitmatrices) representing the raw QR code.

##### Arguments
- `image` - a [`BitMatrix`](#bitmatrices) representing a binary image (as output by [`binarizeImage`](#qrjsbinarizeimagedata-width-height))
- `location` - The location of a QR code, as returned by [`locateQRInBinaryImage`](#qrjslocateqrinbinaryimageimage)

##### Returns
`extractQRFromBinaryImage` a [`BitMatrix`](#bitmatrices) representing the extracted QR code. The matrix is size `N` by `N` where `N` is the number of "blocks" along the edge of the QR code.

#### qrJS.decodeQR(qrCode)

`decodeQR` takes in a [`BitMatrix`](#bitmatrices) representing a raw QR code (as output by [`extractQRFromBinaryImage`](#qrjsextractqrfrombinaryimageimage-location)) and returns a string of decoded data. It is the last step in the QR decoding process.

##### Arguments
- `qrCode` - a [`BitMatrix`](#bitmatrices) representing a raw QR code (as output by [`extractQRFromBinaryImage`](#qrjsextractqrfrombinaryimageimage-location))

#### BitMatrices

Throughout the QR extraction and decoding process data is often represented as a `BitMatrix`.
BitMatrices are a convenient way to represent and interact with a 2d array of booleans.

##### Properties
- `width` - The width of the matrix.
- `height` - The height of the matrix.
- `data` - The underlying data (represented as a 1d array)

##### Methods
- `get(x, y)` - Get the bit at specific coordinates.
- `set(x, y, bit)` - Set the bit at specific coordinates.

#### qrJS.createBitMatrix(data, width)
`createBitMatrix` is a convenience method for creating bit matrices.

##### Arguments
- `data` - A 1d array of booleans representing the data represented by the bit matrix.
- `width` - The width of the matrix (height is inferred by `data.length / width`).
### Arguments
- `imageData` - An `Uint8ClampedArray` of RGBA pixel values in the form `[r0, g0, b0, a0, r1, g1, b1, a1, ...]`.
As such the length of this array should be `4 * width * height`.
This data is in the same form as the [`ImageData`](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) interface, and it's also [commonly](https://www.npmjs.com/package/jpeg-js#decoding-jpegs) [returned](https://github.com/lukeapage/pngjs/blob/master/README.md#property-data) by node modules for reading images.
- `width` - The width of the image you wish to decode.
- `height` The height of the image you wish to decode.

### Return value
If a QR is able to be decoded the library will return an object with the following keys.

- `binaryData` - `Uint8ClampedArray` - The raw bytes of the QR code.
- `encodingType` - The encoding type used in the QR code. `"numeric"`, `"alphanumeric"`, `"kanji"`, `"byte"`, `"structured_append"` or `"eci"`.
- `data` - The decoded form of the `binaryData` if there is one.
- If the `encodingType` is `numeric` then a number.
- If the `encodingType` is `alphanumeric` or `kanji` then a string.
- Does not exist for all other encoding types.
- `errorRate` - A `number` between 0 and 1 indicating how the error correction rate during decoding.
0 indicates a QR code that was perfectly read.
In practice will never be 1 since a QR code with 100% error rate wouldn't be possible to decode.
- `location` - An object with keys describing key points of the QR code. Each key is a point of the form `{x: number, y: number}`.
Has points for the following locations.
- Corners - `topRightCorner`/`topLeftCorner`/`bottomRightCorner`/`bottomLeftCorner`;
- Finder patterns - `topRightFinderPattern`/`topLeftFinderPattern`/`bottomLeftFinderPattern`
- May also have a point for the `bottomRightAlignmentPattern` assuming one exists and can be located.

Because the library is written in [typescript](http://www.typescriptlang.org/) you can also view the [type definitions](./dist/index.d.ts) to understand the API.

## Contributing

jsQR is written using [typescript](http://www.typescriptlang.org/).
You can view the development source in the `src` directory.
You can view the development source in the [`src`](./src) directory.

Tests can be run with

```
npm test
```

The test suite is several hundred images that can be found in the [test-data/](./test-data/images) folder. These images have been collected from

1. the original ZXing test suite
2. Creative commons images that have QR codes in them
3. Issues that have been filed.

The test suite is several hundred images that can be found in the [test-data/](./test-data/images) folder.

Not all the images can be read. In general changes should hope to increase the number of images that read. However due to the nature of computer vision some changes may cause images that pass to start to fail and visa versa. To update the expected outcomes run `npm run-script generate-test-data`. These outcomes can be evaluated in the context of a PR to determine if a change improves or harms the overall ability of the library to read QR codes.

Expand Down
18 changes: 14 additions & 4 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { Point } from "./locator";
export interface QRCode {
export interface QRInfo {
binaryData: Uint8ClampedArray;
text: string;
encodingType: "numeric" | "alphanumeric" | "byte" | "structured_append" | "eci" | "kanji" | "TODO";
location: {
topRightCorner: Point;
topLeftCorner: Point;
Expand All @@ -15,4 +13,16 @@ export interface QRCode {
};
errorRate: number;
}
export declare function readQR(data: Uint8ClampedArray, width: number, height: number): QRCode | null;
export interface NumericCode extends QRInfo {
data: number;
encodingType: "numeric";
}
export interface AlphaNumericCode extends QRInfo {
encodingType: "alphanumeric" | "kanji" | "TODO";
data: string;
}
export interface BinaryCode extends QRInfo {
encodingType: "byte" | "structured_append" | "eci";
}
export declare type QRCode = NumericCode | AlphaNumericCode | BinaryCode;
export default function x(data: Uint8ClampedArray, width: number, height: number): QRCode | null;
16 changes: 8 additions & 8 deletions dist/jsQR.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
exports["jsQR"] = factory();
else
root["jsQR"] = factory();
})(this, function() {
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
Expand Down Expand Up @@ -128,8 +128,8 @@ function byteArrayToString(bytes) {
}
return str;
}
// TODO - is this the name we want?
function readQR(data, width, height) {
;
function x(data, width, height) {
var binarized = binarizer_1.binarize(data, width, height);
var location = locator_1.locate(binarized);
if (!location) {
Expand All @@ -144,7 +144,7 @@ function readQR(data, width, height) {
return {
binaryData: decoded,
encodingType: "TODO",
text: decodedString,
data: decodedString,
location: {
topRightCorner: extracted.mappingFunction(location.dimension, 0),
topLeftCorner: extracted.mappingFunction(0, 0),
Expand All @@ -158,7 +158,7 @@ function readQR(data, width, height) {
errorRate: 0,
};
}
exports.readQR = readQR;
exports.default = x;


/***/ }),
Expand Down Expand Up @@ -1916,15 +1916,15 @@ function locate(matrix) {
for (var x = -1; x <= matrix.width; x++) {
_loop_2(x);
}
finderPatternQuads.push.apply(finderPatternQuads, activeFinderPatternQuads.filter(function (q) { return q.bottom.y !== y; }));
finderPatternQuads.push.apply(finderPatternQuads, activeFinderPatternQuads.filter(function (q) { return q.bottom.y !== y && q.bottom.y - q.top.y >= 2; }));
activeFinderPatternQuads = activeFinderPatternQuads.filter(function (q) { return q.bottom.y === y; });
alignmentPatternQuads.push.apply(alignmentPatternQuads, activeAlignmentPatternQuads.filter(function (q) { return q.bottom.y !== y; }));
activeAlignmentPatternQuads = activeAlignmentPatternQuads.filter(function (q) { return q.bottom.y === y; });
};
for (var y = 0; y <= matrix.height; y++) {
_loop_1(y);
}
finderPatternQuads.push.apply(finderPatternQuads, activeFinderPatternQuads);
finderPatternQuads.push.apply(finderPatternQuads, activeFinderPatternQuads.filter(function (q) { return q.bottom.y - q.top.y >= 2; }));
alignmentPatternQuads.push.apply(alignmentPatternQuads, activeAlignmentPatternQuads);
var finderPatternGroups = finderPatternQuads
.filter(function (q) { return q.bottom.y - q.top.y >= 2; }) // All quads must be at least 2px tall since the center square is larger than a block
Expand Down Expand Up @@ -2002,5 +2002,5 @@ exports.locate = locate;


/***/ })
/******/ ]);
/******/ ])["default"];
});
20 changes: 15 additions & 5 deletions examples/demo.html → docs/index.html
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
<html>
<head>
<meta charset="utf-8">
<title>jsQR</title>
<script src="../dist/jsQR.js"></script>
<title>jsQR Demo</title>
<script src="./jsQR.js"></script>
<link href="https://fonts.googleapis.com/css?family=Ropa+Sans" rel="stylesheet">
<style>
body {
font-family: 'Ropa Sans', sans-serif;
color: #333;
max-width: 640px;
margin: 0 auto;
position: relative;
}

#githubLink {
position: absolute;
right: 0;
top: 12px;
color: #2D99FF;
}

h1 {
Expand Down Expand Up @@ -45,7 +53,9 @@
</style>
</head>
<body>
<h1>jsQR</h1>
<h1>jsQR Demo</h1>
<a id="githubLink" href="https://github.com/cozmo/jsQR">View documentation on Github</a>
<p>Pure JavaScript QR code decoding library.</p>
<div id="loadingMessage">🎥 Unable to access video stream (please make sure you have a webcam enabled)</div>
<canvas id="canvas" hidden></canvas>
<div id="output" hidden>
Expand Down Expand Up @@ -89,7 +99,7 @@ <h1>jsQR</h1>
canvasElement.width = video.videoWidth;
canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
var imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
var code = jsQR.readQR(imageData.data, imageData.width, imageData.height);
var code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
drawLine(code.location.topLeftCorner, code.location.topRightCorner, "#FF3B58");
drawLine(code.location.topRightCorner, code.location.bottomRightCorner, "#FF3B58");
Expand All @@ -99,7 +109,7 @@ <h1>jsQR</h1>
outputEncoding.parentElement.hidden = false;
outputEncoding.innerText = code.encodingType;
outputData.parentElement.hidden = false;
outputData.innerText = code.text;
outputData.innerText = code.data;
} else {
outputMessage.hidden = false;
outputEncoding.parentElement.hidden = true;
Expand Down
Loading

0 comments on commit 0f218a3

Please sign in to comment.