def __init__(self, ie, model_path, device='CPU', max_reqs=100):
     self.max_reqs = max_reqs
     self.net = load_ie_model(ie,
                              model_path,
                              device,
                              None,
                              num_reqs=self.max_reqs)
Exemple #2
0
    def __init__(self,
                 ie,
                 model_path,
                 trg_classes,
                 conf=.6,
                 device='CPU',
                 ext_path='',
                 max_reqs=100):
        self.trg_classes = trg_classes
        self.max_reqs = max_reqs
        self.confidence = conf
        self.net = load_ie_model(ie,
                                 model_path,
                                 device,
                                 None,
                                 ext_path,
                                 num_reqs=self.max_reqs)

        required_input_keys = [{'im_info', 'im_data'}, {'im_data', 'im_info'}]
        current_input_keys = self.net.input_info.keys()
        assert current_input_keys in required_input_keys
        required_output_keys = {'boxes', 'scores', 'classes', 'raw_masks'}
        assert required_output_keys.issubset(self.net.net.outputs)

        self.n, self.c, self.h, self.w = self.net.input_info[
            'im_data'].input_data.shape
        assert self.n == 1, 'Only batch 1 is supported.'
 def __init__(self, ie, model_path, trg_classes, conf=.6,
              device='CPU', ext_path='', max_num_frames=1):
     self.net = load_ie_model(ie, model_path, device, None, ext_path, num_reqs=max_num_frames)
     self.trg_classes = trg_classes
     self.confidence = conf
     self.expand_ratio = (1., 1.)
     self.max_num_frames = max_num_frames
 def __init__(self,
              ie,
              model_path,
              device='CPU',
              ext_path='',
              max_reqs=100):
     self.max_reqs = max_reqs
     self.net = load_ie_model(ie,
                              model_path,
                              device,
                              None,
                              'Object Reidentification',
                              ext_path,
                              num_reqs=self.max_reqs)
def main():
    args = parse_args()

    test_db = load_eye_db(args.data_root)
    net = load_ie_model(args.model, 'CPU', None)
    _, _, height, width = net.get_input_shape().shape

    for sample in test_db:
        img = cv.imread(sample['filename'])
        assert not img is None
        h, w, _ = img.shape
        out = net.forward(cv.resize(img, (width, height)))
        is_open = out[0][0][0][0] < out[0][1][0][0]
        if is_open:
            cv.rectangle(img, (1, 1), (w - 1, h - 1), (0, 255, 0), 2)
        else:
            cv.rectangle(img, (1, 1), (w - 1, h - 1), (0, 0, 255), 2)
        cv.imshow("Eye", img)
        cv.waitKey(0)
    def __init__(self,
                 ie,
                 model_path,
                 trg_classes,
                 conf=.6,
                 device='CPU',
                 ext_path='',
                 max_reqs=100):
        self.trg_classes = trg_classes
        self.max_reqs = max_reqs
        self.confidence = conf
        self.net = load_ie_model(ie,
                                 model_path,
                                 device,
                                 None,
                                 'Instance Segmentation',
                                 ext_path,
                                 num_reqs=self.max_reqs)

        required_input_keys = {'image'}
        required_output_keys = {'boxes', 'labels', 'masks'}

        required_input_keys_segmentoly = {'im_info', 'im_data'}
        required_output_keys_segmentoly = {
            'boxes', 'scores', 'classes', 'raw_masks'
        }

        current_input_keys = self.net.inputs_info.keys()

        assert (current_input_keys == required_input_keys and
                required_output_keys.issubset(self.net.net.outputs)) or \
               (current_input_keys == required_input_keys_segmentoly and
                required_output_keys_segmentoly.issubset(self.net.net.outputs))

        self.segmentoly_type = self.check_segmentoly_type()
        input_name = 'im_data' if self.segmentoly_type else 'image'
        self.n, self.c, self.h, self.w = self.net.inputs_info[
            input_name].input_data.shape
        assert self.n == 1, 'Only batch 1 is supported.'
