如何在(最好是纯粹的)Python中解码QR码图像?

kra*_*r65 72 python decode qr-code zxing zbar

TL; DR:我需要一种方法来解码使用(最好是纯粹的)Python的图像文件中的QR码.

我有一个带有QR码的jpg文件,我想用Python解码.我找到了几个声称这样做的图书馆:

PyQRCode(这里的网站)据说可以通过简单地提供这样的路径来解码图像中的qr代码:

import sys, qrcode
d = qrcode.Decoder()
if d.decode('out.png'):
    print 'result: ' + d.result
else:
    print 'error: ' + d.error
Run Code Online (Sandbox Code Playgroud)

所以我只是使用它安装它sudo pip install pyqrcode.然而,我对上面的示例代码感到奇怪的是,它只导入qrcode(而不是导入pyqrcode)因为我认为qrcode引用这个只能生成 qr代码图像的,这让我很困惑.所以,我想上面两个密码pyqrcodeqrcode,但双方未能在第二条线的说法AttributeError: 'module' object has no attribute 'Decoder'.此外,该网站是指Ubuntu 8.10(超过6年前推出),我找不到它的公共(git或其他)存储库来检查最新的提交.所以我转到了下一个图书馆:

ZBar(这里的网站)声称是,"an open source software suite for reading bar codes from various sources, such as image files."所以我尝试在Mac OSX上运行它sudo pip install zbar.这失败了error: command 'cc' failed with exit status 1.我试着在这个问题的答案中提出建议,但我似乎无法解决它.所以我决定继续前进:

QRTools,根据这篇博文,可以使用以下代码轻松解码图像:

from qrtools import QR
myCode = QR(filename=u"/home/psutton/Documents/Python/qrcodes/qrcode.png")
if myCode.decode():
  print myCode.data
  print myCode.data_type
  print myCode.data_to_string()
Run Code Online (Sandbox Code Playgroud)

所以我尝试使用sudo pip install qrtools它安装它,找不到任何东西.我也试了一下python-qrtools,qr-tools,python-qrtools和一对夫妇更多的组合,可惜不得要领.我想这是指这个回购说它基于ZBar(见上文).虽然我想在Heroku上运行我的代码(因此更喜欢纯Python解决方案),但我成功地将它安装在Linux机器上(带sudo apt-get install python-qrtools)并尝试运行它:

from qrtools import QR
c = QR(filename='/home/kramer65/qrcode.jpg')
c.data  # prints u'NULL'
c.data_type  # prints u'text'
c.data_to_string()  # prints '\xef\xbb\xbfNULL' where I expect an int (being `1234567890`)
Run Code Online (Sandbox Code Playgroud)

虽然这似乎解码了它,它似乎没有正确地做到这一点.它还需要ZBar,因此不是纯Python.所以我决定找另一个图书馆.

PyXing(这里的网站)应该是流行的Java ZXing库的Python端口,但最初的和唯一的提交是6年,项目没有任何自述文件或文档.

其余的我找到了几个qr -en编码器(不是de coders)和一些可以为你解码的API端点.由于我不喜欢这个服务依赖于其他API端点,我希望保持解码本地.

总结一下; 谁能知道如何从(优选纯粹的)Python中的图像中解码QR码?欢迎所有提示!

mu *_*u 無 91

您可以使用以下步骤和代码尝试qrtools:

  • 创建一个qrcode文件(如果尚未存在)

  • 使用解码现有qrcode文件qrtools

    • 安装qrtools使用sudo apt-get install python-qrtools
    • 现在在python提示符下使用以下代码

      >>> import qrtools
      >>> qr = qrtools.QR()
      >>> qr.decode("horn.png")
      >>> print qr.data
      u'HORN O.K. PLEASE.'
      
      Run Code Online (Sandbox Code Playgroud)

以下是单次运行中的完整代码:

In [2]: import pyqrcode
In [3]: qr = pyqrcode.create("HORN O.K. PLEASE.")
In [4]: qr.png("horn.png", scale=6)
In [5]: import qrtools
In [6]: qr = qrtools.QR()
In [7]: qr.decode("horn.png")
Out[7]: True
In [8]: print qr.data
HORN O.K. PLEASE.
Run Code Online (Sandbox Code Playgroud)

注意事项

  • 导入 qrtools 时没有名为 zbar 的模块 (4认同)
  • 这不起作用,给出了Exception:tostring()已被删除. (3认同)
  • @BhishanPoudel我也遇到过这个.似乎错误已经修复,应该出现在下一个版本中.对于遇到此问题的任何人,您可以编辑/usr/lib/python2.7/dist-packages/qrtools.py的第181行(位置可能不同)并将"tostring"替换为"tobytes".它现在对我很好. (2认同)
  • 不起作用。AttributeError:模块“ qrtools”没有属性“ QR” (2认同)
  • @SaeedMohtasham 尝试`from qrtools import qrtools` (2认同)

小智 21

以下代码对我来说很好用:

