コード例 #1
0
class OcrDetCTPN():
    def __init__(self, model_path='./checkpoints/CTPN.pth'):
        self.model = CTPN_Model()
        self.use_gpu = torch.cuda.is_available()
        if self.use_gpu:
            self.model.cuda()
        device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
        self.model.load_state_dict(
            torch.load(model_path, map_location=device)['model_state_dict'])
        for p in self.model.parameters():
            p.requires_grad = False
        self.model.eval()
        self.prob_thresh = 0.5

    def inference(self, image):
        image_sz = resize(image, height=ctpn_params.IMAGE_HEIGHT)
        # 宽高缩放比例(等比例缩放)
        rescale_fac = image.shape[0] / image_sz.shape[0]
        h, w = image_sz.shape[:2]
        # 减均值
        image_sz = image_sz.astype(np.float32) - ctpn_params.IMAGE_MEAN
        image_sz = torch.from_numpy(image_sz.transpose(
            2, 0, 1)).unsqueeze(0).float()

        if self.use_gpu:
            image_sz = image_sz.cuda()
        cls, regr = self.model(image_sz)
        cls_prob = F.softmax(cls, dim=-1).cpu().numpy()
        regr = regr.cpu().numpy()
        anchor = gen_anchor((int(h / 16), int(w / 16)), 16)
        bbox = bbox_transfor_inv(anchor, regr)
        bbox = clip_box(bbox, [h, w])

        fg = np.where(cls_prob[0, :, 1] > self.prob_thresh)[0]
        select_anchor = bbox[fg, :]
        select_score = cls_prob[0, fg, 1]
        select_anchor = select_anchor.astype(np.int32)
        keep_index = filter_bbox(select_anchor, 16)

        # nms
        select_anchor = select_anchor[keep_index]
        select_score = select_score[keep_index]
        select_score = np.reshape(select_score, (select_score.shape[0], 1))
        nmsbox = np.hstack((select_anchor, select_score))
        keep = nms(nmsbox, 0.3)
        select_anchor = select_anchor[keep]
        select_score = select_score[keep]

        # text line-
        textConn = TextProposalConnectorOriented()
        text = textConn.get_text_lines(select_anchor, select_score, [h, w])
        text = [np.hstack((res[:8] * rescale_fac, res[8])) for res in text]

        return text
コード例 #2
0
    print('####################  Start evaluate  ####################')
    print(f'loss: {total_loss:.4f}')
    print(f'classification loss: {total_cls_loss:.4f}')
    print(f'vertical regression loss: {total_v_reg_loss:.4f}')
    print(f'{epoch_size} iterations for {total_time:.4f} seconds, avg {avg_infer_time:.4f} seconds.')
    print('#####################  Evaluate end  #####################')
    print('\n')

    return total_cls_loss, total_v_reg_loss, total_loss


if __name__ == "__main__":
    opt = parser.parse_args()
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model = CTPN_Model()
    criterion_cls = RPN_CLS_Loss(device)
    criterion_regr = RPN_REGR_Loss(device)
    if torch.cuda.is_available():
        torch.backends.cudnn.benchmark = True
        model = model.cuda()

    val_dataset = vocDataset(opt.data_root)
    val_dataloader = DataLoader(val_dataset, batch_size=opt.batch_size, shuffle=False, num_workers=4)
    
    if opt.model_path !='' and os.path.exists(opt.model_path):
        print('loading pretrained model from %s' % opt.model_path)
        cc = torch.load(opt.model_path, map_location=device)
        model.load_state_dict(cc['model_state_dict'])
        loss_cls, loss_regr, loss = val(model, val_dataloader, criterion_cls, criterion_regr, device)
    else:
        print(f'evaluate Error: {opt.model_path} doesnot exist')