cozmo / jsQR

A pure javascript QR code reading library. This library takes in raw images and will locate, extract and parse any QR code found within.
https://cozmo.github.io/jsQR/
Apache License 2.0
3.64k stars 602 forks source link

Restrict search bounds? #168

Open eventualbuddha opened 4 years ago

eventualbuddha commented 4 years ago

Rather than requiring a new cropped image, it would be nice if I could specify the search bounds if I have a larger image but I know roughly where the QR code should be. Is this a feature you'd consider? If so, I may have time to make a PR for it.

cozmo commented 4 years ago

Hey! I'm of 2 minds here. On one hand, I think the API of taking in an image and returning any found QR codes is the simplest, and cropping an image doesn't really feel like it's the job of jsQR, and should be as relatively simple to do, something like:

function crop(originalImageData: Uint8ClampedArray, originalWidth: number, originalHeight: Number, topLeft: Point, bottomRight: Point) {
  const newWidth = bottomRight.x - topLeft.x;
  const newHeight = bottomRight.y - topLeft.y;

  const croppedImageData = new Uint8ClampedArray(newWidth * newHeight * 4);

  for (let y = 0; y < newHeight; y++) {
    const stride = originalImageData.subarray(
      (((y + topLeft.y) * originalWidth + topLeft.x) * 4) + 0, // start of the stride in the original image coordinates
      (((y + topLeft.y) * originalWidth + topLeft.x + newWidth) * 4) + 4 // end of the stride in the original image coordinates
    )
    croppedImageData.set(stride, y * newWidth);
  }
  return croppedImageData;
}

Which would allow for cropping the image with N memory reads/writes, where N is the height of the new image.

That said, this code is probably more complex than would be expected for most consumers to write correctly, especially in an efficient manner, and I think we can actually do better in jsQR. By changing binarizer here we can basically just look at the part of the image we care about, without doing any additional reads/writes/initializations.

As such, I'm open to putting it into jsQR, but I'm probably won't prioritize it myself. If you were to make a PR I'd be happy to accept it.