Example #1
0
def eval(model, save_path, test_path, device):
    model.eval()
    # torch.cuda.empty_cache()  # speed up evaluating after training finished
    img_path = os.path.join(test_path, 'img')
    gt_path = os.path.join(test_path, 'gt')
    if os.path.exists(save_path):
        shutil.rmtree(save_path, ignore_errors=True)
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    long_size = 2240
    # 预测所有测试图片
    img_paths = [os.path.join(img_path, x) for x in os.listdir(img_path)]
    for img_path in tqdm(img_paths, desc='test models'):
        img_name = os.path.basename(img_path).split('.')[0]
        save_name = os.path.join(save_path, 'res_' + img_name + '.txt')

        assert os.path.exists(img_path), 'file is not exists'
        img = cv2.imread(img_path)
        h, w = img.shape[:2]
        # if max(h, w) > long_size:
        scale = long_size / max(h, w)
        img = cv2.resize(img, None, fx=scale, fy=scale)
        # 将图片由(w,h)变为(1,img_channel,h,w)
        tensor = transforms.ToTensor()(img)
        tensor = tensor.unsqueeze_(0)
        tensor = tensor.to(device)
        with torch.no_grad():
            preds = model(tensor)
            preds, boxes_list = pse_decode(preds[0], config.scale)
            scale = (preds.shape[1] * 1.0 / w, preds.shape[0] * 1.0 / h)
            if len(boxes_list):
                boxes_list = boxes_list / scale
        np.savetxt(save_name,
                   boxes_list.reshape(-1, 8),
                   delimiter=',',
                   fmt='%d')
    # 开始计算 recall precision f1
    result_dict = cal_recall_precison_f1(gt_path, save_path)
    return result_dict['recall'], result_dict['precision'], result_dict[
        'hmean']
Example #2
0
        cv2.imwrite(os.path.join(save_img_folder, '{}.jpg'.format(img_name)),
                    img)
        np.savetxt(save_name,
                   boxes_list.reshape(-1, 8),
                   delimiter=',',
                   fmt='%d')
    print('fps:{}'.format(total_frame / total_time))
    return save_txt_folder


if __name__ == '__main__':
    os.environ['CUDA_VISIBLE_DEVICES'] = str('0')
    backbone = 'resnet101'
    scale = 4
    model_path = './output/APSEGAT_weights.pth'
    data_path = './images/img'
    gt_path = './images/gt'
    save_path = './result/_scale{}'.format(scale)
    gpu_id = 0
    print('backbone:{},scale:{},model_path:{}'.format(backbone, scale,
                                                      model_path))
    save_path = main(model_path,
                     backbone,
                     scale,
                     data_path,
                     save_path,
                     gpu_id=gpu_id)
    result = cal_recall_precison_f1(gt_path=gt_path, result_path=save_path)
    print(result)
    # print(cal_recall_precison_f1('/data2/dataset/ICD151/test/gt', '/data1/zj/tensorflow_PSENet/tmp/'))
Example #3
0
    if not os.path.exists(img_save_path):
        os.mkdir(img_save_path)

    detect = OcrDetCTPN(opt.model_path)
    image_files = os.listdir(opt.image_root)
    for i in tqdm(range(len(image_files))):
        image_file = image_files[i]
        im_name = image_file.split('.')[0]
        fid = open(os.path.join(txt_save_path, 'res_' + im_name + '.txt'),
                   'w+',
                   encoding='utf-8')
        image_file = os.path.join(opt.image_root, image_file)
        image = cv2.imread(image_file)
        det_recs = detect.inference(image)
        for i, box in enumerate(det_recs):
            x3, y3 = box[6], box[7]
            box[6], box[7] = box[4], box[5]
            box[4], box[5] = x3, y3
            box = box[:8].reshape(4, 2).astype(np.int32)
            cv2.polylines(image, [box[:8].reshape((-1, 1, 2))],
                          True,
                          color=(0, 255, 0),
                          thickness=2)
            box = [str(x) for x in box.reshape(-1).tolist()]
            fid.write(','.join(box) + '\n')

        cv2.imwrite(os.path.join(img_save_path, im_name + '.jpg'), image)
        fid.close()

    pre = cal_recall_precison_f1(opt.test_gt, txt_save_path, show_result=False)
    print(pre)
    if not os.path.exists(save_txt_folder):
        os.makedirs(save_txt_folder)

    start_time_all = time.time()
    img_count = 0
    for i in tqdm.tqdm(os.listdir(test_images_path)):
        # print(i)
        img_name = i.split('.')[0]
        i = os.path.join(test_images_path, i)

        img = cv2.imread(i)
        start_time = time.time()

        prediction, vis_output, polygons = detection_demo.run_on_image(img)

        img_save_path = os.path.join(save_img_folder,
                                     'res_' + img_name + '.jpg')
        txt_save_path = os.path.join(save_txt_folder,
                                     'res_' + img_name + '.txt')

        save_result_to_txt(txt_save_path, prediction, polygons)

        # print("Time: {:.2f} s / img".format(time.time() - start_time))
        vis_output.save(img_save_path)
        img_count += 1
    print("Average Time: {:.2f} s /img".format(
        (time.time() - start_time_all) / img_count))
    result = cal_recall_precison_f1(gt_path=args.gt_path,
                                    result_path=save_txt_folder)
    print(result)