PassportEye 2.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ '''
2
+ PassportEye: Tools for visual processing of identification documents.
3
+
4
+ Author: Konstantin Tretyakov
5
+ License: MIT
6
+ '''
7
+
8
+ __version__ = "2.3.0"
9
+
10
+ from passporteye.mrz.image import read_mrz
@@ -0,0 +1,7 @@
1
+ '''
2
+ PassportEye::MRZ: Machine-readable zone extraction and parsing.
3
+
4
+ Author: Konstantin Tretyakov
5
+ License: MIT
6
+ '''
7
+
@@ -0,0 +1,387 @@
1
+ '''
2
+ PassportEye::MRZ: Machine-readable zone extraction and parsing.
3
+ Image processing for MRZ extraction.
4
+
5
+ Author: Konstantin Tretyakov
6
+ License: MIT
7
+ '''
8
+ import io
9
+ import numpy as np
10
+ import imageio.v3 as imageio_v3
11
+ from skimage import transform, morphology, filters, measure, color
12
+ from ..util.pdf import extract_first_jpeg_in_pdf
13
+ from ..util.pipeline import Pipeline
14
+ from ..util.geometry import RotatedBox
15
+ from ..util.ocr import ocr
16
+ from .text import MRZ
17
+
18
+
19
+ class Loader(object):
20
+ """Loads `file` to `img`."""
21
+
22
+ __depends__ = []
23
+ __provides__ = ['img']
24
+
25
+ def __init__(self, file, as_gray=True, pdf_aware=True):
26
+ self.file = file
27
+ self.as_gray = as_gray
28
+ self.pdf_aware = pdf_aware
29
+
30
+ def _imread(self, file):
31
+ """Reads an image from a filename, bytes or a binary stream.
32
+
33
+ This used to be skimage.io.imread(..., plugin='imageio') with a fallback to plugin='matplotlib'.
34
+ The plugin infrastructure of skimage.io is deprecated since 0.25 and is removed in 0.27,
35
+ so we call the libraries those plugins wrapped directly, keeping the same behaviour."""
36
+ img = self._postprocess(imageio_v3.imread(file))
37
+ if img is not None and len(img.shape) != 2:
38
+ # The PIL plugin somewhy fails to load some images
39
+ import matplotlib.image # pylint: disable=import-outside-toplevel
40
+ img = self._postprocess(matplotlib.image.imread(file))
41
+ return img
42
+
43
+ def _postprocess(self, img):
44
+ """Mirrors what skimage.io.imread does after reading: writable array, channels last, optional conversion to gray."""
45
+ img = np.asarray(img)
46
+ if not img.flags['WRITEABLE']:
47
+ img = img.copy()
48
+ if img.ndim > 2:
49
+ if img.shape[-1] not in (3, 4) and img.shape[-3] in (3, 4):
50
+ img = np.swapaxes(img, -1, -3)
51
+ img = np.swapaxes(img, -2, -3)
52
+ if self.as_gray:
53
+ if img.shape[2] == 4:
54
+ img = color.rgba2rgb(img)
55
+ img = color.rgb2gray(img)
56
+ return img
57
+
58
+ def __call__(self):
59
+ if isinstance(self.file, str):
60
+ if self.pdf_aware and self.file.lower().endswith('.pdf'):
61
+ with open(self.file, 'rb') as f:
62
+ img_data = extract_first_jpeg_in_pdf(f)
63
+ if img_data is None:
64
+ return None
65
+ return self._imread(img_data)
66
+ else:
67
+ return self._imread(self.file)
68
+ elif isinstance(self.file, (bytes, io.IOBase)):
69
+ return self._imread(self.file)
70
+ return None
71
+
72
+
73
+ class Scaler(object):
74
+ """Scales `image` down to `img_scaled` so that its width is at most 250."""
75
+
76
+ __depends__ = ['img']
77
+ __provides__ = ['img_small', 'scale_factor']
78
+
79
+ def __init__(self, max_width=250):
80
+ self.max_width = max_width
81
+
82
+ def __call__(self, img):
83
+ scale_factor = self.max_width / float(img.shape[1])
84
+ if scale_factor <= 1:
85
+ img_small = transform.rescale(img, scale_factor, mode='constant', channel_axis=None, anti_aliasing=True)
86
+ else:
87
+ scale_factor = 1.0
88
+ img_small = img
89
+ return img_small, scale_factor
90
+
91
+
92
+ def _square_footprint(size):
93
+ """Returns a `size` x `size` morphological footprint.
94
+
95
+ scikit-image 0.25 introduced `footprint_rectangle` and deprecated
96
+ `square`/`rectangle` in favor of it; the old functions are scheduled
97
+ for removal in 0.27. This keeps us working across the full range of
98
+ scikit-image versions this package supports (>= 0.19.0) both before
99
+ and after that removal.
100
+ """
101
+ if hasattr(morphology, 'footprint_rectangle'):
102
+ return morphology.footprint_rectangle((size, size))
103
+ return morphology.square(size)
104
+
105
+
106
+ class BooneTransform(object):
107
+ """Processes `img_small` according to Hans Boone's method
108
+ (http://www.pyimagesearch.com/2015/11/30/detecting-machine-readable-zones-in-passport-images/)
109
+ Outputs a `img_binary` - a result of threshold_otsu(closing(sobel(black_tophat(img_small)))"""
110
+
111
+ __depends__ = ['img_small']
112
+ __provides__ = ['img_binary']
113
+
114
+ def __init__(self, square_size=5):
115
+ self.square_size = square_size
116
+
117
+ def __call__(self, img_small):
118
+ m = _square_footprint(self.square_size)
119
+ img_th = morphology.black_tophat(img_small, m)
120
+ img_sob = abs(filters.sobel_v(img_th))
121
+ img_closed = morphology.closing(img_sob, m)
122
+ threshold = filters.threshold_otsu(img_closed)
123
+ return img_closed > threshold
124
+
125
+
126
+ class MRZBoxLocator(object):
127
+ """Extracts putative MRZs as RotatedBox instances from the contours of `img_binary`"""
128
+
129
+ __depends__ = ['img_binary']
130
+ __provides__ = ['boxes']
131
+
132
+ def __init__(self, max_boxes=4, min_points_in_contour=50, min_area=500, min_box_aspect=5, angle_tol=0.1,
133
+ lineskip_tol=1.5, box_type='bb'):
134
+ self.max_boxes = max_boxes
135
+ self.min_points_in_contour = min_points_in_contour
136
+ self.min_area = min_area
137
+ self.min_box_aspect = min_box_aspect
138
+ self.angle_tol = angle_tol
139
+ self.lineskip_tol = lineskip_tol
140
+ self.box_type = box_type
141
+
142
+ def __call__(self, img_binary):
143
+ cs = measure.find_contours(img_binary, 0.5)
144
+
145
+ # Collect contours into RotatedBoxes
146
+ results = []
147
+ for c in cs:
148
+ # Now examine the bounding box. If it is too small, we ignore the contour
149
+ ll, ur = np.min(c, 0), np.max(c, 0)
150
+ wh = ur - ll
151
+ if wh[0] * wh[1] < self.min_area:
152
+ continue
153
+
154
+ # Finally, construct the rotatedbox. If its aspect ratio is too small, we ignore it
155
+ rb = RotatedBox.from_points(c, self.box_type)
156
+ if rb.height == 0 or rb.width / rb.height < self.min_box_aspect:
157
+ continue
158
+
159
+ # All tests fine, add to the list
160
+ results.append(rb)
161
+
162
+ # Next sort and leave only max_boxes largest boxes by area
163
+ results.sort(key=lambda x: -x.area)
164
+ return self._fixup_boxes(self._merge_boxes(results[0:self.max_boxes]))
165
+
166
+ def _are_aligned_angles(self, b1, b2):
167
+ "Are two boxes aligned according to their angle?"
168
+ return abs(b1 - b2) <= self.angle_tol or abs(np.pi - abs(b1 - b2)) <= self.angle_tol
169
+
170
+ def _are_nearby_parallel_boxes(self, b1, b2):
171
+ "Are two boxes nearby, parallel, and similar in width?"
172
+ if not self._are_aligned_angles(b1.angle, b2.angle):
173
+ return False
174
+ # Otherwise pick the smaller angle and see whether the two boxes are close according to the "up" direction wrt that angle
175
+ angle = min(b1.angle, b2.angle)
176
+ return abs(np.dot(b1.center - b2.center, [-np.sin(angle), np.cos(angle)])) < self.lineskip_tol * (
177
+ b1.height + b2.height) and (b1.width > 0) and (b2.width > 0) and (0.5 < b1.width / b2.width < 2.0)
178
+
179
+ def _merge_any_two_boxes(self, box_list):
180
+ """Given a list of boxes, finds two nearby parallel ones and merges them. Returns false if none found."""
181
+ n = len(box_list)
182
+ for i in range(n):
183
+ for j in range(i + 1, n):
184
+ if self._are_nearby_parallel_boxes(box_list[i], box_list[j]):
185
+ # Remove the two boxes from the list, add a new one
186
+ a, b = box_list[i], box_list[j]
187
+ merged_points = np.vstack([a.points, b.points])
188
+ merged_box = RotatedBox.from_points(merged_points, self.box_type)
189
+ if merged_box.width / merged_box.height >= self.min_box_aspect:
190
+ box_list.remove(a)
191
+ box_list.remove(b)
192
+ box_list.append(merged_box)
193
+ return True
194
+ return False
195
+
196
+ def _merge_boxes(self, box_list):
197
+ """Mergest nearby parallel boxes in the given list."""
198
+ while self._merge_any_two_boxes(box_list):
199
+ pass
200
+ return box_list
201
+
202
+ def _fixup_boxes(self, box_list):
203
+ """If the box's angle is np.pi/2 +- 0.01, we shall round it to np.pi/2.
204
+
205
+ This way image extraction is fast and introduces no distortions.
206
+ and this may be more important than being perfectly straight
207
+ similar for 0 angle.
208
+ The box_list is fixed in-place (but also returned).
209
+ """
210
+ for box in box_list:
211
+ if abs(abs(box.angle) - np.pi / 2) <= 0.01:
212
+ box.angle = np.pi / 2
213
+ if abs(box.angle) <= 0.01:
214
+ box.angle = 0.0
215
+ return box_list
216
+
217
+ class ExtractAllBoxes(object):
218
+ """Extract all the images from the boxes, for external OCR processing"""
219
+
220
+ __provides__ = ['rois']
221
+ __depends__ = ['boxes', 'img', 'scale_factor']
222
+
223
+ def __call__(self, boxes, img, scale_factor):
224
+ return [box.extract_from_image(img, 1.0 / scale_factor) for box in boxes]
225
+
226
+
227
+ class FindFirstValidMRZ(object):
228
+ """Iterates over boxes found by MRZBoxLocator, passes them to BoxToMRZ, finds the first valid MRZ
229
+ or the best-scoring MRZ"""
230
+
231
+ __provides__ = ['box_idx', 'roi', 'text', 'mrz']
232
+ __depends__ = ['boxes', 'img', 'img_small', 'scale_factor', '__data__']
233
+
234
+ def __init__(self, use_original_image=True, extra_cmdline_params=''):
235
+ self.box_to_mrz = BoxToMRZ(use_original_image, extra_cmdline_params=extra_cmdline_params)
236
+
237
+ def __call__(self, boxes, img, img_small, scale_factor, data):
238
+ mrzs = []
239
+ data['__debug__mrz'] = []
240
+ for i, b in enumerate(boxes):
241
+ roi, text, mrz = self.box_to_mrz(b, img, img_small, scale_factor)
242
+ data['__debug__mrz'].append((roi, text, mrz))
243
+ if mrz.valid:
244
+ return i, roi, text, mrz
245
+ elif mrz.valid_score > 0:
246
+ mrzs.append((i, roi, text, mrz))
247
+ if not mrzs:
248
+ return None, None, None, None
249
+ else:
250
+ mrzs.sort(key=lambda x: x[3].valid_score)
251
+ return mrzs[-1]
252
+
253
+
254
+ class BoxToMRZ(object):
255
+ """Extracts ROI from the image, corresponding to a box found by MRZBoxLocator, does OCR and MRZ parsing on this region."""
256
+
257
+ __provides__ = ['roi', 'text', 'mrz']
258
+ __depends__ = ['box', 'img', 'img_small', 'scale_factor']
259
+
260
+ def __init__(self, use_original_image=True, extra_cmdline_params=''):
261
+ """
262
+ :param use_original_image: when True, the ROI is extracted from img, otherwise from img_small
263
+ """
264
+ self.use_original_image = use_original_image
265
+ self.extra_cmdline_params = extra_cmdline_params
266
+
267
+ def __call__(self, box, img, img_small, scale_factor):
268
+ img = img if self.use_original_image else img_small
269
+ scale = 1.0 / scale_factor if self.use_original_image else 1.0
270
+ roi = box.extract_from_image(img, scale)
271
+ text = ocr(roi, extra_cmdline_params=self.extra_cmdline_params)
272
+
273
+ if '>>' in text or ('>' in text and '<' not in text):
274
+ # Most probably we need to reverse the ROI
275
+ roi = roi[::-1, ::-1]
276
+ text = ocr(roi, extra_cmdline_params=self.extra_cmdline_params)
277
+
278
+ if '<' not in text:
279
+ # Assume this is unrecoverable and stop here (TODO: this may be premature, although it saves time on useless stuff)
280
+ return roi, text, MRZ.from_ocr(text)
281
+
282
+ mrz = MRZ.from_ocr(text)
283
+ mrz.aux['method'] = 'direct'
284
+
285
+ # Now try improving the result via hacks
286
+ if not mrz.valid:
287
+ text, mrz = self._try_larger_image(roi, text, mrz)
288
+
289
+ # Sometimes the filter used for enlargement is important!
290
+ if not mrz.valid:
291
+ text, mrz = self._try_larger_image(roi, text, mrz, 1)
292
+
293
+ if not mrz.valid:
294
+ text, mrz = self._try_black_tophat(roi, text, mrz)
295
+
296
+ return roi, text, mrz
297
+
298
+ def _try_larger_image(self, roi, cur_text, cur_mrz, filter_order=3):
299
+ """Attempts to improve the OCR result by scaling the image. If the new mrz is better, returns it, otherwise returns
300
+ the old mrz."""
301
+ if roi.shape[1] <= 700:
302
+ scale_by = int(1050.0 / roi.shape[1] + 0.5)
303
+ roi_lg = transform.rescale(roi, scale_by, order=filter_order, mode='constant', channel_axis=None,
304
+ anti_aliasing=True)
305
+ new_text = ocr(roi_lg, extra_cmdline_params=self.extra_cmdline_params)
306
+ new_mrz = MRZ.from_ocr(new_text)
307
+ new_mrz.aux['method'] = 'rescaled(%d)' % filter_order
308
+ if new_mrz.valid_score > cur_mrz.valid_score:
309
+ cur_mrz = new_mrz
310
+ cur_text = new_text
311
+ return cur_text, cur_mrz
312
+
313
+ def _try_black_tophat(self, roi, cur_text, cur_mrz):
314
+ roi_b = morphology.black_tophat(roi, morphology.disk(5))
315
+ # There are some examples where this line basically hangs for an undetermined amount of time.
316
+ new_text = ocr(roi_b, extra_cmdline_params=self.extra_cmdline_params)
317
+ new_mrz = MRZ.from_ocr(new_text)
318
+ if new_mrz.valid_score > cur_mrz.valid_score:
319
+ new_mrz.aux['method'] = 'black_tophat'
320
+ cur_text, cur_mrz = new_text, new_mrz
321
+
322
+ new_text, new_mrz = self._try_larger_image(roi_b, cur_text, cur_mrz)
323
+ if new_mrz.valid_score > cur_mrz.valid_score:
324
+ new_mrz.aux['method'] = 'black_tophat(rescaled(3))'
325
+ cur_text, cur_mrz = new_text, new_mrz
326
+
327
+ return cur_text, cur_mrz
328
+
329
+
330
+ class TryOtherMaxWidth(object):
331
+ """
332
+ If mrz was not found so far in the current pipeline,
333
+ changes the max_width parameter of the scaler to 1000 and reruns the pipeline again.
334
+ """
335
+
336
+ __provides__ = ['mrz_final']
337
+ __depends__ = ['mrz', '__pipeline__']
338
+
339
+ def __init__(self, other_max_width=1000):
340
+ self.other_max_width = other_max_width
341
+
342
+ def __call__(self, mrz, __pipeline__):
343
+ # We'll only try this if we see that img_binary.mean() is very small or img.mean() is very large (i.e. image is mostly white).
344
+ if mrz is None and (__pipeline__['img_binary'].mean() < 0.01 or __pipeline__['img'].mean() > 0.95):
345
+ __pipeline__.replace_component('scaler', Scaler(self.other_max_width))
346
+ new_mrz = __pipeline__['mrz']
347
+ if new_mrz is not None:
348
+ new_mrz.aux['method'] = new_mrz.aux['method'] + '|max_width(%d)' % self.other_max_width
349
+ mrz = new_mrz
350
+ return mrz
351
+
352
+
353
+ class MRZPipeline(Pipeline):
354
+ """This is the "currently best-performing" pipeline for parsing MRZ from a given image file."""
355
+
356
+ def __init__(self, file, extra_cmdline_params=''):
357
+ super(MRZPipeline, self).__init__()
358
+ self.version = '1.0' # In principle we might have different pipelines in use, so possible backward compatibility is an issue
359
+ self.file = file
360
+ self.add_component('loader', Loader(file))
361
+ self.add_component('scaler', Scaler())
362
+ self.add_component('boone', BooneTransform())
363
+ self.add_component('box_locator', MRZBoxLocator())
364
+ self.add_component('mrz', FindFirstValidMRZ(extra_cmdline_params=extra_cmdline_params))
365
+ self.add_component('other_max_width', TryOtherMaxWidth())
366
+
367
+ # Step used by extract_mrz_rois (not even invoked by the standard result method)
368
+ self.add_component('extractor', ExtractAllBoxes())
369
+
370
+ @property
371
+ def result(self):
372
+ return self['mrz_final']
373
+
374
+
375
+ def read_mrz(file, save_roi=False, extra_cmdline_params=''):
376
+ """The main interface function to this module, encapsulating the recognition pipeline.
377
+ Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
378
+
379
+ :param file: A filename or a stream to read the file data from.
380
+ :param save_roi: when this is True, the .aux['roi'] field will contain the Region of Interest where the MRZ was parsed from.
381
+ :param extra_cmdline_params:extra parameters to the ocr.py
382
+ """
383
+ p = MRZPipeline(file, extra_cmdline_params)
384
+ mrz = p.result
385
+ if mrz is not None and save_roi:
386
+ mrz.aux['roi'] = p['roi']
387
+ return mrz
@@ -0,0 +1,200 @@
1
+ '''
2
+ PassportEye::MRZ: Machine-readable zone extraction and parsing.
3
+ Command-line scripts
4
+
5
+ Author: Konstantin Tretyakov
6
+ License: MIT
7
+ '''
8
+ import argparse
9
+ import glob
10
+ import json
11
+ import logging
12
+ import multiprocessing
13
+ import os
14
+ import shutil
15
+ import sys
16
+ import time
17
+ from collections import Counter
18
+ from skimage import io
19
+ import numpy as np
20
+ from pytesseract.pytesseract import TesseractNotFoundError, TesseractError
21
+ import passporteye
22
+ from .image import read_mrz, MRZPipeline
23
+
24
+
25
+ def process_file(params):
26
+ """
27
+ Processes a file and returns the parsed MRZ (or None if no candidate regions were even found).
28
+
29
+ The input argument is a list (filename, save_roi, extra_params).
30
+ (Because we need to use this function within imap_unordered)
31
+ """
32
+ tic = time.time()
33
+ filename, save_roi, extra_params = params
34
+ result = read_mrz(filename, save_roi=save_roi, extra_cmdline_params=extra_params)
35
+ walltime = time.time() - tic
36
+ return (filename, result, walltime)
37
+
38
+
39
+ def evaluate_mrz():
40
+ """
41
+ A script for evaluating the current MRZ recognition pipeline by applying it to a list of files in a directory and reporting how well it went.
42
+ """
43
+ parser = argparse.ArgumentParser(description='Run the MRZ OCR recognition algorithm on the sample test data, reporting the quality summary.')
44
+ parser.add_argument('-j', '--jobs', default=1, type=int, help='Number of parallel jobs to run')
45
+ parser.add_argument('-dd', '--data-dir', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'testdata'),
46
+ help='Read files from this directory instead of the sample images (passporteye/mrz/testdata, '
47
+ 'only available when running from a source checkout of the repository)')
48
+ parser.add_argument('-sd', '--success-dir', default=None,
49
+ help='Copy files with successful (nonzero score) extraction results to this directory')
50
+ parser.add_argument('-fd', '--fail-dir', default=None,
51
+ help='Copy files with unsuccessful (zero score) extraction resutls to this directory')
52
+ parser.add_argument('-rd', '--roi-dir', default=None,
53
+ help='Extract ROIs to this directory')
54
+ parser.add_argument('-l', '--limit', default=-1, type=int, help='Only process the first <limit> files in the directory.')
55
+ parser.add_argument('--legacy', action='store_true',
56
+ help='Use the "legacy" Tesseract OCR engine (--oem 0). Despite the name, it most often results in better '
57
+ 'results. It is not the default option, because it will only work if '
58
+ 'your Tesseract installation includes the legacy *.traineddata files. You can download them at '
59
+ 'https://github.com/tesseract-ocr/tesseract/wiki/Data-Files#data-files-for-version-400-november-29-2016')
60
+ args = parser.parse_args()
61
+ files = sorted(glob.glob(os.path.join(args.data_dir, '*.*')))
62
+ if not files:
63
+ parser.error("No files found in %s. The sample images are only available when running from a source checkout "
64
+ "of the PassportEye repository (https://github.com/konstantint/PassportEye), they are not part of the "
65
+ "installed package. Use --data-dir to process another directory." % args.data_dir)
66
+ if args.limit >= 0:
67
+ files = files[0:args.limit]
68
+
69
+ logging.basicConfig(level=logging.INFO)
70
+ log = logging.getLogger("evaluate_mrz")
71
+
72
+ tic = time.time()
73
+ pool = multiprocessing.Pool(args.jobs)
74
+ log.info("Preparing computation for %d files from %s", len(files), args.data_dir)
75
+ log.info("Running %d workers", args.jobs)
76
+ results = []
77
+ save_roi = args.roi_dir is not None
78
+ for d in [args.success_dir, args.fail_dir, args.roi_dir]:
79
+ if d is not None and not os.path.isdir(d):
80
+ os.mkdir(d)
81
+
82
+ def valid_score(mrz_):
83
+ return 0 if mrz_ is None else mrz_.valid_score
84
+
85
+ def score_change_type(filename, mrz_):
86
+ try:
87
+ new_score = valid_score(mrz_)
88
+ old_score = int(os.path.basename(filename).split('_')[0])
89
+ schange = new_score - old_score
90
+ return '=' if schange == 0 else ('>' if schange > 0 else '<')
91
+ except Exception:
92
+ return '?'
93
+
94
+ method_stats = Counter()
95
+
96
+ extra_params = '--oem 0' if args.legacy else ''
97
+ for result in pool.imap_unordered(process_file, [(f, save_roi, extra_params) for f in files]):
98
+ filename, mrz_, walltime = result
99
+ results.append(result)
100
+ log.info("Processed %s in %0.2fs (score %d) [%s]", os.path.basename(filename), walltime, valid_score(mrz_), score_change_type(filename, mrz_))
101
+ log.debug("\t%s", mrz_)
102
+
103
+ vs = valid_score(mrz_)
104
+ if args.success_dir is not None and vs > 0:
105
+ shutil.copyfile(filename, os.path.join(args.success_dir, '%d_%s' % (vs, os.path.basename(filename))))
106
+ if args.fail_dir is not None and vs == 0:
107
+ shutil.copyfile(filename, os.path.join(args.fail_dir, '%d_%s' % (vs, os.path.basename(filename))))
108
+ if args.roi_dir is not None and mrz_ is not None and 'roi' in mrz_.aux:
109
+ roi_fn = '%d_roi_%s.png' % (vs, os.path.basename(filename))
110
+ io.imsave(os.path.join(args.roi_dir, roi_fn), mrz_.aux['roi'])
111
+
112
+ if vs > 0 and 'method' in mrz_.aux:
113
+ method_stats[mrz_.aux['method']] += 1
114
+
115
+ num_files = len(results)
116
+ score_changes = [score_change_type(fn, mrz_) for fn, mrz_, wt in results]
117
+ scores = [valid_score(mrz_) for fn, mrz_, wt in results]
118
+ num_perfect = scores.count(100)
119
+ num_invalid = scores.count(0)
120
+ total_score = sum(scores)
121
+ total_computation_walltime = sum([wt for fn, mrz_, wt in results])
122
+ total_walltime = time.time() - tic
123
+ log.info("Completed")
124
+ print("Walltime: %0.2fs" % total_walltime)
125
+ print("Compute walltime: %0.2fs" % total_computation_walltime)
126
+ print("Processed files: %d" % num_files)
127
+ print("Perfect parses: %d" % num_perfect)
128
+ print("Invalid parses: %d" % num_invalid)
129
+ print("Improved parses: %d" % len([x for x in score_changes if x == '>']))
130
+ print("Worsened parses: %d" % len([x for x in score_changes if x == '<']))
131
+ print("Total score: %d" % total_score)
132
+ print("Mean score: %0.2f" % (float(total_score)/num_files))
133
+ print("Mean compute time: %0.2fs" % (total_computation_walltime/num_files))
134
+ print("Methods used:")
135
+ for stat in method_stats.most_common():
136
+ print(" %s: %d" % stat)
137
+
138
+
139
+ def mrz():
140
+ """
141
+ Command-line script for extracting MRZ from a given image
142
+ """
143
+ parser = argparse.ArgumentParser(description='Run the MRZ OCR recognition algorithm on the given image.')
144
+ parser.add_argument('filename')
145
+ parser.add_argument('--json', action='store_true', help='Produce JSON (rather than tabular) output')
146
+ parser.add_argument('--legacy', action='store_true',
147
+ help='Use the "legacy" Tesseract OCR engine (--oem 0). Despite the name, it most often results in better '
148
+ 'results. It is not the default option, because it will only work if '
149
+ 'your Tesseract installation includes the legacy *.traineddata files. You can download them at '
150
+ 'https://github.com/tesseract-ocr/tesseract/wiki/Data-Files#data-files-for-version-400-november-29-2016')
151
+ parser.add_argument('-r', '--save-roi', default=None,
152
+ help='Output the region of the image that is detected to contain the MRZ to the given png file.')
153
+ parser.add_argument('--version', action='version', version='PassportEye MRZ v%s' % passporteye.__version__)
154
+ args = parser.parse_args()
155
+
156
+ try:
157
+ extra_params = '--oem 0' if args.legacy else ''
158
+ filename, mrz_, walltime = process_file((args.filename, args.save_roi is not None, extra_params))
159
+ except TesseractNotFoundError:
160
+ sys.stderr.write("ERROR: The tesseract executable was not found.\n"
161
+ "Please, make sure Tesseract is installed and the appropriate directory is included "
162
+ "in your PATH environment variable.\n")
163
+ sys.exit(1)
164
+ except TesseractError as ex:
165
+ sys.stderr.write("ERROR: %s" % ex.message)
166
+ sys.exit(ex.status)
167
+
168
+ d = mrz_.to_dict() if mrz_ is not None else {'mrz_type': None, 'valid': False, 'valid_score': 0}
169
+ d['walltime'] = walltime
170
+ d['filename'] = filename
171
+
172
+ if args.save_roi is not None and mrz_ is not None and 'roi' in mrz_.aux:
173
+ io.imsave(args.save_roi, (mrz_.aux['roi'] * 255).astype(np.uint8))
174
+
175
+ if not args.json:
176
+ for k in d:
177
+ print("%s\t%s" % (k, str(d[k]).replace('\n', ' ')))
178
+ else:
179
+ print(json.dumps(d, indent=2))
180
+
181
+
182
+ def extract_mrz_rois():
183
+ """
184
+ Command-line script for extracting all potential MRZ regions from a given image as images
185
+ """
186
+ parser = argparse.ArgumentParser(description='Extract all potential MRZ regions from a given image and output as individual PNG files.')
187
+ parser.add_argument('filename')
188
+ parser.add_argument('-d', '--output-dir', default='.',
189
+ help='The directory where the images for the potential MRZ regions will be output (default is the current directory). '
190
+ 'The files created will be named 1.png, 2.png, ...')
191
+ parser.add_argument('-c', '--create-dir', action='store_true', help='Force the creation of the directory (and all parents) if it does not exist.')
192
+ parser.add_argument('--version', action='version', version='PassprtEye extract_mrz_rois v%s' % passporteye.__version__)
193
+ args = parser.parse_args()
194
+
195
+ rois = MRZPipeline(args.filename)['rois']
196
+ if args.create_dir:
197
+ os.makedirs(args.output_dir, exist_ok=True)
198
+
199
+ for n, img in enumerate(rois, 1):
200
+ io.imsave(os.path.join(args.output_dir, '%d.png' % n), (img * 255).astype(np.uint8))