コード例 #1
0
def main(config):
    rec_predictor = RecPredictor(config)
    image_list = get_image_list(config["Global"]["infer_imgs"])

    batch_imgs = []
    batch_names = []
    cnt = 0
    for idx, img_path in enumerate(image_list):
        img = cv2.imread(img_path)
        if img is None:
            logger.warning(
                "Image file failed to read and has been skipped. The path: {}".
                format(img_path))
        else:
            img = img[:, :, ::-1]
            batch_imgs.append(img)
            img_name = os.path.basename(img_path)
            batch_names.append(img_name)
            cnt += 1

        if cnt % config["Global"]["batch_size"] == 0 or (idx +
                                                         1) == len(image_list):
            if len(batch_imgs) == 0:
                continue

            batch_results = rec_predictor.predict(batch_imgs)
            for number, result_dict in enumerate(batch_results):
                filename = batch_names[number]
                print("{}:\t{}".format(filename, result_dict))
            batch_imgs = []
            batch_names = []

    return
コード例 #2
0
ファイル: predict_system.py プロジェクト: dyning/PaddleClas
def main(config):
    system_predictor = SystemPredictor(config)
    image_list = get_image_list(config["Global"]["infer_imgs"])

    assert config["Global"]["batch_size"] == 1
    for idx, image_file in enumerate(image_list):
        img = cv2.imread(image_file)[:, :, ::-1]
        output = system_predictor.predict(img)
        draw_bbox_results(img, output, image_file)
        print(output)
    return
コード例 #3
0
def main(config):
    det_predictor = DetPredictor(config)
    image_list = get_image_list(config["Global"]["infer_imgs"])

    assert config["Global"]["batch_size"] == 1
    for idx, image_file in enumerate(image_list):
        img = cv2.imread(image_file)[:, :, ::-1]
        output = det_predictor.predict(img)
        print(output)

    return
コード例 #4
0
def main(config):
    cls_predictor = ClsPredictor(config)
    image_list = get_image_list(config["Global"]["infer_imgs"])

    batch_imgs = []
    batch_names = []
    cnt = 0
    for idx, img_path in enumerate(image_list):
        img = cv2.imread(img_path)
        if img is None:
            logger.warning(
                "Image file failed to read and has been skipped. The path: {}".
                format(img_path))
        else:
            img = img[:, :, ::-1]
            batch_imgs.append(img)
            img_name = os.path.basename(img_path)
            batch_names.append(img_name)
            cnt += 1

        if cnt % config["Global"]["batch_size"] == 0 or (idx +
                                                         1) == len(image_list):
            if len(batch_imgs) == 0:
                continue
            batch_results = cls_predictor.predict(batch_imgs)
            for number, result_dict in enumerate(batch_results):
                filename = batch_names[number]
                clas_ids = result_dict["class_ids"]
                scores_str = "[{}]".format(", ".join(
                    "{:.2f}".format(r) for r in result_dict["scores"]))
                label_names = result_dict["label_names"]
                print("{}:\tclass id(s): {}, score(s): {}, label_name(s): {}".
                      format(filename, clas_ids, scores_str, label_names))
            batch_imgs = []
            batch_names = []
    if cls_predictor.benchmark:
        cls_predictor.auto_logger.report()
    return
コード例 #5
0
def main(args):
    image_path_list = get_image_list(args.image_file)
    headers = {"Content-type": "application/json"}
    preprocess_ops = create_operators(
        PreprocessConfig(args.resize_short, args.crop_size, args.normalize,
                         args.to_chw)())

    cnt = 0
    predict_time = 0
    all_score = 0.0
    start_time = time.time()

    img_data_list = []
    img_name_list = []
    cnt = 0
    for idx, img_path in enumerate(image_path_list):
        img = cv2.imread(img_path)
        if img is None:
            logger.warning(
                f"Image file failed to read and has been skipped. The path: {img_path}"
            )
            continue
        else:
            img = img[:, :, ::-1]
            for ops in preprocess_ops:
                img = ops(img)
            img = np.array(img)
            img_data_list.append(img)

            img_name = img_path.split('/')[-1]
            img_name_list.append(img_name)
            cnt += 1
        if cnt % args.batch_size == 0 or (idx + 1) == len(image_path_list):
            inputs = np.array(img_data_list)
            b64str, revert_shape = np_to_b64(inputs)
            data = {
                "images": b64str,
                "revert_params": {
                    "shape": revert_shape,
                    "dtype": str(inputs.dtype)
                }
            }
            try:
                r = requests.post(
                    url=args.server_url,
                    headers=headers,
                    data=json.dumps(data))
                r.raise_for_status
                if r.json()["status"] != "000":
                    msg = r.json()["msg"]
                    raise Exception(msg)
            except Exception as e:
                logger.error(f"{e}, in file(s): {img_name_list[0]} etc.")
                continue
            else:
                results = r.json()["results"]
                preds = results["prediction"]
                elapse = results["elapse"]

                cnt += len(preds)
                predict_time += elapse

                for number, result_list in enumerate(preds):
                    all_score += result_list["scores"][0]
                    pred_str = ", ".join(
                        [f"{k}: {result_list[k]}" for k in result_list])
                    logger.info(
                        f"File:{img_name_list[number]}, The result(s): {pred_str}"
                    )

            finally:
                img_data_list = []
                img_name_list = []

    total_time = time.time() - start_time
    logger.info("The average time of prediction cost: {:.3f} s/image".format(
        predict_time / cnt))
    logger.info("The average time cost: {:.3f} s/image".format(total_time /
                                                               cnt))
    logger.info("The average top-1 score: {:.3f}".format(all_score / cnt))