| 52 | |
| 53 | |
| 54 | class MARCONetPlus(object): |
| 55 | def __init__(self, WEncoderPath=None, PriorModelPath=None, SRModelPath=None, YoloPath=None, device='cuda'): |
| 56 | self.device = device |
| 57 | |
| 58 | modelscope_dir = snapshot_download('damo/cv_convnextTiny_ocr-recognition-general_damo', cache_dir='./checkpoints/modelscope_ocr') |
| 59 | self.modelscope_ocr_recognition = pipeline(Tasks.ocr_recognition, model=modelscope_dir) |
| 60 | self.yolo_character = YOLO(YoloPath) |
| 61 | |
| 62 | self.modelWEncoder = PSPEncoder() # WEncoder() |
| 63 | self.modelWEncoder.load_state_dict(torch.load(WEncoderPath)['params'], strict=True) |
| 64 | self.modelWEncoder.eval() |
| 65 | self.modelWEncoder.to(device) |
| 66 | |
| 67 | self.modelPrior = TextPriorModel() |
| 68 | self.modelPrior.load_state_dict(torch.load(PriorModelPath)['params'], strict=True) |
| 69 | self.modelPrior.eval() |
| 70 | self.modelPrior.to(device) |
| 71 | |
| 72 | self.modelSR = SRNet() |
| 73 | self.modelSR.load_state_dict(torch.load(SRModelPath)['params'], strict=True) |
| 74 | self.modelSR.eval() |
| 75 | self.modelSR.to(device) |
| 76 | |
| 77 | |
| 78 | print('='*128) |
| 79 | print('{:>25s} : {:.2f} M Parameters'.format('modelWEncoder', get_parameter_details(self.modelWEncoder))) |
| 80 | print('{:>25s} : {:.2f} M Parameters'.format('modelPrior', get_parameter_details(self.modelPrior))) |
| 81 | print('{:>25s} : {:.2f} M Parameters'.format('modelSR', get_parameter_details(self.modelSR))) |
| 82 | print('='*128) |
| 83 | |
| 84 | torch.cuda.empty_cache() |
| 85 | self.cnstd = CnStd(model_name='db_resnet34',rotated_bbox=True, model_backend='pytorch', box_score_thresh=0.3, min_box_size=10, context=device) |
| 86 | self.insize = 32 |
| 87 | |
| 88 | |
| 89 | def handle_texts(self, img, bg=None, sf=4, is_aligned=False, lq_label=None): |
| 90 | ''' |
| 91 | Parameters: |
| 92 | img: RGB 0~255. |
| 93 | ''' |
| 94 | |
| 95 | height, width = img.shape[:2] |
| 96 | bg_height, bg_width = bg.shape[:2] |
| 97 | print(' ' * 25 + f' ... The input->output image size is {bg_height//sf}*{bg_width//sf}->{bg_height}*{bg_width}') |
| 98 | |
| 99 | full_mask_blur = np.zeros(bg.shape, dtype=np.float32) |
| 100 | full_mask_noblur = np.zeros(bg.shape, dtype=np.float32) |
| 101 | full_text_img = np.zeros(bg.shape, dtype=np.float32) #+255 |
| 102 | |
| 103 | orig_texts, enhanced_texts, debug_texts, pred_texts = [], [], [], [] |
| 104 | ocr_scores = [] |
| 105 | |
| 106 | if not is_aligned: |
| 107 | box_infos = self.cnstd.detect(img) |
| 108 | for iix, box_info in enumerate(box_infos['detected_texts']): |
| 109 | box = box_info['box'].astype(int)# left top, right top, right bottom, left bottom, [width, height] |
| 110 | score = box_info['score'] |
| 111 | if score < 0.5: |