Command-line script for extracting MRZ from a given image
480765
def mrz():
    
    parser = argparse.ArgumentParser(description='Run the MRZ OCR recognition algorithm on the given image.')
    parser.add_argument('filename')
    parser.add_argument('--json', action='store_true', help='Produce JSON (rather than tabular) output')
    parser.add_argument('--legacy', action='store_true',
                        help='Use the "legacy" Tesseract OCR engine (--oem 0). Despite the name, it most often results in better '
                        'results. It is not the default option, because it will only work if '
                        'your Tesseract installation includes the legacy *.traineddata files. You can download them at '
                        'https://github.com/tesseract-ocr/tesseract/wiki/Data-Files#data-files-for-version-400-november-29-2016')
    parser.add_argument('-r', '--save-roi', default=None,
                        help='Output the region of the image that is detected to contain the MRZ to the given png file')
    parser.add_argument('--version', action='version', version='PassportEye MRZ v%s' % passporteye.__version__)
    args = parser.parse_args()

    try:
        extra_params = '--oem 0' if args.legacy else ''
        filename, mrz_, walltime = process_file((args.filename, args.save_roi is not None, extra_params))
    except TesseractNotFoundError:
        sys.stderr.write("ERROR: The tesseract executable was not found.\n"
                         "Please, make sure Tesseract is installed and the appropriate directory is included "
                         "in your PATH environment variable.\n")
        sys.exit(1)
    except TesseractError as ex:
        sys.stderr.write("ERROR: %s" % ex.message)
        sys.exit(ex.status)
    
    d = mrz_.to_dict() if mrz_ is not None else {'mrz_type': None, 'valid': False, 'valid_score': 0}
    d['walltime'] = walltime
    d['filename'] = filename

    if args.save_roi is not None and mrz_ is not None and 'roi' in mrz_.aux:
        io.imsave(args.save_roi, mrz_.aux['roi'])

    if not args.json:
        for k in d:
            print("%s\t%s" % (k, str(d[k])))
    else:
        print(json.dumps(d, indent=2))
443259
def cmd_filter(args):
    
    check_output_format(args.output, args.count)

    img = Image.open(args.input)
    width, height = img.size

    if args.state is not None:
        markov = load(MarkovImage, args.state, args)
    else:
        args.state = ()
        if args.type == JSON:
            storage = JsonStorage(settings=args.settings)
        else:
            storage = SqliteStorage(settings=args.settings)
        markov = MarkovImage.from_storage(storage)
        read([args.input], markov, args.progress, False)

    args.level = min(args.level, markov.levels - 1) - 1

    if args.level < 0:
        args.level = -1
        scale = markov.scanner.min_size
        width, height = width // scale, height // scale
        start = None
    else:
        scale = reduce(
            lambda x, y: x * y,
            islice(markov.scanner.level_scale, args.level, markov.levels),
            1
        )
        width, height = width // scale, height // scale
        start = img.resize((width, height), markov.scanner.scale)

    for fname in outfiles(markov, args.output,
                          args.count, args.progress, args.level + 1):
        img = markov(
            width, height,
            state_size=args.state_size,
            start_level=args.level,
            start_image=start
        )
        save_image(img, fname)
228016
def extract_xz(archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    return _extract(archive, compression, cmd, 'xz', verbosity, outdir)
317876
def _extract_mnist_images(filename, num_images):
  
  with gzip.open(filename) as bytestream:
    bytestream.read(16)
    buf = bytestream.read(_MNIST_IMAGE_SIZE * _MNIST_IMAGE_SIZE * num_images)
    data = np.frombuffer(buf, dtype=np.uint8)
    data = data.reshape(num_images, _MNIST_IMAGE_SIZE, _MNIST_IMAGE_SIZE, 1)
  return data
862818
def getParser():
    ""
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=__description__)
    parser.add_argument('input', help='the input image')
    parser.add_argument('output', help='the output image')
    parser.add_argument('shape', type=argparseu.sequenceOfIntegersGt, help='the desired shape in colon-separated values, e.g. 255,255,32')

    parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', help='verbose output')
    parser.add_argument('-d', dest='debug', action='store_true', help='Display debug information.')
    parser.add_argument('-f', '--force', dest='force', action='store_true', help='overwrite existing files')
    return parser
