Shows the face recognition results visually.

    :param img_path: path to image to be recognized
    :param predictions: results of the predict function
    :return:
768625
def show_prediction_labels_on_image(img_path, predictions):
    
    pil_image = Image.open(img_path).convert("RGB")
    draw = ImageDraw.Draw(pil_image)

    for name, (top, right, bottom, left) in predictions:
        # Draw a box around the face using the Pillow module
        draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255))

        # There's a bug in Pillow where it blows up with non-UTF-8 text
        # when using the default bitmap font
        name = name.encode("UTF-8")

        # Draw a label with a name below the face
        text_width, text_height = draw.textsize(name)
        draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 255), outline=(0, 0, 255))
        draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255))

    # Remove the drawing library from memory as per the Pillow docs
    del draw

    # Display the resulting image
    pil_image.show()
157545
def averageSameExpTimes(imgs_path):
    '''
    
    '''
    firsts = imgs_path[:2]
    imgs = imgs_path[2:]
    for n, i in enumerate(firsts):
        firsts[n] = np.asfarray(imread(i))
    d = DarkCurrentMap(firsts)
    for i in imgs:
        i = imread(i)
        d.addImg(i)
    return d.map()
266403
def predict(self, predictdata: np.ndarray) -> np.ndarray:
        
        return self.clf.predict(predictdata)
145591
def fetch_image(self, path, dest, user='root'):
        
        self.run('test -f %s || curl -L -s -o %s %s' % (dest, dest, path),
                 user=user, ignore_error=True)
535144
def save(path, im):
    
    from PIL import Image
    if im.dtype == np.uint8:
        pil_im = Image.fromarray(im)
    else:
        pil_im = Image.fromarray((im*255).astype(np.uint8))
    pil_im.save(path)
451047
def verify_images(path:PathOrStr, delete:bool=True, max_workers:int=4, max_size:Union[int]=None, recurse:bool=False,
                  dest:PathOrStr='.', n_channels:int=3, interp=PIL.Image.BILINEAR, ext:str=None, img_format:str=None,
                  resume:bool=None, **kwargs):
    ""
    path = Path(path)
    if resume is None and dest == '.': resume=False
    dest = path/Path(dest)
    os.makedirs(dest, exist_ok=True)
    files = get_image_files(path, recurse=recurse)
    func = partial(verify_image, delete=delete, max_size=max_size, dest=dest, n_channels=n_channels, interp=interp,
                   ext=ext, img_format=img_format, resume=resume, **kwargs)
    parallel(func, files, max_workers=max_workers)
595229
def apply_inference_graph(model_path):
    
    pred_config = PredictConfig(
        session_init=get_model_loader(model_path),
        model=InferenceOnlyModel(),
        input_names=['input_img_bytes'],
        output_names=['prediction_img_bytes'])

    pred = OfflinePredictor(pred_config)
    buf = open('lena.png', 'rb').read()
    prediction = pred([buf])[0]
    with open('applied_inference_graph.png', 'wb') as f:
        f.write(prediction[0])
1000538
def process_prediction_results(results, show_image):
  """"""

  import pandas as pd

  if (is_in_IPython() and show_image is True):
    import IPython
    for image_url, image, label_and_score in results:
      IPython.display.display_html('<p style="font-size:28px">%s(%.5f)</p>' % label_and_score,
                                   raw=True)
      IPython.display.display(IPython.display.Image(data=image))
  result_dict = [{'image_url': url, 'label': r[0], 'score': r[1]} for url, _, r in results]
  return pd.DataFrame(result_dict)
673202
def model_from_path(model_path, fuzziness=False):
    
    app_name = '.'.join(model_path.split('.')[:-1])
    model_name = model_path.split('.')[-1]

    if not app_name:
        return None

    module = importlib.import_module(app_name)
    try:
        model = getattr(module, model_name)
    except AttributeError:
        try:
            model = getattr(getattr(module, 'models'), model_name)
        except AttributeError:
            model = get_model(model_name, app_name, fuzziness=fuzziness)

    return model
