Read barcode in python

pyzbar 0.1.9

Read one-dimensional barcodes and QR codes from Python 2 and 3.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License (MIT)

Сопровождающие

Классификаторы

Описание проекта

Read one-dimensional barcodes and QR codes from Python 2 and 3 using the zbar library.

  • Pure python
  • Works with PIL / Pillow images, OpenCV / imageio / numpy ndarray s, and raw bytes
  • Decodes locations of barcodes
  • No dependencies, other than the zbar library itself
  • Tested on Python 2.7, and Python 3.5 to 3.10

The older zbar package is stuck in Python 2.x-land. The zbarlight package does not provide support for Windows and depends upon Pillow.

Installation

The zbar DLLs are included with the Windows Python wheels. On other operating systems, you will need to install the zbar shared library.

sudo apt-get install libzbar0

Install this Python wrapper; use the second form to install dependencies of the command-line scripts:

pip install pyzbar pip install pyzbar[scripts]

Example usage

The decode function accepts instances of PIL.Image .

>>> from pyzbar.pyzbar import decode >>> from PIL import Image >>> decode(Image.open('pyzbar/tests/code128.png')) [ Decoded( data=b'Foramenifera', type='CODE128', rect=Rect(left=37, top=550, width=324, height=76), polygon=[ Point(x=37, y=551), Point(x=37, y=625), Point(x=361, y=626), Point(x=361, y=550) ], orientation="UP", quality=77 ) Decoded( data=b'Rana temporaria', type='CODE128', rect=Rect(left=4, top=0, width=390, height=76), polygon=[ Point(x=4, y=1), Point(x=4, y=75), Point(x=394, y=76), Point(x=394, y=0) ], orientation="UP", quality=77 ) ]

It also accepts instances of numpy.ndarray , which might come from loading images using OpenCV.

>>> import cv2 >>> decode(cv2.imread('pyzbar/tests/code128.png')) [ Decoded( data=b'Foramenifera', type='CODE128', rect=Rect(left=37, top=550, width=324, height=76), polygon=[ Point(x=37, y=551), Point(x=37, y=625), Point(x=361, y=626), Point(x=361, y=550) ], orientation="UP", quality=77 ) Decoded( data=b'Rana temporaria', type='CODE128', rect=Rect(left=4, top=0, width=390, height=76), polygon=[ Point(x=4, y=1), Point(x=4, y=75), Point(x=394, y=76), Point(x=394, y=0) ], orientation="UP", quality=77 ) ]

You can also provide a tuple (pixels, width, height) , where the image data is eight bits-per-pixel.

>>> image = cv2.imread('pyzbar/tests/code128.png') >>> height, width = image.shape[:2] >>> # 8 bpp by considering just the blue channel >>> decode((image[:, :, 0].astype('uint8').tobytes(), width, height)) [ Decoded( data=b'Foramenifera', type='CODE128', rect=Rect(left=37, top=550, width=324, height=76), polygon=[ Point(x=37, y=551), Point(x=37, y=625), Point(x=361, y=626), Point(x=361, y=550) ], orientation="UP", quality=77 ) Decoded( data=b'Rana temporaria', type='CODE128', rect=Rect(left=4, top=0, width=390, height=76), polygon=[ Point(x=4, y=1), Point(x=4, y=75), Point(x=394, y=76), Point(x=394, y=0) ], orientation="UP", quality=77 ) ] >>> # 8 bpp by converting image to greyscale >>> grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) >>> decode((grey.tobytes(), width, height)) [ Decoded( data=b'Foramenifera', type='CODE128', rect=Rect(left=37, top=550, width=324, height=76), polygon=[ Point(x=37, y=551), Point(x=37, y=625), Point(x=361, y=626), Point(x=361, y=550) ], orientation="UP", quality=77 ) Decoded( data=b'Rana temporaria', type='CODE128', rect=Rect(left=4, top=0, width=390, height=76), polygon=[ Point(x=4, y=1), Point(x=4, y=75), Point(x=394, y=76), Point(x=394, y=0) ], orientation="UP", quality=77 ) ] >>> # If you don't provide 8 bpp >>> decode((image.tobytes(), width, height)) Traceback (most recent call last): File "", line 1, in File "/Users/lawh/projects/pyzbar/pyzbar/pyzbar.py", line 102, in decode raise PyZbarError('Unsupported bits-per-pixel []'.format(bpp)) pyzbar.pyzbar_error.PyZbarError: Unsupported bits-per-pixel [24]

The default behaviour is to decode all symbol types. You can look for just your symbol types

>>> from pyzbar.pyzbar import ZBarSymbol >>> # Look for just qrcode >>> decode(Image.open('pyzbar/tests/qrcode.png'), symbols=[ZBarSymbol.QRCODE]) [ Decoded( data=b'Thalassiodracon', type='QRCODE', rect=Rect(left=27, top=27, width=145, height=145), polygon=[ Point(x=27, y=27), Point(x=27, y=172), Point(x=172, y=172), Point(x=172, y=27) ], orientation="UP", quality=1 ) ] >>> # If we look for just code128, the qrcodes in the image will not be detected >>> decode(Image.open('pyzbar/tests/qrcode.png'), symbols=[ZBarSymbol.CODE128]) []

ZBar versions

Development of the original zbar stopped in 2012. Development was started again in 2019 under a new project that has added some new features, including support for decoding barcode orientation. At the time of writing this new project does not produce Windows DLLs. The zbar DLLs that are included with the Windows Python wheels are built from the original project and so do not include support for decoding barcode orientation. If you see orientation=None then your system has an older release of zbar that does not support orientation.