785699
def tenengrad(img, ksize=3):
    '''''''
    Gx = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=ksize)
    Gy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=ksize)
    FM = Gx*Gx + Gy*Gy
    mn = cv2.mean(FM)[0]
    if np.isnan(mn):
        return np.nanmean(FM)
    return mn
169324
def parse_md_to_rst(file):
    """"""
    try:
        from m2r import parse_from_file
        return parse_from_file(file).replace(
            "artwork/", "http://198.27.119.65/"
        )
    except ImportError:
        # m2r may not be installed in user environment
        return read(file)
904406
private void extractImageFeatures(final ProgressMonitor progressMonitor, final int progress,
									  T image,
									  List<TupleDesc> descs, List<Point2D_F64> locs) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				progressMonitor.setNote("Detecting");
			}
		});
		detector.detect(image);
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				progressMonitor.setProgress(progress + 1);
				progressMonitor.setNote("Describing");
			}
		});
		describe.setImage(image);
		orientation.setImage(image);

		// See if the detector can detect the feature's scale
		if (detector.hasScale()) {
			for (int i = 0; i < detector.getNumberOfFeatures(); i++) {
				double yaw = 0;

				Point2D_F64 pt = detector.getLocation(i);
				double radius = detector.getRadius(i);
				if (describe.requiresOrientation()) {
					orientation.setObjectRadius(radius);
					yaw = orientation.compute(pt.x, pt.y);
				}

				TupleDesc d = describe.createDescription();
				if ( describe.process(pt.x, pt.y, yaw, radius, d) ) {
					descs.add(d);
					locs.add(pt.copy());
				}
			}
		} else {
			// just set the radius to one in this case
			orientation.setObjectRadius(1);
			for (int i = 0; i < detector.getNumberOfFeatures(); i++) {
				double yaw = 0;

				Point2D_F64 pt = detector.getLocation(i);
				if (describe.requiresOrientation()) {
					yaw = orientation.compute(pt.x, pt.y);
				}

				TupleDesc d = describe.createDescription();
				if (describe.process(pt.x, pt.y, yaw, 1, d)) {
					descs.add(d);
					locs.add(pt.copy());
				}
			}
		}
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				progressMonitor.setProgress(progress + 2);
			}
		});
	}