brew install zbar
pip install pyqrcode
pip install pyzbar
Run Code Online (Sandbox Code Playgroud)

对于二维码图像创建:

import pyqrcode
qr = pyqrcode.create("test1")
qr.png("test1.png", scale=6)
Run Code Online (Sandbox Code Playgroud)

二维码解码:

from PIL import Image
from pyzbar.pyzbar import decode
data = decode(Image.open('test1.png'))
print(data)
Run Code Online (Sandbox Code Playgroud)

打印结果:

[Decoded(data=b'test1', type='QRCODE', rect=Rect(left=24, top=24, width=126, height=126), polygon=[Point(x=24, y=24), Point(x=24, y=150), Point(x=150, y=150), Point(x=150, y=24)])]
Run Code Online (Sandbox Code Playgroud)

  • 为了使上述解决方案起作用,您还需要运行 pip install pypng && pip install image (2认同)

小智 15

我找到了一种新的有效方法,就是使用 cv2。下面的代码将解码 QR 码。

import cv2
# Name of the QR Code Image file
filename = "attandence_Record_QR_code.png"
# read the QRCODE image
image = cv2.imread(filename)
# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()
# detect and decode
data, vertices_array, binary_qrcode = detector.detectAndDecode(image)
# if there is a QR code
# print the data
if vertices_array is not None:
  print("QRCode data:")
  print(data)
else:
  print("There was some error") 
Run Code Online (Sandbox Code Playgroud)


Bas*_*asj 7

我只回答有关zbar安装的问题的一部分。

我花了将近半个小时和几个小时使它在 Windows + Python 2.7 64 位上运行,所以这里是对已接受答案的附加说明:

PS:使它与 Python 3.x 一起工作更加困难:为 Python 3.x 编译 zbar

PS2:我刚刚用pyzbar进行了测试pip install pyzbar,它更容易,它开箱即用(唯一的问题是您需要安装 VC Redist 2013 文件)。在这篇 pyimagesearch.com 文章中也推荐使用这个库。


Gok*_* NC 6

有一个名为BoofCV 的库,它声称比 ZBar 和其他库更好
以下是使用它的步骤(任何操作系统)。

先决条件:

  • 确保 JDK 14+ 已安装并在 $PATH 中设置
  • pip install pyboof

要解码的类:

import os
import numpy as np
import pyboof as pb

pb.init_memmap() #Optional

class QR_Extractor:
    # Src: github.com/lessthanoptimal/PyBoof/blob/master/examples/qrcode_detect.py
    def __init__(self):
        self.detector = pb.FactoryFiducial(np.uint8).qrcode()
    
    def extract(self, img_path):
        if not os.path.isfile(img_path):
            print('File not found:', img_path)
            return None
        image = pb.load_single_band(img_path, np.uint8)
        self.detector.detect(image)
        qr_codes = []
        for qr in self.detector.detections:
            qr_codes.append({
                'text': qr.message,
                'points': qr.bounds.convert_tuple()
            })
        return qr_codes
Run Code Online (Sandbox Code Playgroud)

用法:

qr_scanner = QR_Extractor()
output = qr_scanner.extract('Your-Image.jpg')
print(output)
Run Code Online (Sandbox Code Playgroud)

已在 Python 3.8(Windows 和 Ubuntu)上测试并运行

  • 它似乎试图调用 java: jar_path = os.path.join(os.path.dirname(jar_path),"PyBoof-all.jar") 所以不是真正纯粹的Python ... (3认同)

Ben*_*nji 5

在 2022 年,使用 Python 3 这对我来说很有效。

第1步:安装zbar库

苹果系统:

brew install zbar
Run Code Online (Sandbox Code Playgroud)

如果您收到'Unable to find zbar shared library'ImportError 则执行以下操作:

mkdir ~/lib
ln -s $(brew --prefix zbar)/lib/libzbar.dylib ~/lib/libzbar.dylib
Run Code Online (Sandbox Code Playgroud)

Ubuntu/Debian Linux:

sudo apt-get update
sudo apt-get install zbar-tools
Run Code Online (Sandbox Code Playgroud)

视窗:

根据pyzbar 项目页面:安装“Visual C++ Redistributable Packages for Visual Studio 2013。如果使用 64 位 Python,请安装 vcredist_x64.exe,如果使用 32 位 Python,请安装 vcredist_x86.exe。”

步骤 2:安装 PIP Python 包

pip3 install opencv-python
pip3 install pyzbar
Run Code Online (Sandbox Code Playgroud)

第 3 步:创建 Python 脚本

创建.py脚本并运行以下命令:

import cv2 as cv
from pyzbar.pyzbar import decode

qrcode_img = 'path/to/qrcode/img.png'
img = cv.imread(qrcode_img)
decoded_data = decode(img)

# parse the decoded zbar data
url = decoded_data[0].data.decode()
print(f'URL: {url}')
Run Code Online (Sandbox Code Playgroud)