如何在(最好是纯)Python 中解码二维码图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27233351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to decode a QR-code image in (preferably pure) Python?
提问by kramer65
TL;DR: I need a way to decode a QR-code from an image file using (preferable pure) Python.
TL;DR:我需要一种使用(最好是纯)Python 从图像文件中解码 QR 码的方法。
I've got a jpg file with a QR-code which I want to decode using Python. I've found a couple libraries which claim to do this:
我有一个带有二维码的 jpg 文件,我想使用 Python 对其进行解码。我发现了几个声称这样做的图书馆:
PyQRCode(website here) which supposedly can decode qr codes from images by simply providing a path like this:
PyQRCode(网站在这里)据说可以通过简单地提供这样的路径来解码图像中的二维码:
import sys, qrcode
d = qrcode.Decoder()
if d.decode('out.png'):
print 'result: ' + d.result
else:
print 'error: ' + d.error
So I simply installed it using sudo pip install pyqrcode. The thing I find strange about the example code above however, is that it only imports qrcode(and not pyqrcodethough) Since I think qrcoderefers to this librarywhich can only generateqr-code images it kind of confused me. So I tried the code above with both pyqrcodeand qrcode, but both fail at the second line saying AttributeError: 'module' object has no attribute 'Decoder'. Furthermore, the websiterefers to Ubuntu 8.10 (which came out more than 6 years ago) and I can't find a public (git or other) repository of it to check the latest commit. So I moved on to the next library:
所以我只是使用sudo pip install pyqrcode. 然而,我对上面的示例代码感到奇怪的是,它只导入qrcode(而不是pyqrcode虽然),因为我认为qrcode指的是这个只能生成二维码图像的库,这让我有点困惑。所以我用pyqrcode和尝试了上面的代码qrcode,但都在第二行说AttributeError: 'module' object has no attribute 'Decoder'. 此外,该网站指的是 Ubuntu 8.10(6 年前推出),我找不到它的公共(git 或其他)存储库来检查最新提交。所以我转到下一个图书馆:
ZBar(website here) claims to be "an open source software suite for reading bar codes from various sources, such as image files."So I tried installing it on Mac OSX running sudo pip install zbar. This fails with error: command 'cc' failed with exit status 1. I tried to suggestions in the answers to this SO question, but I can't seem to solve it. So I decided to move on again:
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。我试图在这个 SO question的答案中提出建议,但我似乎无法解决它。所以我决定再次继续前进:
QRTools, which according to this blogpostcan decode images easily by using the following code:
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()
So I tried installing it using sudo pip install qrtools, which can't find anything. I also tried it with python-qrtools, qr-tools, python-qrtoolsand a couple more combinations, but unfortunately to no avail. I suppose it refers to this repowhich says it is based on ZBar (see above). Although I want to run my code on Heroku (and thus prefer a pure Python solution) I successfully installed it on a Linux box (with sudo apt-get install python-qrtools) and tried running it:
所以我尝试使用 安装它sudo pip install qrtools,但找不到任何东西。我也试了一下python-qrtools,qr-tools,python-qrtools和一对夫妇更多的组合,可惜不得要领。我想它指的是这个 repo,它说它基于 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`)
Although this seems to decode it, It doesn't seem to do it correctly. It furthermore needs ZBar and is thus not pure Python. So I decided to find yet another library.
虽然这似乎可以解码它,但它似乎没有正确执行。它还需要 ZBar,因此不是纯 Python。所以我决定再找一个图书馆。
PyXing(website here) is supposedly a Python port of the popular Java ZXing library, but the initial and only commit is 6 years old and the project has no readme or documentation whatsoever.
PyXing(此处为网站)据称是流行的 Java ZXing 库的 Python 端口,但最初且唯一的提交已使用 6 年,并且该项目没有任何自述文件或文档。
For the rest I found a couple qr-encoders (not decoders) and some API endpoints which can decode for you. Since I don't like this service to be dependent on other API endpoints I would want to keep the decoding local though.
对于剩下的我发现一对夫妇QR- EN编码器(未德编码器),并且能为你解码一些API端点。由于我不喜欢此服务依赖于其他 API 端点,因此我希望将解码保留在本地。
So to conclude; would anybody know how I can decode QR-codes from images in (preferable pure) Python? All tips are welcome!
所以得出结论; 有谁知道我如何从(最好是纯)Python 中的图像中解码 QR 码?欢迎所有提示!
采纳答案by u1860929
You can try the following steps and code using qrtools:
您可以尝试使用以下步骤和代码qrtools:
Create a
qrcodefile, if not already existing- I used
pyqrcodefor doing this, which can be installed usingpip install pyqrcode And then use the code:
>>> import pyqrcode >>> qr = pyqrcode.create("HORN O.K. PLEASE.") >>> qr.png("horn.png", scale=6)
- I used
Decode an existing
qrcodefile usingqrtools- Install
qrtoolsusingsudo apt-get install python-qrtools Now use the following code within your python prompt
>>> import qrtools >>> qr = qrtools.QR() >>> qr.decode("horn.png") >>> print qr.data u'HORN O.K. PLEASE.'
- Install
创建一个
qrcode文件,如果不存在- 我曾经
pyqrcode这样做过,可以使用安装pip install pyqrcode 然后使用代码:
>>> import pyqrcode >>> qr = pyqrcode.create("HORN O.K. PLEASE.") >>> qr.png("horn.png", scale=6)
- 我曾经
使用解码现有
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.'
- 安装
Here is the complete code in a single run:
以下是单次运行的完整代码:
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.
Caveats
注意事项
- You might need to install
PyPNGusingpip install pypngfor usingpyqrcode In case you have
PILinstalled, you might getIOError: decoder zip not available. In that case, try uninstalling and reinstallingPILusing:pip uninstall PIL pip install PILIf that doesn't work, try using
Pillowinsteadpip uninstall PIL pip install pillow
回答by Basj
I'm answering only the part of the question about zbarinstallation.
我只回答有关zbar安装的问题的一部分。
I spent nearly half an houra few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:
我花了将近半个小时和几个小时使它在 Windows + Python 2.7 64 位上工作,所以这里是对已接受答案的附加说明:
Install it with
pip install zbar-0.10-cp27-none-win_amd64.whlIf Python reports an
ImportError: DLL load failed: The specified module could not be found.when doingimport zbar, then you will justneed to install the Visual C++ Redistributable Packages for VS 2013(I spent a lot of time here, trying to recompile unsuccessfully...)Required too: libzbar64-0.dll must be in a folder which is in the PATH. In my case I copied it to "C:\Python27\libzbar64-0.dll" (which is in the PATH). If it still does not work, add this:
import os os.environ['PATH'] += ';C:\Python27' import zbar
安装它
pip install zbar-0.10-cp27-none-win_amd64.whl如果 Python
ImportError: DLL load failed: The specified module could not be found.在执行时报告 animport zbar,那么您只需要安装Visual C++ Redistributable Packages for VS 2013(我在这里花了很多时间,试图重新编译失败......)也需要:libzbar64-0.dll 必须位于 PATH 中的文件夹中。就我而言,我将其复制到“C:\Python27\libzbar64-0.dll”(在 PATH 中)。如果仍然不起作用,请添加以下内容:
import os os.environ['PATH'] += ';C:\Python27' import zbar
PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.
PS:使它与 Python 3.x 一起工作更加困难:为 Python 3.x 编译 zbar。
PS2: I just tested pyzbarwith pip install pyzbarand it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.
PS2:我刚刚用pyzbar测试了pip install pyzbar它,它更容易,它开箱即用(唯一的问题是你需要安装 VC Redist 2013 文件)。在这篇 pyimagesearch.com 文章中也推荐使用这个库。
回答by Yuiq
The following code works fine with me:
以下代码对我来说很好用:
brew install zbar
pip install pyqrcode
pip install pyzbar
For QR code image creation:
对于二维码图像创建:
import pyqrcode
qr = pyqrcode.create("test1")
qr.png("test1.png", scale=6)
For QR code decoding:
二维码解码:
from PIL import Image
from pyzbar.pyzbar import decode
data = decode(Image.open('test1.png'))
print(data)
that prints the result:
打印结果:
[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)])]

