Code Monkey home page Code Monkey logo

python-zxing's Introduction

python-zxing

PyPI Build Status License: LGPL v3

This is a wrapper for the ZXing barcode library. It will allow you to read and decode barcode images from Python.

It was originally a "slightly less quick-and-dirty" fork of oostendo/python-zxing, but has since evolved considerably beyond that ancestral package.

Dependencies and installation

Use the Python 3 version of pip (usually invoked via pip3) to install: pip3 install zxing

  • You'll neeed to have a recent java binary somewhere in your path. (Tested with OpenJDK v7, v8, v11.)
  • pip will automatically download the relevant JAR files for the Java ZXing libraries (currently v3.5.3)

Usage

The BarCodeReader class is used to decode images:

>>> import zxing
>>> reader = zxing.BarCodeReader()
>>> print(reader.zxing_version, reader.zxing_version_info)
3.5.1 (3, 5, 1)
>>> barcode = reader.decode("test/barcodes/QR_CODE-easy.png")
>>> print(barcode)
BarCode(raw='This should be QR_CODE', parsed='This should be QR_CODE', path='test/barcodes/QR_CODE-easy.png', format='QR_CODE', type='TEXT', points=[(15.0, 87.0), (15.0, 15.0), (87.0, 15.0), (75.0, 75.0)])

The attributes of the decoded BarCode object are raw, parsed, path, format, type, points, and raw_bits. The list of formats which ZXing can decode is here.

The decode() method accepts an image path or PIL Image object (or list thereof) and takes optional parameters try_harder (boolean), possible_formats (list of formats to consider), and pure_barcode (boolean). If no barcode is found, it returns a False-y BarCode object with all fields except path set to None. If it encounters any other recognizable error from the Java ZXing library, it raises BarCodeReaderException.

Command-line interface

The command-line interface can decode images into barcodes and output in either a human-readable or CSV format:

usage: zxing [-h] [-c] [--try-harder] [--pure-barcode] [-V] image [image ...]

Human-readable:

$ zxing /tmp/barcode.png
/tmp/barcode.png
================
  Decoded TEXT barcode in QR_CODE format.
  Raw text:    'Testing 123'
  Parsed text: 'Testing 123'

CSV output (can be opened by LibreOffice or Excel):

$ zxing /tmp/barcode1.png /tmp/barcode2.png /tmp/barcode3.png
Filename,Format,Type,Raw,Parsed
/tmp/barcode1.png,CODE_128,TEXT,Testing 123,Testing 123
/tmp/barcode2.png,QR_CODE,URI,http://zxing.org,http://zxing.org
/tmp/barcode3.png,QR_CODE,TEXT,"This text, ""Has stuff in it!"" Wow⏎Yes it does!","This text, ""Has stuff in it!"" Wow⏎Yes it does!"

License

LGPLv3

python-zxing's People

Contributors

ankita-kumari avatar dlenski avatar graingert avatar hjernefrys avatar lemmarathon avatar manouchehri avatar muued avatar oostendo avatar scdor avatar shatterhand19 avatar vladvrabie 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

python-zxing's Issues

Insufficient handling of missing result in BarCode.__repr__

When there is no result for a file, id est we have the standard output

file:///home/stefan/temp/image-001.png: No barcode found

then displaying the result will fail as BarCode.__repr__ does not like it:

Traceback (most recent call last):
  File "/home/stefan/temp/run.py", line 57, in <module>
    print(reader.decode(path))
  File "/home/stefan/temp/venv/lib/python3.9/site-packages/zxing/__init__.py", line 238, in __repr__
    self.__class__.__name__, self.raw, self.parsed, self.raw_bits.hex(),
AttributeError: 'NoneType' object has no attribute 'hex'

Java binary specified does not exist

I use "pip install zxing" to install zxing 0.11,and in my venv dir have all the file demand,“core.jar”“javase.jar”“jcommander.jar”,but when run zxing.BarCodeReader().decode(xxx.png) raise error :

"raise BarCodeReaderException("Java binary specified does not exist", self.java, e) zxing.BarCodeReaderException: ('Java binary specified does not exist', 'java', FileNotFoundError(2, '系统找不到指定的文件。', None, 2, None))"

[WinError 2] The system cannot find the file specified

Tried implmenting it on a windows platform.Found this error after following the error

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-14-57bf31b8a763> in <module>
----> 1 text = reader.decode("ad1.jpg")

~\AppData\Local\Continuum\anaconda3\lib\site-packages\zxing\__init__.py in decode(self, filename, try_harder, possible_formats)
     35                 cmd += ['--possible_formats', pf ]
     36 
---> 37         p = sp.Popen(cmd, stdout=sp.PIPE, universal_newlines=False)
     38         stdout, stderr = p.communicate()
     39 

