Debian Codegraph @

pylibdmtx/pylibdmtx.py

raw
1 from __future__ import print_function
2
3 import ctypes
4 from collections import namedtuple
5 from contextlib import contextmanager
6 from ctypes import byref, cast, string_at
7 from functools import partial
8
9 from .pylibdmtx_error import PyLibDMTXError
10 from .wrapper import (
11 c_ubyte_p, dmtxImageCreate, dmtxImageDestroy, dmtxDecodeCreate,
12 dmtxDecodeDestroy, dmtxRegionDestroy, dmtxMessageDestroy, dmtxTimeAdd,
13 dmtxTimeNow, dmtxDecodeMatrixRegion, dmtxRegionFindNext,
14 dmtxMatrix3VMultiplyBy, dmtxDecodeSetProp, DmtxPackOrder, DmtxProperty,
15 DmtxUndefined, DmtxVector2, EXTERNAL_DEPENDENCIES,
16 DmtxSymbolSize, DmtxScheme, dmtxEncodeSetProp, dmtxEncodeDataMatrix,
17 dmtxImageGetProp, dmtxEncodeCreate, dmtxEncodeDestroy
18 )
19
20 __all__ = [
21 'decode', 'encode', 'Encoded', 'ENCODING_SCHEME_NAMES',
22 'ENCODING_SIZE_NAMES', 'EXTERNAL_DEPENDENCIES',
23 ]
24
25 ENCODING_SCHEME_PREFIX = 'DmtxScheme'
26 ENCODING_SIZE_PREFIX = 'DmtxSymbol'
27
28 ENCODING_SCHEME_NAMES = sorted(
29 n.name[len(ENCODING_SCHEME_PREFIX):] for n in DmtxScheme
30 )
31
32 # Not sorting encoding size names - would need to use natural sort order;
33 # the existing order within DmtxSymbolSize is sensible.
34 ENCODING_SIZE_NAMES = [
35 n.name[len(ENCODING_SIZE_PREFIX):] for n in DmtxSymbolSize
36 ]
37
38 # A rectangle
39 Rect = namedtuple('Rect', 'left top width height')
40 Rect_vertices = namedtuple('Rect_vertices', 'P0 P1 P2 P3')
41
42 # Results of reading a barcode
43 Decoded = namedtuple('Decoded', 'data rect')
44
45 # Results of encoding data to an image
46 Encoded = namedtuple('Encoded', 'width height bpp pixels')
47
48 # Crude mapping from bits-per-pixels to values in DmtxPackOrder enum
49 _PACK_ORDER = {
50 8: DmtxPackOrder.DmtxPack8bppK,
51 16: DmtxPackOrder.DmtxPack16bppRGB,
52 24: DmtxPackOrder.DmtxPack24bppRGB,
53 32: DmtxPackOrder.DmtxPack32bppRGBX,
54 }
55
56
57 @contextmanager
58 def _image(pixels, width, height, pack):
59 """A context manager for `DmtxImage`, created and destroyed by
60 `dmtxImageCreate` and `dmtxImageDestroy`.
61
62 Args:
63 pixels (:obj:):
64 width (int):
65 height (int):
66 pack (int):
67
68 Yields:
69 DmtxImage: The created image
70
71 Raises:
72 PyLibDMTXError: If the image could not be created.
73 """
74 image = dmtxImageCreate(pixels, width, height, pack)
75 if not image:
76 raise PyLibDMTXError('Could not create image')
77 else:
78 try:
79 yield image
80 finally:
81 dmtxImageDestroy(byref(image))
82
83
84 @contextmanager
85 def _decoder(image, shrink):
86 """A context manager for `DmtxDecode`, created and destroyed by
87 `dmtxDecodeCreate` and `dmtxDecodeDestroy`.
88
89 Args:
90 image (POINTER(DmtxImage)):
91 shrink (int):
92
93 Yields:
94 POINTER(DmtxDecode): The created decoder
95
96 Raises:
97 PyLibDMTXError: If the decoder could not be created.
98 """
99 decoder = dmtxDecodeCreate(image, shrink)
100 if not decoder:
101 raise PyLibDMTXError('Could not create decoder')
102 else:
103 try:
104 yield decoder
105 finally:
106 dmtxDecodeDestroy(byref(decoder))
107
108
109 @contextmanager
110 def _region(decoder, timeout):
111 """A context manager for `DmtxRegion`, created and destroyed by
112 `dmtxRegionFindNext` and `dmtxRegionDestroy`.
113
114 Args:
115 decoder (POINTER(DmtxDecode)):
116 timeout (int or None):
117
118 Yields:
119 DmtxRegion: The next region or None, if all regions have been found.
120 """
121 region = dmtxRegionFindNext(decoder, timeout)
122 try:
123 yield region
124 finally:
125 if region:
126 dmtxRegionDestroy(byref(region))
127
128
129 @contextmanager
130 def _decoded_matrix_region(decoder, region, corrections):
131 """A context manager for `DmtxMessage`, created and destoyed by
132 `dmtxDecodeMatrixRegion` and `dmtxMessageDestroy`.
133
134 Args:
135 decoder (POINTER(DmtxDecode)):
136 region (POINTER(DmtxRegion)):
137 corrections (int):
138
139 Yields:
140 DmtxMessage: The message.
141 """
142 message = dmtxDecodeMatrixRegion(decoder, region, corrections)
143 try:
144 yield message
145 finally:
146 if message:
147 dmtxMessageDestroy(byref(message))
148
149
150 def _decode_region(decoder, region, corrections, shrink, return_vertices=False):
151 """Decodes and returns the value in a region.
152
153 Args:
154 region (DmtxRegion):
155
156 Yields:
157 Decoded or None: The decoded value.
158 """
159 with _decoded_matrix_region(decoder, region, corrections) as msg:
160 if msg:
161 # Coordinates
162 p00 = DmtxVector2()
163 p11 = DmtxVector2(1.0, 1.0)
164 p10 = DmtxVector2(1.0, 0.0)
165 p01 = DmtxVector2(0.0, 1.0)
166 dmtxMatrix3VMultiplyBy(p00, region.contents.fit2raw)
167 dmtxMatrix3VMultiplyBy(p11, region.contents.fit2raw)
168 dmtxMatrix3VMultiplyBy(p01, region.contents.fit2raw)
169 dmtxMatrix3VMultiplyBy(p10, region.contents.fit2raw)
170 x00 = int((shrink * p00.X) + 0.5)
171 y00 = int((shrink * p00.Y) + 0.5)
172 x11 = int((shrink * p11.X) + 0.5)
173 y11 = int((shrink * p11.Y) + 0.5)
174 x10 = int((shrink * p10.X) + 0.5)
175 y10 = int((shrink * p10.Y) + 0.5)
176 x01 = int((shrink * p01.X) + 0.5)
177 y01 = int((shrink * p01.Y) + 0.5)
178
179 if return_vertices:
180 return Decoded(
181 string_at(msg.contents.output),
182 Rect_vertices((x00,y00), (x01,y01), (x10,y10), (x11,y11))
183 )
184 else:
185 min_x = min(x00, x11, x10, x01)
186 max_x = max(x00, x11, x10, x01)
187 min_y = min(y00, y11, y10, y01)
188 max_y = max(y00, y11, y10, y01)
189
190 return Decoded(
191 string_at(msg.contents.output),
192 Rect(min_x, min_y, max_x - min_x, max_y - min_y)
193 )
194
195 else:
196 return None
197
198
199 def _pixel_data(image):
200 """Returns (pixels, width, height, bpp)
201
202 Returns:
203 :obj: `tuple` (pixels, width, height, bpp)
204 """
205 # Test for PIL.Image, numpy.ndarray, and imageio.core.util without
206 # requiring that cv2, PIL, or imageio are installed.
207
208 image_type = str(type(image))
209 if 'PIL.' in image_type:
210 pixels = image.tobytes()
211 width, height = image.size
212 elif 'numpy.ndarray' in image_type or 'imageio.core.util' in image_type:
213 # Different versions of imageio use a subclass of numpy.ndarray
214 # called either imageio.core.util.Image or imageio.core.util.Array.
215 if 'uint8' != str(image.dtype):
216 image = image.astype('uint8')
217 try:
218 pixels = image.tobytes()
219 except AttributeError:
220 # `numpy.ndarray.tobytes()` introduced in `numpy` 1.9.0 - use the
221 # older `tostring` method.
222 pixels = image.tostring()
223 height, width = image.shape[:2]
224 else:
225 # image should be a tuple (pixels, width, height)
226 pixels, width, height = image
227
228 # Check dimensions
229 if 0 != len(pixels) % (width * height):
230 raise PyLibDMTXError(
231 (
232 'Inconsistent dimensions: image data of {0} bytes is not '
233 'divisible by (width x height = {1})'
234 ).format(len(pixels), (width * height))
235 )
236
237 # Compute bits-per-pixel
238 bpp = 8 * len(pixels) // (width * height)
239 if bpp not in _PACK_ORDER:
240 raise PyLibDMTXError(
241 'Unsupported bits-per-pixel: [{0}] Should be one of {1}'.format(
242 bpp, sorted(_PACK_ORDER.keys())
243 )
244 )
245
246 return pixels, width, height, bpp
247
248
249 def decode(image, timeout=None, gap_size=None, shrink=1, shape=None,
250 deviation=None, threshold=None, min_edge=None, max_edge=None,
251 corrections=None, max_count=None, return_vertices=False):
252 """Decodes datamatrix barcodes in `image`.
253
254 Args:
255 image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, height)
256 timeout (int): milliseconds
257 gap_size (int):
258 shrink (int):
259 shape (int):
260 deviation (int):
261 threshold (int):
262 min_edge (int):
263 max_edge (int):
264 corrections (int):
265 max_count (int): stop after reading this many barcodes. `None` to read
266 as many as possible.
267 return_vertices: If to return the coordinates of the four vertices of the datamatrix or just one + width/height
268
269 Returns:
270 :obj:`list` of :obj:`Decoded`: The values decoded from barcodes.
271 """
272 dmtx_timeout = None
273 if timeout:
274 now = dmtxTimeNow()
275 dmtx_timeout = dmtxTimeAdd(now, timeout)
276
277 if max_count is not None and max_count < 1:
278 raise ValueError('Invalid max_count [{0}]'.format(max_count))
279
280 pixels, width, height, bpp = _pixel_data(image)
281
282 results = []
283 with _image(
284 cast(pixels, c_ubyte_p), width, height, _PACK_ORDER[bpp]
285 ) as img:
286 with _decoder(img, shrink) as decoder:
287 properties = [
288 (DmtxProperty.DmtxPropScanGap, gap_size),
289 (DmtxProperty.DmtxPropSymbolSize, shape),
290 (DmtxProperty.DmtxPropSquareDevn, deviation),
291 (DmtxProperty.DmtxPropEdgeThresh, threshold),
292 (DmtxProperty.DmtxPropEdgeMin, min_edge),
293 (DmtxProperty.DmtxPropEdgeMax, max_edge)
294 ]
295
296 # Set only those properties with a non-None value
297 for prop, value in ((p, v) for p, v in properties if v is not None):
298 dmtxDecodeSetProp(decoder, prop, value)
299
300 if not corrections:
301 corrections = DmtxUndefined
302
303 while True:
304 with _region(decoder, dmtx_timeout) as region:
305 # Finished file or ran out of time before finding another
306 # region
307 if not region:
308 break
309 else:
310 # Decoded
311 res = _decode_region(
312 decoder, region, corrections, shrink, return_vertices
313 )
314 if res:
315 results.append(res)
316
317 # Stop if we've reached maximum count
318 if max_count and len(results) == max_count:
319 break
320
321 return results
322
323
324 @contextmanager
325 def _encoder():
326 encoder = dmtxEncodeCreate()
327 if not encoder:
328 raise PyLibDMTXError('Could not create encoder')
329
330 try:
331 yield encoder
332 finally:
333 dmtxEncodeDestroy(byref(encoder))
334
335
336 def encode(data, scheme=None, size=None):
337 """
338 Encodes `data` in a DataMatrix image.
339
340 For now bpp is the libdmtx default which is 24
341
342 Args:
343 data: bytes instance
344 scheme: encoding scheme - one of `ENCODING_SCHEME_NAMES`, or `None`.
345 If `None`, defaults to 'Ascii'.
346 size: image dimensions - one of `ENCODING_SIZE_NAMES`, or `None`.
347 If `None`, defaults to 'ShapeAuto'.
348
349 Returns:
350 Encoded: with properties `(width, height, bpp, pixels)`.
351 You can use that result to build a PIL image:
352
353 Image.frombytes('RGB', (width, height), pixels)
354
355 """
356
357 size = size if size else 'ShapeAuto'
358 size_name = '{0}{1}'.format(ENCODING_SIZE_PREFIX, size)
359 if not hasattr(DmtxSymbolSize, size_name):
360 raise PyLibDMTXError(
361 'Invalid size [{0}]: should be one of {1}'.format(
362 size, ENCODING_SIZE_NAMES
363 )
364 )
365 size = getattr(DmtxSymbolSize, size_name)
366
367 scheme = scheme if scheme else 'Ascii'
368 scheme_name = '{0}{1}'.format(
369 ENCODING_SCHEME_PREFIX, scheme.capitalize()
370 )
371 if not hasattr(DmtxScheme, scheme_name):
372 raise PyLibDMTXError(
373 'Invalid scheme [{0}]: should be one of {1}'.format(
374 scheme, ENCODING_SCHEME_NAMES
375 )
376 )
377 scheme = getattr(DmtxScheme, scheme_name)
378
379 with _encoder() as encoder:
380 dmtxEncodeSetProp(encoder, DmtxProperty.DmtxPropScheme, scheme)
381 dmtxEncodeSetProp(encoder, DmtxProperty.DmtxPropSizeRequest, size)
382
383 if dmtxEncodeDataMatrix(encoder, len(data), cast(data, c_ubyte_p)) == 0:
384 raise PyLibDMTXError(
385 'Could not encode data, possibly because the image is not '
386 'large enough to contain the data'
387 )
388
389 w, h, bpp = map(
390 partial(dmtxImageGetProp, encoder[0].image),
391 (
392 DmtxProperty.DmtxPropWidth, DmtxProperty.DmtxPropHeight,
393 DmtxProperty.DmtxPropBitsPerPixel
394 )
395 )
396 size = w * h * bpp // 8
397 pixels = cast(
398 encoder[0].image[0].pxl, ctypes.POINTER(ctypes.c_ubyte * size)
399 )
400 return Encoded(
401 width=w, height=h, bpp=bpp, pixels=ctypes.string_at(pixels, size)
402 )