LoginSignup
20
21

More than 5 years have passed since last update.

Pythonで画像ファイルからQRコードを読み込む (MacOS)

Last updated at Posted at 2015-03-05

ZBar とPythonモジュール https://pypi.python.org/pypi/zbar/ を利用します。
QRコード以外のバーコードにも対応しています。

紙のカードを使った実験結果の集計を効率化するために、あらかじめカードにQRコードを仕込んでおき、スキャン後にPythonで自動処理する、ということをやったのでメモ。

環境、バージョン

インストール

ZBar

Homebrewで一発インストール。

$ brew install zbar

Python zbarモジュール

これもPyPIで一発インストール、と行きたいのですが、そのまま入れてしまうとインポート時にSegmentation faultでPythonが死にます。

$ pip install zbar

$ python
Python 2.7.9 (default, Jan  7 2015, 11:50:42) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import zbar
Segmentation fault: 11

$ pip uninstall zbar

そこで、ソースコードにパッチをあててインストールします。
このパッチでは、配列にsentinelを追加してあげることで、Segmantation faultの発生を防いでいます。

$ wget https://pypi.python.org/packages/source/z/zbar/zbar-0.10.tar.bz2
$ wget https://github.com/npinchot/zbar/commit/d3c1611ad2411fbdc3e79eb96ca704a63d30ae69.diff
$ tar jxvf zbar-0.10.tar.bz2
$ cd zbar-0.10
$ patch -p1 < ../d3c1611ad2411fbdc3e79eb96ca704a63d30ae69.diff
patching file imagescanner.c
$ python setup.py install

$ python
Python 2.7.9 (default, Jan  7 2015, 11:50:42) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import zlib
>>>

今度は大丈夫でした。

Python Pillowモジュール

PyPI一発で入ります。

$ pip install Pillow

画像ファイルからQRコードを抽出する

Pythonのテストコードです。

zbar_test.py

zbar_test.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

### cf. http://99blues.dyndns.org/blog/2010/12/zbar/

import sys
import zbar
import PIL.Image

if len(sys.argv) < 2: exit(1)

# create a reader
scanner = zbar.ImageScanner()

# configure the reader
scanner.parse_config('enable')

# obtain image data
pil = PIL.Image.open(sys.argv[1]).convert('L')
(width, height) = pil.size
raw = pil.tostring()

# wrap image data
image = zbar.Image(width, height, 'Y800', raw)

# scan the image for barcodes
scanner.scan(image)

# extract results
for symbol in image:
    # do something useful with results
    print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data

# clean up
del(image)
$ ./zbar_test.py /path/to/image.jpg
decoded QRCODE symbol "http://www.example.com/"

参考

20
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
21