dlenski / python-zxing

python wrapper for the ZXing barcode library
GNU Lesser General Public License v3.0
121 stars 36 forks source link

How to input image array instead of filename to read QR code? #21

Closed ThurgaShri closed 2 years ago

ThurgaShri commented 2 years ago

How can I pass an image array to BarcodeReader instead of the filename?

reader = zxing.BarCodeReader()
barcode = reader.decode('image.jpg')

to

cv_image = cv2.imread('image.jpg')
reader = zxing.BarCodeReader()
barcode = reader.decode(cv_image)

Is there any function to do this?

dlenski commented 2 years ago

Is there any function to do this?

Not presently, but the module could easily be extended to do it using a NamedTemporaryFile.

ThurgaShri commented 2 years ago

Yea thanks, got it working by saving it in a temp dir.

img = cv2.imread('image.jpg')
imgOutput = #do something

with tempfile.TemporaryDirectory() as tmpdir:
       cv2.imwrite(tmpdir+'/1.jpg', imgOutput)
       files_in_dir = os.listdir(tmpdir)

       ## Image from temp dir
       reader = zxing.BarCodeReader()
       barcode = reader.decode(tmpdir+'/'+files_in_dir[0])
dlenski commented 2 years ago

Yea thanks, got it working by saving it in a temp dir.

Note that your version may be quite slow, because writing as a JPEG involves unnecessary (re)compression, and may be lossy causing some images no longer to work.

What I was suggesting is modifying python-zxing itself to make this a built-in capability. :upside_down_face:

You didn't specify in your original issue what image library you were using… so I assumed PIL Image class, which is very commonly used in Python modules that manipulate images.. I went ahead and Just Did It, so now zxing.BarCodeReader will accept the PIL Image class. See 81f55d3e8666ae42178f579353704f8526cd4200

If you want to extend this to work for the OpenCV format, it should be quite easy.