Читайте также:  Php заменить все кавычки

Quality field

From zbar.h, the quality field is

…an unscaled, relative quantity: larger values are better than smaller values, where “large” and “small” are application dependent. Expect the exact definition of this quantity to change as the metric is refined. currently, only the ordered relationship between two values is defined and will remain stable in the future

Bounding boxes and polygons

The blue and pink boxes show rect and polygon , respectively, for barcodes in pyzbar/tests/qrcode.png (see bounding_box_and_polygon.py).

Two barcodes with bounding boxes and polygons

Windows error message

If you see an ugly ImportError when importing pyzbar on Windows you will most likely need the Visual C++ Redistributable Packages for Visual Studio 2013. Install vcredist_x64.exe if using 64-bit Python, vcredist_x86.exe if using 32-bit Python.

Contributors

  • Alex (@globophobe) — first implementation of barcode locations
  • Dmytro Ferens (@dferens) — barcode orientation
  • Ismail Bento (@isman7) — support for images loaded using imageio
  • @jaant — read barcodes containing null characters

License

pyzbar is distributed under the MIT license (see LICENCE.txt ). The zbar shared library is distributed under the GNU Lesser General Public License, version 2.1

Источник

Detect and read barcodes with OpenCV in Python

This article describes how to detect and read barcodes with OpenCV in Python.

  • cv2.barcode is included in the OpenCV contrib module
  • Super Resolution Model
  • Detect and read barcodes from an image
  • Detect and read barcodes from camera video

See the following article on how to detect and read QR codes instead of barcodes.

You can also use ZBar (pyzbar). Although not thoroughly verified, ZBar seems to have better detection accuracy.

Читайте также:  Html choose file button

The version of OpenCV used in the sample code is 4.6.0 .

import cv2 print(cv2.__version__) # 4.6.0 

cv2.barcode is included in the OpenCV contrib module

The cv2.barcode to detect and read barcodes is included in the contrib module (as of version 4.6.0 ).

In the output of cv2.getBuildInformation() , barcode must be included in To be built of OpenCV modules .

For example, on macOS, if you installed OpenCV with Homebrew, the contrib module should be included, but if you installed opencv-python with pip , it might not be included. You need to install OpenCV with pip install opencv-contrib-python .

Super Resolution Model

The official tutorial introduces the Super Resolution Model.

You can download and use sr.prototxt , sr.caffemodel from the following repository.

Specify the path of the downloaded file to cv2.barcode.BarcodeDetector() . If omitted, no model is used.

bd = cv2.barcode.BarcodeDetector('/path/to/sr.prototxt', '/path/to/sr.caffemodel') 

I may be doing something wrong, but I did not notice any difference in accuracy with or without the model in my environment. It is not used in the sample code below.

Detect and read barcodes from an image

The following barcode image is used as an example.

img = cv2.imread('data/src/barcode.jpg') 

Barcode sample

Create an instance of cv2.barcode.BarcodeDetector and execute detectAndDecode() . Although detect() to only detect and decode() to decode based on the detected coordinates are also provided, they are not mentioned here.

Note that the results may differ depending on the version and environment.

bd = cv2.barcode.BarcodeDetector() # bd = cv2.barcode.BarcodeDetector('path/to/sr.prototxt', 'path/to/sr.caffemodel') retval, decoded_info, decoded_type, points = bd.detectAndDecode(img) 

retval is True if a barcode is detected and False if none is detected.

Читайте также:  Other error in php

decoded_info is a tuple whose elements are strings stored in barcodes. If it can be detected but not decoded, it is an empty string » .

print(decoded_info) # ('1923055034006', '9784873117980') 

decoded_type is a tuple whose elements are numbers representing barcode types.

print(decoded_type) # (2, 2) print(cv2.barcode.EAN_13) # 2 

points is a numpy.ndarray representing the coordinates of the four corners of the detected QR Code.

print(type(points)) # print(points) # [[[142.38849 221.83641] # [156.36218 172.35411] # [356.90564 228.98714] # [342.93195 278.46942]] # # [[180.30583 128.89304] # [191.59013 88.83808] # [371.00458 139.38284] # [359.72028 179.4378 ]]] print(points.shape) # (2, 4, 2) 

Draw frames for the detected barcode and superimpose the decoded text.

img = cv2.polylines(img, points.astype(int), True, (0, 255, 0), 3) for s, p in zip(decoded_info, points): img = cv2.putText(img, s, p[1].astype(int), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1, cv2.LINE_AA) cv2.imwrite('data/dst/barcode_opencv.jpg', img) 

Detect and decode barcode with OpenCV

Detect and read barcodes from camera video

The following is a sample code that detects and reads barcodes from real-time camera video.

See the following article for more information on the handling of videos in OpenCV.

Press q on the keyboard to exit.

import cv2 camera_id = 0 delay = 1 window_name = 'OpenCV Barcode' bd = cv2.barcode.BarcodeDetector() cap = cv2.VideoCapture(camera_id) while True: ret, frame = cap.read() if ret: ret_bc, decoded_info, _, points = bd.detectAndDecode(frame) if ret_bc: frame = cv2.polylines(frame, points.astype(int), True, (0, 255, 0), 3) for s, p in zip(decoded_info, points): if s: print(s) frame = cv2.putText(frame, s, p[1].astype(int), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 2, cv2.LINE_AA) cv2.imshow(window_name, frame) if cv2.waitKey(delay) & 0xFF == ord('q'): break cv2.destroyWindow(window_name) 

In an actual application, the while loop would be terminated by break when the decoded_info string is obtained, and the application would move on to operation using the string.

Источник

Оцените статью