def main():
    parser = argparse.ArgumentParser(
        description='Evaluation script for Face Recognition in PyTorch')
    parser.add_argument('--devices',
                        type=int,
                        nargs='+',
                        default=[0],
                        help='CUDA devices to use.')
    parser.add_argument('--embed_size',
                        type=int,
                        default=128,
                        help='Size of the face embedding.')
    parser.add_argument('--val_data_root',
                        dest='val',
                        required=True,
                        type=str,
                        help='Path to validation data.')
    parser.add_argument('--val_list',
                        dest='v_list',
                        required=True,
                        type=str,
                        help='Path to train data image list.')
    parser.add_argument('--val_landmarks',
                        dest='v_land',
                        default='',
                        required=False,
                        type=str,
                        help='Path to landmarks for the test images.')
    parser.add_argument('--val_batch_size',
                        type=int,
                        default=8,
                        help='Validation batch size.')
    parser.add_argument('--snap',
                        type=str,
                        required=False,
                        help='Snapshot to evaluate.')
    parser.add_argument('--roc_fname', type=str, default='', help='ROC file.')
    parser.add_argument('--dump_embeddings',
                        action='store_true',
                        help='Dump embeddings to summary writer.')
    parser.add_argument('--dist',
                        choices=['l2', 'cos'],
                        type=str,
                        default='cos',
                        help='Distance.')
    parser.add_argument('--flipped_emb',
                        action='store_true',
                        help='Flipped embedding concatenation trick.')
    parser.add_argument('--show_failed',
                        action='store_true',
                        help='Show misclassified pairs.')
    parser.add_argument('--model',
                        choices=models_backbones.keys(),
                        type=str,
                        default='rmnet',
                        help='Model type.')
    parser.add_argument('--engine',
                        choices=['pt', 'ie'],
                        type=str,
                        default='pt',
                        help='Framework to use for eval.')

    # IE-related options
    parser.add_argument('--fr_model', type=str, required=False)
    parser.add_argument('--lm_model', type=str, required=False)
    parser.add_argument('-pp',
                        '--plugin_dir',
                        type=str,
                        default=None,
                        help='Path to a plugin folder')
    args = parser.parse_args()

    if args.engine == 'pt':
        assert args.snap is not None, 'To evaluate PyTorch snapshot, please, specify --snap option.'
        with torch.cuda.device(args.devices[0]):
            data, embeddings_fun = load_test_dataset(args)
            model = models_backbones[args.model](
                embedding_size=args.embed_size, feature=True)
            model = load_model_state(model, args.snap, args.devices[0])
            evaluate(args, data, model, embeddings_fun, args.val_batch_size,
                     args.dump_embeddings, args.roc_fname, args.snap, True,
                     args.show_failed)
    else:
        from utils.ie_tools import load_ie_model

        assert args.fr_model is not None, 'To evaluate IE model, please, specify --fr_model option.'
        fr_model = load_ie_model(args.fr_model, 'CPU', args.plugin_dir)
        lm_model = None
        if args.lm_model:
            lm_model = load_ie_model(args.lm_model, 'CPU', args.plugin_dir)
        input_size = tuple(fr_model.get_input_shape()[2:])

        lfw = LFW(args.val, args.v_list, args.v_land)
        if not lfw.use_landmarks or lm_model:
            lfw.transform = t.Compose(
                [ResizeNumpy(220),
                 CenterCropNumpy(input_size)])
            lfw.use_landmarks = False
        else:
            log.info('Using landmarks for the LFW images.')
            lfw.transform = t.Compose([ResizeNumpy(input_size)])

        evaluate(args,
                 lfw,
                 fr_model,
                 partial(compute_embeddings_lfw_ie, lm_model=lm_model),
                 val_batch_size=1,
                 dump_embeddings=False,
                 roc_fname='',
                 snap_name='',
                 verbose=True,
                 show_failed=False)
Exemple #8
0
 def __init__(self, model_path, device='CPU'):
     self.net = load_ie_model(model_path, device, None)
Exemple #9
0
 def __init__(self, model_path, conf=.6, device='CPU', ext_path=''):
     self.net = load_ie_model(model_path, device, None, ext_path)
     self.confidence = conf
     self.expand_ratio = (1.1, 1.05)
Exemple #10
0
def main():
    """Runs the accuracy check"""
    parser = argparse.ArgumentParser(
        description='Accuracy check script (pt vs caffe)')
    parser.add_argument('--embed_size',
                        type=int,
                        default=128,
                        help='Size of the face embedding.')
    parser.add_argument('--snap',
                        type=str,
                        required=True,
                        help='Snapshot to convert.')
    parser.add_argument('--device',
                        '-d',
                        default=0,
                        type=int,
                        help='Device for model placement.')
    parser.add_argument('--model',
                        choices=list(models_backbones.keys()) +
                        list(models_landmarks.keys()),
                        type=str,
                        default='rmnet')

    # IE-related options
    parser.add_argument('--ie_model', type=str, required=True)
    parser.add_argument(
        "-l",
        "--cpu_extension",
        help=
        "MKLDNN (CPU)-targeted custom layers.Absolute path to a shared library with the kernels "
        "impl.",
        type=str,
        default=None)
    parser.add_argument("-pp",
                        "--plugin_dir",
                        help="Path to a plugin folder",
                        type=str,
                        default=None)
    parser.add_argument(
        "-d_ie",
        "--device_ie",
        help=
        "Specify the target device to infer on; CPU, GPU, FPGA or MYRIAD is acceptable. Sample "
        "will look for a suitable plugin for device specified (CPU by default)",
        default="CPU",
        type=str)

    args = parser.parse_args()

    max_err = 0.
    with torch.cuda.device(args.device):
        if args.model in models_landmarks.keys():
            pt_model = models_landmarks[args.model]
        else:
            pt_model = models_backbones[args.model](
                embedding_size=args.embed_size, feature=True)
        pt_model = load_model_state(pt_model, args.snap, args.device)

        ie_model = load_ie_model(args.ie_model, args.device_ie,
                                 args.plugin_dir, args.cpu_extension)
        np.random.seed(0)

        for _ in tqdm(range(100)):
            input_img = np.random.randint(0,
                                          high=255,
                                          size=(*pt_model.get_input_res(), 3),
                                          dtype=np.uint8)
            input_bgr = cv.cvtColor(input_img, cv.COLOR_BGR2RGB)

            input_pt = torch.unsqueeze(torch.from_numpy(
                input_img.transpose(2, 0, 1).astype('float32') / 255.).cuda(),
                                       dim=0)
            pt_output = (pt_model(input_pt)).data.cpu().numpy().reshape(1, -1)
            ie_output = ie_model.forward(input_bgr).reshape(1, -1)

            max_err = max(np.linalg.norm(pt_output - ie_output, np.inf),
                          max_err)

    log.info('Max l_inf error: %e', max_err)