874395
def image_list(name=None, profile=None, **kwargs):
    '''
    
    '''
    conn = _auth(profile, **kwargs)
    return conn.image_list(name)
1034092
def do_visualize(model, model_path, nr_visualize=100, output_dir='output'):
    
    df = get_train_dataflow()   # we don't visualize mask stuff
    df.reset_state()

    pred = OfflinePredictor(PredictConfig(
        model=model,
        session_init=get_model_loader(model_path),
        input_names=['image', 'gt_boxes', 'gt_labels'],
        output_names=[
            'generate_{}_proposals/boxes'.format('fpn' if cfg.MODE_FPN else 'rpn'),
            'generate_{}_proposals/scores'.format('fpn' if cfg.MODE_FPN else 'rpn'),
            'fastrcnn_all_scores',
            'output/boxes',
            'output/scores',
            'output/labels',
        ]))

    if os.path.isdir(output_dir):
        shutil.rmtree(output_dir)
    utils.fs.mkdir_p(output_dir)
    with tqdm.tqdm(total=nr_visualize) as pbar:
        for idx, dp in itertools.islice(enumerate(df), nr_visualize):
            img, gt_boxes, gt_labels = dp['image'], dp['gt_boxes'], dp['gt_labels']

            rpn_boxes, rpn_scores, all_scores, \
                final_boxes, final_scores, final_labels = pred(img, gt_boxes, gt_labels)

            # draw groundtruth boxes
            gt_viz = draw_annotation(img, gt_boxes, gt_labels)
            # draw best proposals for each groundtruth, to show recall
            proposal_viz, good_proposals_ind = draw_proposal_recall(img, rpn_boxes, rpn_scores, gt_boxes)
            # draw the scores for the above proposals
            score_viz = draw_predictions(img, rpn_boxes[good_proposals_ind], all_scores[good_proposals_ind])

            results = [DetectionResult(*args) for args in
                       zip(final_boxes, final_scores, final_labels,
                           [None] * len(final_labels))]
            final_viz = draw_final_outputs(img, results)

            viz = tpviz.stack_patches([
                gt_viz, proposal_viz,
                score_viz, final_viz], 2, 2)

            if os.environ.get('DISPLAY', None):
                tpviz.interactive_imshow(viz)
            cv2.imwrite("{}/{:03d}.png".format(output_dir, idx), viz)
            pbar.update()
1372570
def from_image_to_file(img_path, file_path):
    
    img = Image.open(img_path)
    data = numpy.array(img)
    data = numpy.reshape(data, len(img.getdata()) * 3)
    to_remove = data[len(data) - 1]
    data = numpy.delete(data, xrange(len(data) - to_remove, len(data)))
    data.tofile(file_path)
494632
function predict(face) {
      return getNet().computeFaceDescriptorAsync(face)
        .then(inputDescriptor =>
          getDescriptorsByClass().map(ds => ({
            className: ds.className,
            distance: computeMeanDistance(ds.faceDescriptors, inputDescriptor)
          }))
        )
    }
1128154
def fitImg(self, img_rgb):
        '''
        
        '''
        H = self.pattern.findHomography(img_rgb)[0]
        H_inv = self.pattern.invertHomography(H)
        s = self.img_orig.shape
        warped = cv2.warpPerspective(img_rgb, H_inv, (s[1], s[0]))
        return warped
166590
def predict(model_dir, image_files, resize, show_image):
    """"""

    from . import _predictor

    images = _util.load_images(image_files, resize=resize)
    labels_and_scores = _predictor.predict(model_dir, images)
    results = zip(image_files, images, labels_and_scores)
    ret = _util.process_prediction_results(results, show_image)
    return ret
1296534
def to_dict(self, img_sets):
        
        # Get the basic Json object from the super class
        json_obj = super(DefaultPredictionImageSetManager, self).to_dict(img_sets)
        # Add list of image sets as Json array
        json_obj['images'] = [img_set.to_dict() for img_set in img_sets.images]
        return json_obj
1256062
function predictBest(face, unknownThreshold = 0) {
      return predict(face)
        .then(predictions => getBestPrediction(predictions, unknownThreshold))
    }