Reading Bar Codes with the Raspberry Pi
Installation
Install OpenCVsudo apt get install python-opencv libopencv-dev
You might find it is already installed.
Install Python bindings
pip3 install opencv-pythonInstall additional libraries
sudo apt-get install libcblas-devsudo apt-get install libhdf5-dev -y
&& sudo apt-get install libhdf5-serial-dev -y
&& sudo apt-get install libatlas-base-dev -y
&& sudo apt-get install libjasper-dev -y
&& sudo apt-get install libqtgui4 -y
&& sudo apt-get install libqt4-test -y
Install ZBAR and PYZBAR
According to one of the references, zbar does not have a python3 version, however the pyzbar works with Python3.sudo apt-get install libzbar0
pip3 install pyzbar
Remember to use pip3 not pip to install pyzbar for Python3 (your installation may vary - pip defaults to Python2 in most installations).
Test program
from pyzbar import pyzbar
import cv2
imagefile="/home/pi/Documents/Python/barcodetest.jpg"
print(imagefile)
# load the input image
image = cv2.imread(imagefile)
# find the barcodes in the image and decode each of the barcodes
barcodes = pyzbar.decode(image)
# loop over the detected barcodes
for barcode in barcodes:
# extract the bounding box location of the barcode and draw the
# bounding box surrounding the barcode on the image
(x, y, w, h) = barcode.rect
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
# the barcode data is a bytes object so if we want to draw it on
# our output image we need to convert it to a string first
barcodeData = barcode.data.decode("utf-8")
barcodeType = barcode.type
# draw the barcode data and barcode type on the image
text = "{} ({})".format(barcodeData, barcodeType)
cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0, 0, 255), 2)
# print the barcode type and data to the terminal
print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))
# show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)
Troubleshooting
There may be issues with the version of numpy installed by the above.
If you getr an import error, remove the installed version of numpy and replace it with one from the Raspbian repository.
pip3 uninstall numpy # remove previously installed version
apt install python3-numpy
https://numpy.org/devdocs/user/troubleshooting-importerror.html
References
https://www.pyimagesearch.com/2018/05/21/an-opencv-barcode-and-qr-code-scanner-with-zbar/https://www.learnopencv.com/barcode-and-qr-code-scanner-using-zbar-and-opencv/
https://www.raspberrypi.org/forums/viewtopic.php?p=848265
https://stackoverflow.com/questions/19876079/cannot-find-module-cv2-when-using-opencv