22
33import ctypes
44
5- from quirc import api
5+ import api
6+ import compat
7+ import converters
68
7- USING_PIL = True
8- try :
9- from PIL import Image
10- except ImportError :
9+ if compat .have_pil :
1110 try :
1211 import Image
1312 except ImportError :
14- USING_PIL = False
13+ from PIL import Image
1514
1615
1716def decode (image ):
@@ -34,24 +33,16 @@ def decode(image):
3433 buffer = api .begin (obj , width , height )
3534
3635 # Fill buffer with a image pixels. One cell, one pixel.
37- # TODO: looks like a very slow operation
38- idx = 0
39- for i in range (width ):
40- for j in range (height ):
41- buffer [idx ] = ctypes .c_uint8 (pixels [j , i ])
42- idx += 1
43-
44- del idx
36+ for idx , pixel in enumerate (converters .pil (image )):
37+ buffer [idx ] = pixel
4538
4639 # Finish codes identification
4740 api .end (obj )
4841
49- num_codes = api .count (obj )
50-
5142 code = api .structures .Code ()
5243 data = api .structures .Data ()
5344
54- for i in range (num_codes ):
45+ for i in range (api . count ( obj ) ):
5546
5647 # Extract first code
5748 api .extract (obj , i , code )
@@ -67,3 +58,37 @@ def decode(image):
6758 }
6859
6960 api .destroy (obj )
61+
62+
63+ class Decoder (object ):
64+
65+ def __init__ (self , width , height ):
66+ self ._width = width
67+ self ._height = height
68+
69+ self ._obj = api .new ()
70+ api .resize (self ._obj , self ._width , self ._height )
71+
72+ self ._code = api .structures .Code ()
73+ self ._data = api .structures .Data ()
74+
75+ def decode (self , image ):
76+ buffer = api .begin (self ._obj , self ._width , self ._height )
77+
78+ if image .mode not in ('1' , 'L' ):
79+ image = image .convert ('L' )
80+ pixels = image .load ()
81+
82+ idx = 0
83+ for i in range (self ._width ):
84+ for j in range (self ._height ):
85+ buffer [idx ] = ctypes .c_uint8 (pixels [j , i ])
86+ idx += 1
87+
88+ del idx
89+
90+ # Finish codes identification
91+ api .end (self ._obj )
92+
93+ def __del__ (self ):
94+ api .destroy (self ._obj )
0 commit comments