条码生成与解析


1. *pyStrich (原huBarcode): 仅用于生成条码、二维码

github

pyStrich is a Python module to generate 1D and 2D barcodes. Currently it supports:

  • code39
  • code128
  • ean13
  • datamatrix
  • qrcode

1.1. 安装

pip install pyStrich

1.2. 使用

from pystrich.ean13 import EAN13Encoder
encoder = EAN13Encoder("690123456789")
encoder.save("pyStrich.png")

from pystrich.datamatrix import DataMatrixEncoder
encoder = DataMatrixEncoder("This is a DataMatrix.")
encoder.save( "sample_barcodes/datamatrix_test.png" )
print(encoder.get_ascii())

from pystrich.code39 import Code39Encoder
from pystrich.code128 import Code128Encoder
from pystrich.datamatrix import DataMatrixEncoder
from pystrich.ean13 import EAN13Encoder
from pystrich.qrcode import QRCodeEncoder

2. pylibdmtx: 仅支持DM码

github

2.1. 安装

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

  • Mac OS X: brew install libdmtx
  • Linux: sudo apt-get install libdmtx0a

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

pip install pylibdmtx
pip install pylibdmtx[scripts]

2.2. Windows error message

If you see an ugly ImportError when importing pylibdmtx 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.

2.3. 使用

2.3.1. 生成DM码

The encode function generates an image containing a Data Matrix barcode:

>>> from pylibdmtx.pylibdmtx import encode
>>> encoded = encode('hello world'.encode('utf8'))
>>> img = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels)
>>> img.save('dmtx.png')
>>> print(decode(Image.open('dmtx.png')))

2.3.2. 解码(支持PIL与numpy)

>>> from pylibdmtx.pylibdmtx import decode
>>> from PIL import Image
>>> decode(Image.open('pylibdmtx/tests/datamatrix.png'))
[Decoded(data='Stegosaurus', rect=Rect(left=5, top=6, width=96, height=95)),
 Decoded(data='Plesiosaurus', rect=Rect(left=298, top=6, width=95, height=95))]

3. qrcode: 仅适用于qrcode的生成

github

3.1. 安装

pip install qrcode

3.2. 命令行

qr 'Some data' > test.png

3.3. API

import qrcode
img = qrcode.make("xinxingzhao")
img.save("xinxing.png")

3.4. 更多的设置

上面两种方式都是按照qrcode默认的方式生成二维码,如果我们希望生成不同尺寸的二维码就需要使用QRCode类了。

import qrcode
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
qr.add_data('Some data')
qr.make(fit=True)

img = qr.make_image(fill_color="black", back_color="white")
  • version

    表示二维码的版本号,二维码总共有1到40个版本,最小的版本号是1,对应的尺寸是21×21,每增加一个版本会增加4个尺寸。这里说的尺寸不是只生成图片的大小,而是值二维码的长宽被平均分为多少份。

  • error_correction

    指的是纠错容量,这就是为什么二维码上面放一个小图标也能扫出来,纠错容量有四个级别,分别是:

    • ERROR_CORRECT_L L级别,7%或更少的错误能修正
    • ERROR_CORRECT_M M级别,15%或更少的错误能修正,也是qrcode的默认级别
    • ERROR_CORRECT_Q Q级别,25%或更少的错误能修正
    • ERROR_CORRECT_H H级别,30%或更少的错误能修正
  • box_size 指的是生成图片的像素

  • border 表示二维码的边框宽度,4是最小值

4. pyBarcode: 适用于EAN13等一维码

github

支持的码制列表:

  • EAN-8
  • EAN-13
  • UPC-A
  • JAN
  • ISBN-10
  • ISBN-13
  • ISSN
  • Code 39
  • Code 128
  • PZN

缺点:没有画出EAN13的起始符和终止符。

5. zxing: Java的解码库

github

Google维护的读码库,很多Android上的App就是用的它。

  • 1D product
    • UPC-A
    • UPC-E
    • EAN-8
    • EAN-13
    • UPC/EAN Extension 2/5
  • 1D industrial
    • Code 39
    • Code 93
    • Code 128
    • Codabar
    • ITF
    • RSS-14
    • RSS-Expanded
  • 2D
    • QR Code
    • Data Matrix
    • Aztec
    • PDF 417
    • MaxiCode