~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    773                                 c2pread, c2pwrite,
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:
    777             # Cleanup if the child failed starting.

~\AppData\Local\Continuum\anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
   1176                                          env,
   1177                                          os.fspath(cwd) if cwd is not None else None,
-> 1178                                          startupinfo)
   1179             finally:
   1180                 # Child is launched. Close the parent's copy of those pipe

FileNotFoundError: [WinError 2] The system cannot find the file specified

data matrix generator

Do you have an example of how to generate a data matrix and control image height and width (number of pixels)?

Install fails on Windows

Installing zxing on Windows results in the following error:

❯ pip install .\python-zxing-1.0.2
Processing python-zxing-1.0.2
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [10 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "python-zxing-1.0.2\setup.py", line 49, in <module>
          long_description=open('README.md').read(),
                           ^^^^^^^^^^^^^^^^^^^^^^^^
        File "C:\Users\lemmarathon\scoop\apps\python\3.12.2\Lib\encodings\cp1252.py", line 23, in decode
          return codecs.charmap_decode(input,self.errors,decoding_table)[0]
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 3118: character maps to <undefined>
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

Command-line interface

Hi may I ask how to install the Command-line interface?(for Linux) The package is otherwise working fine in Python 3.5. Thank you.

Cannot install from tarball

I tried installing the package using PEP 508 direct reference specifications in my setup.py:

install_requires=[ 'zxing @ [git+]https://github.com/dlenski/python-zxing/tarball/master', ]

and I get 2 exceptions:

subprocess.CalledProcessError: Command '['git', 'describe', '--tags', '--dirty=_dirty']' returned non-zero exit status 128.

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-sjxlzlyf\\zxing\\zxing\\version.py'

The problem is here:

python-zxing/setup.py

Lines 23 to 35 in 5bc2e3f

try:
version_git = sp.check_output(["git", "describe", "--tags", "--dirty=_dirty"]).strip().decode('ascii')
final, dev, blob, dirty = re.match(r'v?((?:\d+\.)*\d+)(?:-(\d+)-(g[a-z0-9]+))?(_dirty)?', version_git).groups()
version_pep = final+('.dev%s+%s'%(dev,blob) if dev else '')+(dirty if dirty else '')
except:
d = {}
with open(version_py, 'r') as fh:
exec(fh.read(), d)
version_pep = d['__version__']
else:
with open(version_py, 'w') as fh:
print("# Do not edit this file, versioning is governed by git tags", file=fh)
print('__version__="%s"' % version_pep, file=fh)

The try fails because the tarball does not contain a .git folder.
So in the exception you assume there is a local zxing/version.py file to read, but there isn't (because you have it in the .gitignore).

Possible solution: check if the file zxing/version.py exists or not

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

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?

Can't install ZXing - FileNotFoundError "requirements.txt"

Hello there

I am trying to install ZXing on Python 3.10.6 and it fails on a Sub-Process when trying to get requirements to build the wheel:

"FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt'"

Not quite sure what the Problem is in this case, or what I can do to fix it.
I have OpenJDK 21.0.2 installed via Brew

read multiple barcodes?

It seems that the library can only detect one barcode?

The pyzxing can read multiple barcodes but it is too slow as it runs java -jar every time.

I don't know what the problem is

zxing: error: Unknown Java exception: b'Exception in thread "main" java.lang.IllegalArgumentException: URI path component is empty\r\n\tat sun.nio.fs.WindowsUriSupport.fromUri(Unknown Source)\r\n\tat sun.nio.fs.WindowsFileSystemProvider.getPath(Unknown Source)\r\n\tat java.nio.file.Paths.get(Unknown Source)\r\n\tat com.google.zxing.client.j2se.CommandLineRunner.expand(CommandLineRunner.java:112)\r\n\tat com.google.zxing.client.j2se.CommandLineRunner.main(CommandLineRunner.java:76)\r\n'

Issues in decoding PDF 417 format Barcodes

I am trying to use zxing to decode PDF417 images. However Im getting an error message as follows:

ValueError: Unknown format code 'x' for object of type 'str'

Error seems to be in the __repr__ of the BarCode Class

Here is the File i'm using

Can I understand if there is any workaround for the same?

Different results from online decoder

Thank you for making this library.

I have a collection of barcodes that mostly fail to decode with the python wrapper, but that are successfully decoded using the online ZXing resource here: https://zxing.org/w/decode.jspx. Do you have any insights on what options the online decoder might be using, or how this might differ from your wrapper? Happy to share data privately.

ZXing does not decode some QR images

###Bug Reports
I am using zxing module of python to decode QR images like attached below. But it returns empty string.

image
Image link is 1, 2.
I am using code like below-

from zxing import BarCodeReader
fpath = r"14767.png"
reader = BarCodeReader()
qrcode = reader.decode(fpath)
print(qrcode.raw)

Why it is returning empty string?

utf-8 codec decoding error

Hello,

I'm running a simple test, trying to read an PDF417 bar code. I'm getting this error:

... zxing_init_.py", line 159, in parse
raw = raw[:-1].decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 171: invalid start byte

Here is my code:

import zxing
reader = zxing.BarCodeReader()
barcode = reader.decode("pdf417_bin.png", possible_formats=['PDF_417'], try_harder=True)
print(barcode)

And here is the image to decode:

image

I used the zxing online decoder https://zxing.org/w/decode.jspx and it works fine, so I want to know if I'm doing something wrong or it is a bug.

image

Thanks,

raw and parsed decode compatibility with ZXing

This is probably related to issue #6 and tangentially related to issue #8 ; it might also just be closed with statement on the use case/spec compatibility of this wrapper with ZXing.

With ZXing, the default outputs of the raw stream are hex bytes while the parsed/text appears to defaul to just Java String (UTF-16). However, the python-zxing wrapper has these two lines in __init__.py/Barcode:

raw = raw[:-1].decode()
parsed = parsed[:-1].decode()

which force UTF-8 compatibility of the raw and parsed streams. This causes UnicodeDecodeError exceptions with any byte sequences that begin with bytes "larger" than b"\x7f" with which ZXing doesn't appear to have any problems. Just commenting out '.decode()' in each of these lines, I am able to reproduce ZXing results for byte data in both raw and parsed.

My question: is there a reason the '.decode()' or UTF-8 is even necessary for either raw or parsed or is the use case for this wrapper intended to be for UTF-8 compatible QR codes only?

Use jpype for wrapper?

I have been once creating a wrapper with jpype to zxing.
The great thing would be that we avoid parsing issues.

It also allows you to get the metadata from the zxing barcode Object, eg for PDF_417 barcode.

It would simplify the problem a lot but require jpype as well.

You can also keep the java runtime warm and rerun things on demand with single requests.

Using jPype one can just use the main lines from CommandLineRunner of zxing.

Any thoughts on that?

what's the difference between raw and parsed results?

i got the result
BarCode(raw='This should be QR_CODE', parsed='This should be QR_CODE', format='QR_CODE', type='TEXT', points=[(15.0, 87.0), (15.0, 15.0), (87.0, 15.0), (75.0, 75.0)]),
but the row's content the same with the parsed's content.
i don't know the difference.
could you explain the meanings of the raw and the parsed?give an example is best.

Fails when passing pathlib.Path object

Passing a pathlib.Path object as the filenames parameter raises some error:

Traceback (most recent call last):
  File "/home/stefan/temp/run.py", line 57, in <module>
    print(reader.decode(path))
  File "/home/stefan/temp/venv/lib/python3.9/site-packages/zxing/__init__.py", line 80, in decode
    for fn_or_im in filenames:
TypeError: 'PosixPath' object is not iterable

if isinstance(filenames, (str, IOBase, Image) if have_pil else (str, IOBase)):
one_file = True
filenames = filenames,
else:
one_file = False
seems to be incomplete and probably should check for the inverse, id est for known iterables.

UnboundLocalError: local variable 'bc' referenced before assignment

Hello,

I have installed zxing through pip. this version is installed:

$zxing -V
zxing v1.0
using Java ZXing library version v3.5.1

I have different output running the command from ssh and from graphical....
If I run the command in gnome-terminal I get this output:

$zxing /alb0001.tiff 
/alb0001.tiff
=============
Traceback (most recent call last):
  File "/home/user/.local/bin/zxing", line 8, in <module>
    sys.exit(main())
  File "/home/user/.local/lib/python3.9/site-packages/zxing/__main__.py", line 59, in main
    if not bc:
UnboundLocalError: local variable 'bc' referenced before assignment

but running the same command from ssh on another server, or even running ssh in same server with 127.0.0.1 ( and even in the same gnome-terminal that was not working previously ) is working....

$ssh [email protected] 'zxing /alb0001.tiff'
[email protected]'s password: 
/alb0001.tiff
=============
  Decoded TEXT barcode in PDF_417 format.
  Raw text:    '1234|000'
  Parsed text: '1234|000'

Host is almalinux 9.

Is there anything I can do to get the command running from a graphical terminal?

utf-8 encoding problem, ???????? instead of Thai letters

Hi, I have a problem detecting qrcode which contains Thai characters. Example below:

qr code decoded by zxing wrapper: "ABCC051 ?????????????????????????"
qr code decoded by zbar wrapper: "ABCC051 เอกสารประกอบการขอสินเชื่อ"

Could you please recommend me a way to fix this issue?

Best regards and thank you

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.