forked from ztp-at/RKSV
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimg_decode.py
executable file
·86 lines (67 loc) · 2.54 KB
/
img_decode.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python2.7
###########################################################################
# Copyright 2017 ZT Prentner IT GmbH (www.ztp.at)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
###########################################################################
from builtins import int
from builtins import range
# FIXME: ugly hack to work with both pillow and PIL
def img_to_bytes(img):
if 'tobytes' in dir(img):
return img.tobytes()
return img.tostring()
try:
import zbar
def read_qr_codes(image):
image = image.convert('L')
width, height = image.size
raw = img_to_bytes(image)
zimg = zbar.Image(width, height, 'Y800', raw)
scanner = zbar.ImageScanner()
scanner.scan(zimg)
return [ sym.data for sym in zimg if str(sym.type) == 'QRCODE' ]
except ImportError:
from jnius import autoclass
ZImage = autoclass('net.sourceforge.zbar.Image')
ZImageScanner = autoclass('net.sourceforge.zbar.ImageScanner')
ZSymbol = autoclass('net.sourceforge.zbar.Symbol')
def read_qr_codes(image):
image = image.convert('L')
width, height = image.size
raw = img_to_bytes(image)
zimg = ZImage(width, height, 'Y800')
zimg.setData(raw)
scanner = ZImageScanner()
if scanner.scanImage(zimg) == 0:
return list()
syms = list()
it = zimg.getSymbols().iterator()
while it.hasNext():
sym = it.next()
if sym.getType() == ZSymbol.QRCODE:
syms.append(sym.getData())
return syms
if __name__ == "__main__":
import gettext
gettext.install('rktool', './lang', True)
import sys
from PIL import Image
if len(sys.argv) < 2:
print("Usage: ./img_decode.py <image file>...")
sys.exit(0)
for fn in sys.argv[1:]:
with Image.open(fn) as img:
for qr in read_qr_codes(img):
print(qr)