5.1. C++: zxing-cpp

gihub

In pure C++14, no third-party dependencies.

Ubuntu安装: apt install libzxingcore-dev

5.2. QZXing for Qt/QML

gihub

Qt/QML wrapper library for the ZXing library.

include(QZXing/QZXing.pri)
#include "QZXing.h"

int main()
{
    QImage imageToDecode("file.png");
    QZXing decoder;
        //mandatory settings
    decoder.setDecoder( DecoderFormat_QR_CODE | DecoderFormat_EAN_13 );

        //optional settings
        //decoder.setSourceFilterType(QZXing::SourceFilter_ImageNormal | QZXing::SourceFilter_ImageInverted);
        decoder.setSourceFilterType(QZXing::SourceFilter_ImageNormal);
        decoder.setTryHarderBehaviour(QZXing::TryHarderBehaviour_ThoroughScanning | QZXing::TryHarderBehaviour_Rotate);

        //trigger decode
    QString result = decoder.decodeImage(imageToDecode);
}

5.3. python-zxing: 一个python的wrapper

很久就已经停止维护了……

5.4. pyzxing

gihub

能够直接链接Java库,也是很牛的存在。。。

6. zbar: C的解码库

github: 当前社区版本

github: 原始版本(废弃)

据说效率很高,远超zxing。IOS上的官方读码库。不过支持的条码类型不如zxing丰富:

  • EAN-13
  • UPC-A,
  • UPC-E,
  • EAN-8,
  • Code 128,
  • Code 39,
  • Interleaved 2 of 5
  • QR Code.

注意,不支持以下类型:

  • Data Matrix
  • Axtec
  • PDF417

Debian安装: sudo apt install libzbar-dev

6.1. zbar/python

Debian安装: sudo apt install python3-zbar

import zbar
scanner = zbar.ImageScanner()
image = zbar.Image(width, height, 'Y800', raw_data)
scanner.scan(image)
for symbol in image:
    print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data

6.2. pyzbar, 条码(二维码)识别

github

在Ubuntu或树莓派上安装Zbar

$ sudo apt-get install libzbar0
$ pip3 install pyzbar

使用Demo

from pyzbar import pyzbar

barcodes = pyzbar.decode(im_qr)
for barcode in barcodes:
    # x, y, w, h = barcode.rect  # 获取条码位置
    barcodeData = barcode.data.decode("utf-8")
    barcodeType = barcode.type

    print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))

通过Pillow或OpenCV取图像

>>> 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)
        ]
    )
    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)
        ]
    )
]

7. OpenCV::QRCodeDetector

在opencv4.0以后,已经集成了二维码识读模块,因此,我们可以采用最新的opencv来实现二维码检测和识读。二维码检测和识别主要分为3步:使用 QRCodeDetector() 函数创建二维码检测器;使用 detectAndDecode() 函数对图像进行二维码检测和识别;将检测结果输出。

# 创建二维码检测器
qrDecoder = cv2.QRCodeDetector()

# 逐帧显示
while cv2.getWindowProperty("USB Camera", 0) >= 0:
    ret_val, img = cap.read()
    # 二维码检测和识别
    data,bbox,rectifiedImage = qrDecoder.detectAndDecode(img)
    if data:
        print("解码数据 : {}".format(data))
        n = len(bbox)
        for j in range(n):
            cv2.line(img, tuple(bbox[j][0]), tuple(bbox[(j+1) % n][0]), (255,0,0), 3)
    else:
        print("没有检测到二维码")

8. tesserocr: OCR字符识别

8.1. 安装

8.1.1. Linux平台

sudo apt install libleptonica-dev libtesseract-dev
pip3 install tesserocr

8.1.2. Windows

下载whl文件: github: tesserocr-windows_build

如出现:

运行错误:DLL加载错误

安装Python-Tesserocr需要 VS2015运行库

安装whl文件: pip install xxx.whl

posted @ 2020-06-28 19:31  brt2  阅读(1724)  评论(0编辑  收藏  举报