By reading this piece, you will learn about the tips and tricks to generate one-dimensional barcodes in different formats as well as Quick Response code (QR Code) generation. Besides, this tutorial will outline the methods to decode both the barcode and QR Code using the same Python library. Previously, I have covered a tutorial on How to Generate and Decode QR Codes in Python which used OpenCV to decode QR Codes. In this tutorial, I will be using another module called pyzbar for decoding instead. Based on the official documentation, pyzbar is
通过阅读本文,您将了解生成不同格式的一维条形码以及快速响应代码(QR Code)生成的提示和技巧。 此外,本教程还将概述使用同一Python库对条形码和QR码进行解码的方法。 之前,我介绍了有关如何使用Python生成和解码QR码的教程,该教程使用OpenCV解码QR码。 在本教程中,我将使用另一个名为pyzbar模块进行解码。 根据官方文档, pyzbar是
“… a pure Python library that reads one-dimensional barcodes and QR codes using the zbar library, an open source software suite for reading bar codes from various sources, such as video streams, image files and raw intensity sensors. It supports many popular symbologies (types of bar codes) including EAN-13/UPC-A, UPC-E, EAN-8, Code 128, Code 39, Interleaved 2 of 5 and QR Code.”
“…一个纯Python库,它使用zbar库读取一维条形码和QR码, zbar库是一种开放源代码软件套件,可从各种来源(例如视频流,图像文件和原始强度传感器)读取条形码。 它支持许多流行的符号体系(条形码的类型),包括EAN-13 / UPC-A,UPC-E,EAN-8,Code 128,Code 39,Interleaved 2 of 5和QR Code。”
Based on the experiments that I have conducted, pyzbar performs better compared to python-opencv in terms of accuracy when decoding QR Codes. On top of that, pyzbar is able to decode barcodes as well.
根据我进行的实验, pyzbar在解码QR码时的准确性优于python-opencv 。 最重要的是, pyzbar也能够解码条形码。
Let’s proceed to the next section and start installing the necessary modules.
让我们继续下一节并开始安装必要的模块。
It is highly recommended to setup a virtual environment before you continue with the installation. You can easily install all the modules via pip install.
强烈建议您在继续安装之前先设置虚拟环境。 您可以通过pip install轻松安装所有模块。
Our first module is the python-barcode package which helps to generate one-dimensional barcodes based on the formats that we have specified. Run the following command to install it
我们的第一个模块是python-barcode程序包,该程序包有助于根据我们指定的格式生成一维条形码。 运行以下命令进行安装
pip install python-barcodeBy default, result will be exported as SVG. You need to install additional dependencies such as Pillow. You can choose to install the dependencies independently or together with python-barcode as follows:
默认情况下,结果将导出为SVG。 您需要安装其他依赖项,例如Pillow 。 您可以选择独立安装依赖项,也可以与python-barcode一起安装,如下所示:
pip install python-barcode[images]You can install qrcode package individually via the following command
您可以通过以下命令单独安装qrcode软件包
pip install qrcodeOptionally, you can include the Pillow dependencies together with the standard installation as well
(可选)您还可以将Pillow依赖项与标准安装一起包括在内
pip install qrcode[pil]Installation for pyzbar is slightly complicated and depends on the operating system of your machine. For Windows user, zbar DLL comes together with the Windows Python wheels.
pyzbar安装有些复杂,并且取决于计算机的操作系统。 对于Windows用户, zbar DLL与Windows Python轮子一起提供。
For Mac OS X, you can install the zbar shared library via the following command
对于Mac OS X,您可以通过以下命令安装zbar共享库
brew install zbarThe following command should be used if you are using Linux.
如果使用Linux,则应使用以下命令。
sudo apt-get install libzbar0Once you are done with it, run the following command to install pyzbar Python package.
完成后,运行以下命令安装pyzbar Python软件包。
pip install pyzbarIn fact, it also support command-line functionality which allows you to run it directly in command line. To do so, you should install it as follows:
实际上,它还支持命令行功能,使您可以直接在命令行中运行它。 为此,您应该按以下方式安装它:
pip install pyzbar[scripts]In this section, we are going to generate barcodes using the python-barcode package.
在本节中,我们将使用python-barcode包生成条形码。
At the time of this writing, this package supports the following formats:
在撰写本文时,此软件包支持以下格式:
EAN-8 EAN-8 EAN-13 EAN-13 EAN-14 EAN-14 UPC-A UPC-A JAN 一月 ISBN-10书号10ISBN-13 书号13 ISSN ISSN Code 39 代码39 Code 128 代码128 PZN PZNI am going to generate a new barcode using the EAN13 format. The result will be in PNG format.
我将使用EAN13格式生成一个新的条形码。 结果将为PNG格式。
Let’s add the following import statement. ImageWriter is needed if you are saving the results as images. Otherwise, it will be defaulted to SVG.
让我们添加以下导入语句。 如果ImageWriter结果另存为图像,则需要ImageWriter 。 否则,它将默认为SVG。
from barcode import EAN13from barcode.writer import ImageWriterContinue appending the following code below it. Since we are writing an image, you need to specify the filemode as wb. For your information, EAN13 accepts a string which contains 12 digits instead of 13. The last digit is a checksum and will be generated automatically. If your input is a 13 digits string, the last digit will be ignored.
继续在其下面附加以下代码。 由于我们正在写入图像,因此需要将文件模式指定为wb 。 仅供参考,EAN13接受一个包含12个数字而不是13个数字的字符串。最后一个数字是校验和,将自动生成。 如果您输入的是13位数字的字符串,则最后一位数字将被忽略。
with open('barcode.png', 'wb') as f: EAN13('123456789102', writer=ImageWriter()).write(f)The complete code snippet is as follows:
完整的代码段如下:
from barcode import EAN13 from barcode.writer import ImageWriter with open('barcode.png', 'wb') as f: EAN13('123456789102', writer=ImageWriter()).write(f)It should generate the following image when you run the Python file.
运行Python文件时,它将生成以下图像。
Image by Author 图片作者Generation of QR Code is slightly complicated compared to barcode due to the fact that QR Code is 2-dimensional.
由于QR码是二维的,因此与条形码相比,QR Code的生成稍微复杂一些。
Add the following import statement
添加以下导入语句
import qrcodefrom PIL import ImageCreate an instance of QRCode object with the following parameters
使用以下参数创建QRCode对象的实例
qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=10, border=4,)version — Control the size of the QR Code. It accepts an integer from 1 to 40. Version 1 consists of 21 x 21 matrix.
version —控制QR码的大小。 它接受从1到40的整数。版本1由21 x 21矩阵组成。
error_correction — Control the error correction used for the QR Code.
error_correction —控制用于QR码的错误校正。
box_size — Control the number of pixels of each boxes of the QR code.
box_size —控制QR码每个框的像素数。
border — Control the boxes thickness of the border. The default is value is 4 which is also the minimum value according to the specification.
border —控制框的边框粗细。 默认值为4,这也是根据规范的最小值。
There are 4 constants available for error_correction. The higher errors can be corrected, the better it is.
有4个常量可用于error_correction 。 可以纠正的错误越高,越好。
ERROR_CORRECT_L — About 7% or less errors can be corrected.
ERROR_CORRECT_L可以纠正大约7%或更少的错误。
ERROR_CORRECT_M — About 15% or less errors can be corrected. This is the default value.
ERROR_CORRECT_M可以纠正大约15%或更少的错误。 这是默认值。
ERROR_CORRECT_Q — About 25% or less errors can be corrected.
ERROR_CORRECT_Q可以纠正大约25%或更少的错误。
ERROR_CORRECT_H — About 30% or less errors can be corrected.
ERROR_CORRECT_H可以纠正大约30%或更少的错误。
Continue appending the following code snippet below it. Replace the input parameter for add_data based on your own use cases.
继续在其下面附加以下代码段。 根据您自己的用例替换add_data的输入参数。
qr.add_data("https://medium.com/@ngwaifoong92")qr.make(fit=True)img = qr.make_image(fill_color="black", back_color="white")img.save("qrcode.png")You can find the complete code in the following gist.
您可以在以下要点中找到完整的代码。
import qrcode from PIL import Image qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=10, border=4, ) qr.add_data("https://medium.com/@ngwaifoong92") qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") img.save("qrcode.png")You should get a QR Code once you ran the code. In my case, it looks like this.
运行代码后,您应该会获得一个QR码。 就我而言,它看起来像这样。
Image by Author 图片作者Once you are done with it, proceed to the next section and start implementing our decoder.
完成后,请继续下一节并开始实现我们的解码器。
One main feature of pyzbar is that decoding is done directly using the same function. In addition, it supports decoding multiple barcodes or QR Codes in a single image. Import the decode() function from the module as follows:
pyzbar主要功能之一是使用相同的功能直接进行解码。 此外,它支持在单个图像中解码多个条形码或QR码。 从模块导入decode()函数,如下所示:
from pyzbar.pyzbar import decodeYou can pass either an instance of PIL.Image or an instance of numpy.ndarray. You can easily load an image into numpy.ndarry using OpenCV. For loading with PIL, use the following code
您可以传递PIL.Image实例或numpy.ndarray实例。 您可以使用OpenCV轻松地将图像加载到numpy.ndarry中。 要使用PIL加载,请使用以下代码
from PIL import Imageimg = Image.open('qrcode.png')Here is an example of how you can load your image using OpenCV.
这是如何使用OpenCV加载图像的示例。
import cv2img = cv2.imread('qrcode.png')Append the following code below it. It will print out the results as strings.
在其下面附加以下代码。 它将结果打印为字符串。
result = decode(img)decode() function returns a list of namedtuple called Decoded. Each of them contains the following fields:
decode()函数返回一个名为Decoded的namedtuple列表。 它们每个都包含以下字段:
data — The decoded string in bytes. You need to decode it using utf8 to get a string.
data —解码的字符串,以字节为单位。 您需要使用utf8对其进行解码以获取字符串。
type — Only useful for barcodes as it outlines the barcode format.
type —仅对条形码有用,因为它概述了条形码格式。
rect — A Rect object which represents the captured localization area.
rect —一个Rect对象,代表捕获的本地化区域。
polygon — A list of Point instances which represents the barcode or QR Code.
polygon — Point实例的列表,代表条形码或QR码。
The following image illustrates the difference between rect (blue) and polygon (pink).
下图说明了rect (蓝色)和polygon (粉红色)之间的区别。
pyzbar’s Github pyzbar的GithubIf you were to print out the whole returned result, you should get the following output
如果要打印出整个返回结果,则应获得以下输出
[Decoded(data=b'https://medium.com/@ngwaifoong92', type='QRCODE', rect=Rect(left=40, top=40, width=330, height=330), polygon=[Point(x=40, y=40), Point(x=40, y=369), Point(x=370, y=370), Point(x=369, y=40)])]Use the following code to loop over each of the element and print out the decoded string
使用以下代码循环遍历每个元素并打印出解码后的字符串
for i in result: print(i.data.decode("utf-8"))The complete code can be found at the following gist.
完整的代码可以在以下要点找到。
from pyzbar.pyzbar import decode from PIL import Image img = Image.open('qrcode.png') result = decode(img) for i in result: print(i.data.decode("utf-8"))Let’s recap what we have learned today.
让我们回顾一下我们今天学到的东西。
We started off with some explanations on the fundamental concepts behind python-barcode, qrcode and pyzbar.
我们首先对python-barcode , qrcode和pyzbar背后的基本概念进行了一些解释。
After that, we moved on to install the necessary modules. Installation is pretty straightforward with pip install.
之后,我们继续安装必要的模块。 pip install非常简单。
Once we are done with it, we implemented the generation of both barcodes and QR Codes with the configuration parameters of our choice.
完成后,我们将使用我们选择的配置参数来实现条形码和QR码的生成。
Finally, we utilized pyzbar module to decode the images that we have generated earlier.
最后,我们使用pyzbar模块对我们之前生成的图像进行解码。
Thanks for reading this piece. Hope to see you again in the next article!
感谢您阅读本文。 希望在下一篇文章中再见!
翻译自: https://towardsdatascience.com/barcodes-and-qr-codes-decoder-in-python-59615c5f2b23
相关资源:基于python的二维码识别的代码