1054963
def extract_dms (archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    check_archive_ext(archive)
    cmdlist = [cmd, '-d', outdir]
    if verbosity > 1:
        cmdlist.append('-v')
    cmdlist.extend(['u', archive])
    return cmdlist
790645
def _findObject(self, img):
        '''
        
        '''
        from imgProcessor.imgSignal import signalMinimum
        # img is scaled already
        i = img > signalMinimum(img)  # img.max()/2.5
        # filter noise, single-time-effects etc. from mask:
        i = minimum_filter(i, 4)
        return boundingBox(i)
721007
def extract_colors(
        filename_or_img, min_saturation=config.MIN_SATURATION,
        min_distance=config.MIN_DISTANCE, max_colors=config.MAX_COLORS,
        min_prominence=config.MIN_PROMINENCE, n_quantized=config.N_QUANTIZED):
    
    if Image.isImageType(filename_or_img):
        im = filename_or_img
    else:
        im = Image.open(filename_or_img)

    # get point color count
    if im.mode != 'RGB':
        im = im.convert('RGB')
    im = autocrop(im, config.WHITE)  # assume white box
    im = im.convert(
        'P', palette=Image.ADAPTIVE, colors=n_quantized).convert('RGB')
    dist = Counter({color: count for count, color
                    in im.getcolors(n_quantized)})
    n_pixels = mul(*im.size)

    # aggregate colors
    to_canonical = {config.WHITE: config.WHITE, config.BLACK: config.BLACK}
    aggregated = Counter({config.WHITE: 0, config.BLACK: 0})
    sorted_cols = sorted(dist.items(), key=itemgetter(1), reverse=True)
    for c, n in sorted_cols:
        if c in aggregated:
            # exact match!
            aggregated[c] += n
        else:
            d, nearest = min((distance(c, alt), alt) for alt in aggregated)
            if d < min_distance:
                # nearby match
                aggregated[nearest] += n
                to_canonical[c] = nearest
            else:
                # no nearby match
                aggregated[c] = n
                to_canonical[c] = c

    # order by prominence
    colors = sorted(
        [Color(c, n / float(n_pixels)) for c, n in aggregated.items()],
        key=attrgetter('prominence'), reverse=True)

    colors, bg_color = detect_background(im, colors, to_canonical)

    # keep any color which meets the minimum saturation
    sat_colors = [c for c in colors if meets_min_saturation(c, min_saturation)]
    if bg_color and not meets_min_saturation(bg_color, min_saturation):
        bg_color = None
    if sat_colors:
        colors = sat_colors
    else:
        # keep at least one color
        colors = colors[:1]

    # keep any color within 10% of the majority color
    color_list = []
    color_count = 0

    for color in colors:
        if color.prominence >= colors[0].prominence * min_prominence:
            color_list.append(color)
            color_count += 1

        if color_count >= max_colors:
            break

    return Palette(color_list, bg_color)
1172203
def _compute_zs_mat(sz:TensorImageSize, scale:float, squish:float,
                   invert:bool, row_pct:float, col_pct:float)->AffineMatrix:
    ""
    orig_ratio = math.sqrt(sz[1]/sz[0])
    for s,r,i in zip(scale,squish, invert):
        s,r = 1/math.sqrt(s),math.sqrt(r)
        if s * r <= 1 and s / r <= 1: #Test if we are completely inside the picture
            w,h = (s/r, s*r) if i else (s*r,s/r)
            col_c = (1-w) * (2*col_pct - 1)
            row_c = (1-h) * (2*row_pct - 1)
            return _get_zoom_mat(w, h, col_c, row_c)

    #Fallback, hack to emulate a center crop without cropping anything yet.
    if orig_ratio > 1: return _get_zoom_mat(1/orig_ratio**2, 1, 0, 0.)
    else:              return _get_zoom_mat(1, orig_ratio**2, 0, 0.)
901735
def process_file(params):
    
    tic = time.time()
    filename, save_roi, extra_params = params
    result = read_mrz(filename, save_roi=save_roi, extra_cmdline_params=extra_params)
    walltime = time.time() - tic
    return (filename, result, walltime)
238297
def decompress(self, image_path, quiet=True):
    ''''''

    if not os.path.exists(image_path):
        bot.exit("Cannot find image %s" %image_path)
        
    extracted_file = image_path.replace('.gz','')
    cmd = ['gzip','-d','-f', image_path]
    result = self.run_command(cmd, quiet=quiet) # exits if return code != 0
    return extracted_file
154267
def get_extract_command_template(filename):
  """"""
  for k, v in iteritems(EXTRACT_COMMAND):
    if filename.endswith(k):
      return v
  return None
1006591
def sed2(img, contour=None, shape=[3, 4]):
    
    """
    :param img:
    :param contour:
    :param shape:
    :return:
    """

    plt.imshow(slices(img, shape), cmap='gray')
    if contour is not None:
        plt.contour(slices(contour, shape))
1230119
def _from_p(self, mode):
        """"""
        self._check_modes(("P", "PA"))

        if not self.palette:
            raise RuntimeError("Can't convert palettized image, missing palette.")
        pal = np.array(self.palette)
        pal = da.from_array(pal, chunks=pal.shape)

        if pal.shape[1] == 4:
            # colormap's alpha overrides data alpha
            mode = "RGBA"
            alpha = None
        elif self.mode.endswith("A"):
            # add a new/fake 'bands' dimension to the end
            alpha = self.data.sel(bands="A").data[..., None]
            mode = mode + "A" if not mode.endswith("A") else mode
        else:
            alpha = None

        flat_indexes = self.data.sel(bands='P').data.ravel().astype('int64')
        dim_sizes = ((key, val) for key, val in self.data.sizes.items() if key != 'bands')
        dims, new_shape = zip(*dim_sizes)
        dims = dims + ('bands',)
        new_shape = new_shape + (pal.shape[1],)
        new_data = pal[flat_indexes].reshape(new_shape)
        coords = dict(self.data.coords)
        coords["bands"] = list(mode)

        if alpha is not None:
            new_arr = da.concatenate((new_data, alpha), axis=-1)
            data = xr.DataArray(new_arr, coords=coords, attrs=self.data.attrs, dims=dims)
        else:
            data = xr.DataArray(new_data, coords=coords, attrs=self.data.attrs, dims=dims)

        return data