def mscrop_test(self, in_data_dict, params_dict): total_logits = [np.zeros((meta['ori_img_size'][1], meta['ori_img_size'][0], self.configer.get('data', 'num_classes')), np.float32) for meta in DCHelper.tolist(in_data_dict['meta'])] for scale in params_dict['scale_search']: data_dict = self.blob_helper.get_blob(in_data_dict, scale=scale) if any(image.size()[2] < params_dict['crop_size'][0] or image.size()[1] < params_dict['crop_size'][1] for image in DCHelper.tolist(data_dict['img'])): results = self._predict(data_dict) else: results = self._crop_predict(data_dict, params_dict['crop_size'], params_dict['crop_stride_ratio']) for i in range(len(total_logits)): total_logits[i] += results[i] for scale in params_dict['scale_search']: data_dict = self.blob_helper.get_blob(in_data_dict, scale=scale, flip=True) if any(image.size()[2] < params_dict['crop_size'][0] or image.size()[1] < params_dict['crop_size'][1] for image in DCHelper.tolist(data_dict['img'])): results = self._predict(data_dict) else: results = self._crop_predict(data_dict, params_dict['crop_size'], params_dict['crop_stride_ratio']) for i in range(len(total_logits)): total_logits[i] += results[i][:, ::-1] return total_logits
def get_blob(self, data_dict, scale=None, flip=False): assert scale is not None img_list, meta_list = [], [] for image, meta in zip(DCHelper.tolist(data_dict['img']), DCHelper.tolist(data_dict['meta'])): c, h, w = image.size() border_hw = [int(h*scale), int(w*scale)] meta['border_hw'] = border_hw image = TensorHelper.resize(image, border_hw, mode='bilinear', align_corners=True) if flip: image = image.flip([2]) if self.configer.get('test.fit_stride', default=0) > 0: stride = self.configer.get('test', 'fit_stride') pad_w = 0 if (border_hw[1] % stride == 0) else stride - (border_hw[1] % stride) # right pad_h = 0 if (border_hw[0] % stride == 0) else stride - (border_hw[0] % stride) # down expand_image = torch.zeros((c, border_hw[0] + pad_h, border_hw[1] + pad_w)).to(image.device) expand_image[:, 0:border_hw[0], 0:border_hw[1]] = image image = expand_image img_list.append(image) meta_list.append(meta) new_data_dict = dict( img=DCHelper.todc(img_list, stack=True, samples_per_gpu=True), meta=DCHelper.todc(meta_list, samples_per_gpu=True, cpu_only=True) ) return new_data_dict
def _crop_predict(self, data_dict, crop_size, crop_stride_ratio): split_batch = list() height_starts_list = list() width_starts_list = list() hw_list = list() for image in DCHelper.tolist(data_dict['img']): height, width = image.size()[1:] hw_list.append([height, width]) np_image = image.squeeze(0).permute(1, 2, 0).cpu().numpy() height_starts = self._decide_intersection(height, crop_size[1], crop_stride_ratio) width_starts = self._decide_intersection(width, crop_size[0], crop_stride_ratio) split_crops = [] for height in height_starts: for width in width_starts: image_crop = np_image[height:height + crop_size[1], width:width + crop_size[0]] split_crops.append(image_crop[np.newaxis, :]) height_starts_list.append(height_starts) width_starts_list.append(width_starts) split_crops = np.concatenate(split_crops, axis=0) # (n, crop_image_size, crop_image_size, 3) inputs = torch.from_numpy(split_crops).permute(0, 3, 1, 2).to(self.device) split_batch.append(inputs) assert len(split_batch) == torch.cuda.device_count(), 'Only support one image per gpu.' out_list = list() with torch.no_grad(): results = self.seg_net(dict(img=DCHelper.todc(split_batch, stack=False, samples_per_gpu=True, concat=True))) results = results if isinstance(results, (list, tuple)) else [results] for res in results: out_list.append(res['out'].permute(0, 2, 3, 1).cpu().numpy()) total_logits = [np.zeros((hw[0], hw[1], self.configer.get('data', 'num_classes')), np.float32) for hw in hw_list] count_predictions = [np.zeros((hw[0], hw[1], self.configer.get('data', 'num_classes')), np.float32) for hw in hw_list] for i in range(len(height_starts_list)): index = 0 for height in height_starts_list[i]: for width in width_starts_list[i]: total_logits[i][height:height+crop_size[1], width:width+crop_size[0]] += out_list[i][index] count_predictions[i][height:height+crop_size[1], width:width+crop_size[0]] += 1 index += 1 for i in range(len(total_logits)): total_logits[i] /= count_predictions[i] for i, meta in enumerate(DCHelper.tolist(data_dict['meta'])): total_logits[i] = cv2.resize(total_logits[i][:meta['border_wh'][1], :meta['border_wh'][0]], tuple(meta['ori_img_size']), interpolation=cv2.INTER_CUBIC) return total_logits
def val(self): """ Validation function during the train phase. """ self.det_net.eval() start_time = time.time() with torch.no_grad(): for j, data_dict in enumerate(self.val_loader): # Forward pass. data_dict = RunnerHelper.to_device(self, data_dict) out = self.det_net(data_dict) loss_dict = self.det_loss(out) # Compute the loss of the train batch & backward. loss = loss_dict['loss'].mean() out_dict, _ = RunnerHelper.gather(self, out) self.val_losses.update(loss.item(), len(DCHelper.tolist(data_dict['meta']))) test_indices_and_rois, test_roi_locs, test_roi_scores, test_rois_num = out_dict[ 'test_group'] batch_detections = FastRCNNTest.decode( test_roi_locs, test_roi_scores, test_indices_and_rois, test_rois_num, self.configer, DCHelper.tolist(data_dict['meta'])) batch_pred_bboxes = self.__get_object_list(batch_detections) self.det_running_score.update(batch_pred_bboxes, [ item['ori_bboxes'] for item in DCHelper.tolist(data_dict['meta']) ], [ item['ori_labels'] for item in DCHelper.tolist(data_dict['meta']) ]) # Update the vars of the val phase. self.batch_time.update(time.time() - start_time) start_time = time.time() RunnerHelper.save_net(self, self.det_net, iters=self.runner_state['iters']) # Print the log info & reset the states. Log.info( 'Test Time {batch_time.sum:.3f}s, ({batch_time.avg:.3f})\t' 'Loss {loss.avg:.8f}\n'.format(batch_time=self.batch_time, loss=self.val_losses)) Log.info('Val mAP: {}\n'.format(self.det_running_score.get_mAP())) self.det_running_score.reset() self.batch_time.reset() self.val_losses.reset() self.det_net.train()
def val(self): """ Validation function during the train phase. """ self.gan_net.eval() start_time = time.time() for j, data_dict in enumerate(self.val_loader): with torch.no_grad(): # Forward pass. out_dict = self.gan_net(data_dict) # Compute the loss of the val batch. self.val_losses.update( out_dict['loss_G'].mean().item() + out_dict['loss_D'].mean().item(), len(DCHelper.tolist(data_dict['meta']))) # Update the vars of the val phase. self.batch_time.update(time.time() - start_time) start_time = time.time() RunnerHelper.save_net(self, self.gan_net, val_loss=self.val_losses.avg) # Print the log info & reset the states. Log.info('Test Time {batch_time.sum:.3f}s, ({batch_time.avg:.3f})\t' 'Loss {loss.avg:.8f}\n'.format(batch_time=self.batch_time, loss=self.val_losses)) self.batch_time.reset() self.val_losses.reset() self.gan_net.train()
def test(self, test_dir, out_dir): for _, data_dict in enumerate( self.test_loader.get_testloader(test_dir=test_dir)): data_dict['testing'] = True data_dict = RunnerHelper.to_device(self, data_dict) out_dict = self.det_net(data_dict) meta_list = DCHelper.tolist(data_dict['meta']) test_indices_and_rois, test_roi_locs, test_roi_scores, test_rois_num = out_dict[ 'test_group'] batch_detections = self.decode(test_roi_locs, test_roi_scores, test_indices_and_rois, test_rois_num, self.configer, meta_list) for i in range(len(meta_list)): ori_img_bgr = ImageHelper.read_image(meta_list[i]['img_path'], tool='cv2', mode='BGR') json_dict = self.__get_info_tree(batch_detections[i]) image_canvas = self.det_parser.draw_bboxes( ori_img_bgr.copy(), json_dict, conf_threshold=self.configer.get('res', 'vis_conf_thre')) ImageHelper.save(image_canvas, save_path=os.path.join( out_dir, 'vis/{}.png'.format( meta_list[i]['filename']))) Log.info('Json Path: {}'.format( os.path.join( out_dir, 'json/{}.json'.format(meta_list[i]['filename'])))) JsonHelper.save_file(json_dict, save_path=os.path.join( out_dir, 'json/{}.json'.format( meta_list[i]['filename'])))
def train(self): """ Train function of every epoch during train phase. """ self.det_net.train() start_time = time.time() # Adjust the learning rate after every epoch. self.runner_state['epoch'] += 1 # data_tuple: (inputs, heatmap, maskmap, vecmap) for i, data_dict in enumerate(self.train_loader): Trainer.update(self, warm_list=(0, ), warm_lr_list=(self.configer.get('solver', 'lr')['base_lr'], ), solver_dict=self.configer.get('solver')) self.data_time.update(time.time() - start_time) # Forward pass. out_dict = self.det_net(data_dict) # Compute the loss of the train batch & backward. loss = out_dict['loss'].mean() self.train_losses.update(loss.item(), len(DCHelper.tolist(data_dict['meta']))) self.optimizer.zero_grad() loss.backward() self.optimizer.step() # Update the vars of the train phase. self.batch_time.update(time.time() - start_time) start_time = time.time() self.runner_state['iters'] += 1 # Print the log info & reset the states. if self.runner_state['iters'] % self.configer.get( 'solver', 'display_iter') == 0: Log.info( 'Train Epoch: {0}\tTrain Iteration: {1}\t' 'Time {batch_time.sum:.3f}s / {2}iters, ({batch_time.avg:.3f})\t' 'Data load {data_time.sum:.3f}s / {2}iters, ({data_time.avg:3f})\n' 'Learning rate = {3}\tLoss = {loss.val:.8f} (ave = {loss.avg:.8f})\n' .format(self.runner_state['epoch'], self.runner_state['iters'], self.configer.get('solver', 'display_iter'), RunnerHelper.get_lr(self.optimizer), batch_time=self.batch_time, data_time=self.data_time, loss=self.train_losses)) self.batch_time.reset() self.data_time.reset() self.train_losses.reset() if self.configer.get('solver', 'lr')['metric'] == 'iters' \ and self.runner_state['iters'] == self.configer.get('solver', 'max_iters'): break # Check to val the current model. if self.runner_state['iters'] % self.configer.get( 'solver', 'test_interval') == 0: self.val()
def val(self): """ Validation function during the train phase. """ self.pose_net.eval() start_time = time.time() with torch.no_grad(): for i, data_dict in enumerate(self.val_loader): # Forward pass. out_dict = self.pose_net(data_dict) # Compute the loss of the val batch. loss_dict = self.mse_loss(out_dict, data_dict, gathered=self.configer.get('network', 'gathered')) self.val_losses.update(loss_dict['loss'].mean().item(), len(DCHelper.tolist(data_dict['meta']))) # Update the vars of the val phase. self.batch_time.update(time.time() - start_time) start_time = time.time() self.runner_state['val_loss'] = self.val_losses.avg RunnerHelper.save_net(self, self.pose_net, val_loss=self.val_losses.avg) # Print the log info & reset the states. Log.info( 'Test Time {batch_time.sum:.3f}s, ({batch_time.avg:.3f})\t' 'Loss {loss.avg:.8f}\n'.format( batch_time=self.batch_time, loss=self.val_losses)) self.batch_time.reset() self.val_losses.reset() self.val_loss_heatmap.reset() self.val_loss_associate.reset() self.pose_net.train()
def val(self, data_loader=None): """ Validation function during the train phase. """ self.gan_net.eval() start_time = time.time() data_loader = self.val_loader if data_loader is None else data_loader for j, data_dict in enumerate(data_loader): with torch.no_grad(): # Forward pass. out_dict = self.gan_net(data_dict) # Compute the loss of the val batch. self.val_losses.update(out_dict['loss'].mean().item(), len(DCHelper.tolist(data_dict['meta']))) meta_list = DCHelper.tolist(data_dict['meta']) probe_features = [] gallery_features = [] probe_labels = [] gallery_labels = [] for idx in range(len(meta_list)): gallery_features.append(out_dict['featB'][idx].cpu().numpy()) gallery_labels.append(meta_list[idx]['labelB']) probe_features.append(out_dict['featA'][idx].cpu().numpy()) probe_labels.append(meta_list[idx]['labelA']) rank_1, vr_far_001 = FaceGANTest.decode(probe_features, gallery_features, probe_labels, gallery_labels) Log.info('Rank1 accuracy is {}'.format(rank_1)) Log.info('VR@FAR=0.1% accuracy is {}'.format(vr_far_001)) # Update the vars of the val phase. self.batch_time.update(time.time() - start_time) start_time = time.time() RunnerHelper.save_net(self, self.gan_net, val_loss=self.val_losses.avg) # Print the log info & reset the states. Log.info('Test Time {batch_time.sum:.3f}s, ({batch_time.avg:.3f})\t' 'Loss {loss.avg:.8f}\n'.format(batch_time=self.batch_time, loss=self.val_losses)) self.batch_time.reset() self.val_losses.reset() self.gan_net.train()
def val(self): """ Validation function during the train phase. """ self.det_net.eval() start_time = time.time() with torch.no_grad(): for i, data_dict in enumerate(self.val_loader): # Forward pass. out_dict = self.det_net(data_dict) # Compute the loss of the val batch. loss = out_dict['loss'].mean() self.val_losses.update(loss.item(), len(DCHelper.tolist(data_dict['meta']))) batch_detections = YOLOv3Test.decode( out_dict['dets'], self.configer, DCHelper.tolist(data_dict['meta'])) batch_pred_bboxes = self.__get_object_list(batch_detections) self.det_running_score.update(batch_pred_bboxes, [ item['ori_bboxes'] for item in DCHelper.tolist(data_dict['meta']) ], [ item['ori_labels'] for item in DCHelper.tolist(data_dict['meta']) ]) # Update the vars of the val phase. self.batch_time.update(time.time() - start_time) start_time = time.time() RunnerHelper.save_net(self, self.det_net, iters=self.runner_state['iters']) # Print the log info & reset the states. Log.info( 'Test Time {batch_time.sum:.3f}s, ({batch_time.avg:.3f})\t' 'Loss {loss.avg:.8f}\n'.format(batch_time=self.batch_time, loss=self.val_losses)) Log.info('Val mAP: {}'.format(self.det_running_score.get_mAP())) self.det_running_score.reset() self.batch_time.reset() self.val_losses.reset() self.det_net.train()
def sscrop_test(self, in_data_dict, params_dict): data_dict = self.blob_helper.get_blob(in_data_dict, scale=1.0) if any(image.size()[2] < params_dict['crop_size'][0] or image.size()[1] < params_dict['crop_size'][1] for image in DCHelper.tolist(data_dict['img'])): results = self._predict(data_dict) else: results = self._crop_predict(data_dict, params_dict['crop_size'], params_dict['crop_stride_ratio']) return results
def val(self): """ Validation function during the train phase. """ self.cls_net.eval() start_time = time.time() with torch.no_grad(): for j, data_dict in enumerate(self.val_loader): # Forward pass. out_dict = self.cls_net(data_dict) # Compute the loss of the val batch. loss = self.ce_loss(out_dict, data_dict, gathered=self.configer.get( 'network', 'gathered')) out_dict = RunnerHelper.gather(self, out_dict) self.cls_running_score.update( out_dict['out'], DCHelper.tolist(data_dict['labels'])) self.val_losses.update(loss.item(), len(DCHelper.tolist(data_dict['meta']))) # Update the vars of the val phase. self.batch_time.update(time.time() - start_time) start_time = time.time() RunnerHelper.save_net( self, self.cls_net, performance=self.cls_running_score.get_top1_acc()) self.runner_state[ 'performance'] = self.cls_running_score.get_top1_acc() # Print the log info & reset the states. Log.info('Test Time {batch_time.sum:.3f}s'.format( batch_time=self.batch_time)) Log.info('TestLoss = {loss.avg:.8f}'.format(loss=self.val_losses)) Log.info('Top1 ACC = {}'.format( self.cls_running_score.get_top1_acc())) Log.info('Top5 ACC = {}'.format( self.cls_running_score.get_top5_acc())) self.batch_time.reset() self.val_losses.reset() self.cls_running_score.reset() self.cls_net.train()
def test(self, test_dir, out_dir): if self.configer.exists('test', 'mode') and self.configer.get('test', 'mode') == 'nir2vis': jsonA_path = os.path.join(test_dir, 'val_label{}A.json'.format(self.configer.get('data', 'tag'))) test_loader_A = self.test_loader.get_testloader(json_path=jsonA_path) if os.path.exists(jsonA_path) else None jsonB_path = os.path.join(test_dir, 'val_label{}B.json'.format(self.configer.get('data', 'tag'))) test_loader_B = self.test_loader.get_testloader(json_path=jsonB_path) if os.path.exists(jsonB_path) else None elif self.configer.exists('test', 'mode') and self.configer.get('test', 'mode') == 'pix2pix': imgA_dir = os.path.join(test_dir, 'imageA') test_loader_A = self.test_loader.get_testloader(test_dir=imgA_dir) if os.path.exists(imgA_dir) else None imgB_dir = os.path.join(test_dir, 'imageB') test_loader_B = self.test_loader.get_testloader(test_dir=imgB_dir) if os.path.exists(imgB_dir) else None else: imgA_dir = os.path.join(test_dir, 'imageA') test_loader_A = self.test_loader.get_testloader(test_dir=imgA_dir) if os.path.exists(imgA_dir) else None imgB_dir = os.path.join(test_dir, 'imageB') test_loader_B = self.test_loader.get_testloader(test_dir=imgB_dir) if os.path.exists(imgB_dir) else None if test_loader_A is not None: for data_dict in test_loader_A: new_data_dict = dict(imgA=data_dict['img'], testing=True) with torch.no_grad(): out_dict = self.gan_net(new_data_dict) meta_list = DCHelper.tolist(data_dict['meta']) for key, value in out_dict.items(): for i in range(len(value)): img_bgr = self.blob_helper.tensor2bgr(value[i]) img_path = meta_list[i]['img_path'] Log.info('Image Path: {}'.format(img_path)) ImageHelper.save(img_bgr, os.path.join(out_dir, '{}_{}.jpg'.format(meta_list[i]['filename'], key))) if test_loader_B is not None: for data_dict in test_loader_B: new_data_dict = dict(imgB=data_dict['img'], testing=True) with torch.no_grad(): out_dict = self.gan_net(new_data_dict) meta_list = DCHelper.tolist(data_dict['meta']) for key, value in out_dict.items(): for i in range(len(value)): img_bgr = self.blob_helper.tensor2bgr(value[i]) img_path = meta_list[i]['img_path'] Log.info('Image Path: {}'.format(img_path)) ImageHelper.save(img_bgr, os.path.join(out_dir, '{}_{}.jpg'.format(meta_list[i]['filename'], key)))
def test(self, test_dir, out_dir): for _, data_dict in enumerate( self.test_loader.get_testloader(test_dir=test_dir)): total_logits = None if self.configer.get('test', 'mode') == 'ss_test': total_logits = self.ss_test(data_dict) elif self.configer.get('test', 'mode') == 'sscrop_test': total_logits = self.sscrop_test(data_dict, params_dict=self.configer.get( 'test', 'sscrop_test')) elif self.configer.get('test', 'mode') == 'ms_test': total_logits = self.ms_test(data_dict, params_dict=self.configer.get( 'test', 'ms_test')) elif self.configer.get('test', 'mode') == 'mscrop_test': total_logits = self.mscrop_test(data_dict, params_dict=self.configer.get( 'test', 'mscrop_test')) else: Log.error('Invalid test mode:{}'.format( self.configer.get('test', 'mode'))) exit(1) meta_list = DCHelper.tolist(data_dict['meta']) for i in range(len(meta_list)): label_map = np.argmax(total_logits[i], axis=-1) label_img = np.array(label_map, dtype=np.uint8) ori_img_bgr = ImageHelper.read_image(meta_list[i]['img_path'], tool='cv2', mode='BGR') image_canvas = self.seg_parser.colorize( label_img, image_canvas=ori_img_bgr) ImageHelper.save(image_canvas, save_path=os.path.join( out_dir, 'vis/{}.png'.format( meta_list[i]['filename']))) if self.configer.get('data.label_list', default=None) is not None: label_img = self.__relabel(label_img) if self.configer.get('data.reduce_zero_label', default=False): label_img = label_img + 1 label_img = label_img.astype(np.uint8) label_img = Image.fromarray(label_img, 'P') label_path = os.path.join( out_dir, 'label/{}.png'.format(meta_list[i]['filename'])) Log.info('Label Path: {}'.format(label_path)) ImageHelper.save(label_img, label_path)
def val(self, data_loader=None): """ Validation function during the train phase. """ if self.configer.get('local_rank') != 0: return self.seg_net.eval() start_time = time.time() data_loader = self.val_loader if data_loader is None else data_loader for j, data_dict in enumerate(data_loader): data_dict = RunnerHelper.to_device(self, data_dict) with torch.no_grad(): # Forward pass. out = self.seg_net(data_dict) loss_dict = self.loss(out) # Compute the loss of the val batch. out_dict, _ = RunnerHelper.gather(self, out) self.val_losses.update( {key: loss.item() for key, loss in loss_dict.items()}, data_dict['img'].size(0)) self._update_running_score(out_dict['out'], DCHelper.tolist(data_dict['meta'])) # Update the vars of the val phase. self.batch_time.update(time.time() - start_time) start_time = time.time() self.runner_state['performance'] = self.seg_running_score.get_mean_iou( ) self.runner_state['val_loss'] = self.val_losses.avg['loss'] RunnerHelper.save_net( self, self.seg_net, performance=self.seg_running_score.get_mean_iou(), val_loss=self.val_losses.avg['loss']) # Print the log info & reset the states. Log.info('Test Time {batch_time.sum:.3f}s, ({batch_time.avg:.3f})\t' 'Loss = {0}\n'.format(self.val_losses.info(), batch_time=self.batch_time)) Log.info('Mean IOU: {}\n'.format( self.seg_running_score.get_mean_iou())) Log.info('Pixel ACC: {}\n'.format( self.seg_running_score.get_pixel_acc())) self.batch_time.reset() self.val_losses.reset() self.seg_running_score.reset() self.seg_net.train()
def _predict(self, data_dict): with torch.no_grad(): total_logits = list() results = self.seg_net(data_dict) results = results if isinstance(results, (list, tuple)) else [results] for res in results: assert res['out'].size(0) == 1, 'Only support one image per gpu.' total_logits.append(res['out'].squeeze(0).permute(1, 2, 0).cpu().numpy()) for i, meta in enumerate(DCHelper.tolist(data_dict['meta'])): total_logits[i] = cv2.resize(total_logits[i][:meta['border_wh'][1], :meta['border_wh'][0]], tuple(meta['ori_img_size']), interpolation=cv2.INTER_CUBIC) return total_logits
def _predict(self, data_dict): with torch.no_grad(): total_logits = list() results = self.seg_net(data_dict) for res in results: total_logits.append(res['out'].squeeze(0).permute( 1, 2, 0).cpu().numpy()) for i, meta in enumerate(DCHelper.tolist(data_dict['meta'])): total_logits[i] = cv2.resize( total_logits[i] [:meta['border_hw'][0], :meta['border_hw'][1]], (meta['ori_img_size'][0], meta['ori_img_size'][1]), interpolation=cv2.INTER_CUBIC) return total_logits
def ms_test(self, in_data_dict, params_dict): total_logits = [np.zeros((meta['ori_img_size'][1], meta['ori_img_size'][0], self.configer.get('data', 'num_classes')), np.float32) for meta in DCHelper.tolist(in_data_dict['meta'])] for scale in params_dict['scale_search']: data_dict = self.blob_helper.get_blob(in_data_dict, scale=scale) results = self._predict(data_dict) for i in range(len(total_logits)): total_logits[i] += results[i] for scale in params_dict['scale_search']: data_dict = self.blob_helper.get_blob(in_data_dict, scale=scale, flip=True) results = self._predict(data_dict) for i in range(len(total_logits)): total_logits[i] += results[i][:, ::-1] return total_logits
def _crop_predict(self, data_dict, crop_size, crop_stride_ratio): split_batch = list() height_starts_list = list() width_starts_list = list() hw_list = list() for image in DCHelper.tolist(data_dict['img']): height, width = image.size()[1:] hw_list.append([height, width]) np_image = image.squeeze(0).permute(1, 2, 0).cpu().numpy() height_starts = self._decide_intersection(height, crop_size[1], crop_stride_ratio) width_starts = self._decide_intersection(width, crop_size[0], crop_stride_ratio) split_crops = [] for height in height_starts: for width in width_starts: image_crop = np_image[height:height + crop_size[1], width:width + crop_size[0]] split_crops.append(image_crop[np.newaxis, :]) height_starts_list.append(height_starts) width_starts_list.append(width_starts) split_crops = np.concatenate( split_crops, axis=0) # (n, crop_image_size, crop_image_size, 3) inputs = torch.from_numpy(split_crops).permute(0, 3, 1, 2).to(self.device) split_batch.extend(list(inputs)) out_list = list() print(data_dict['img'].data[0].shape, len(split_batch)) with torch.no_grad(): _len_base = 64 if len(split_batch) > _len_base: #print('my_test') results = [] for i in range(0, len(split_batch) - 1, _len_base): #print(i) torch.cuda.empty_cache() tmp_results = self.seg_net( dict(img=DCHelper.todc( split_batch[i:min(i + _len_base, len(split_batch))], stack=True, samples_per_gpu=True))) results.append( torch.cat([ ele['out'].detach().cpu().permute(0, 2, 3, 1) for ele in tmp_results ])) del tmp_results results = torch.cat(results) results = results.view(len(height_starts_list), -1, results.shape[1], results.shape[2], results.shape[3]) out_list = [ results[i].numpy() for i in range(len(height_starts_list)) ] else: results = self.seg_net( dict(img=DCHelper.todc( split_batch, stack=True, samples_per_gpu=True))) for res in results: out_list.append(res['out'].detach().permute( 0, 2, 3, 1).cpu().numpy()) total_logits = [ np.zeros((hw[0], hw[1], self.configer.get('data', 'num_classes')), np.float32) for hw in hw_list ] count_predictions = [ np.zeros((hw[0], hw[1], self.configer.get('data', 'num_classes')), np.float32) for hw in hw_list ] for i in range(len(height_starts_list)): index = 0 for height in height_starts_list[i]: for width in width_starts_list[i]: total_logits[i][height:height + crop_size[1], width:width + crop_size[0]] += out_list[i][index] count_predictions[i][height:height + crop_size[1], width:width + crop_size[0]] += 1 index += 1 for i in range(len(total_logits)): total_logits[i] /= count_predictions[i] for i, meta in enumerate(DCHelper.tolist(data_dict['meta'])): total_logits[i] = cv2.resize( total_logits[i][:meta['border_wh'][1], :meta['border_wh'][0]], tuple(meta['ori_img_size']), interpolation=cv2.INTER_CUBIC) return total_logits
def test(self, test_dir, out_dir): if self.configer.exists('test', 'mode') and self.configer.get('test', 'mode') == 'nir2vis': jsonA_path = os.path.join(test_dir, 'val_label{}A.json'.format(self.configer.get('data', 'tag'))) test_loader_A = self.test_loader.get_testloader(json_path=jsonA_path) if os.path.exists(jsonA_path) else None jsonB_path = os.path.join(test_dir, 'val_label{}B.json'.format(self.configer.get('data', 'tag'))) test_loader_B = self.test_loader.get_testloader(json_path=jsonB_path) if os.path.exists(jsonB_path) else None else: test_loader_A, test_loader_B = None, None Log.error('Test Mode not Exists!') exit(1) assert test_loader_A is not None and test_loader_B is not None probe_features = [] gallery_features = [] probe_labels = [] gallery_labels = [] for data_dict in test_loader_A: new_data_dict = dict(imgA=data_dict['img']) with torch.no_grad(): out_dict = self.gan_net(new_data_dict, testing=True) meta_list = DCHelper.tolist(data_dict['meta']) for idx in range(len(meta_list)): probe_features.append(out_dict['featA'][idx].cpu().numpy()) probe_labels.append(meta_list[idx]['label']) for key, value in out_dict.items(): for i in range(len(value)): if 'feat' in key: continue img_bgr = self.blob_helper.tensor2bgr(value[i]) img_path = meta_list[i]['img_path'] Log.info('Image Path: {}'.format(img_path)) img_bgr = ImageHelper.resize(img_bgr, target_size=self.configer.get('test', 'out_size'), interpolation='linear') ImageHelper.save(img_bgr, os.path.join(out_dir, key, meta_list[i]['filename'])) for data_dict in test_loader_B: new_data_dict = dict(imgB=data_dict['img']) with torch.no_grad(): out_dict = self.gan_net(new_data_dict, testing=True) meta_list = DCHelper.tolist(data_dict['meta']) for idx in range(len(meta_list)): gallery_features.append(out_dict['feat'][idx].cpu().numpy()) gallery_labels.append(meta_list[idx]['label']) for key, value in out_dict.items(): for i in range(len(value)): if 'feat' in key: continue img_bgr = self.blob_helper.tensor2bgr(value[i]) img_path = meta_list[i]['img_path'] Log.info('Image Path: {}'.format(img_path)) img_bgr = ImageHelper.resize(img_bgr, target_size=self.configer.get('test', 'out_size'), interpolation='linear') ImageHelper.save(img_bgr, os.path.join(out_dir, key, meta_list[i]['filename'])) r_acc, tpr = self.decode(probe_features, gallery_features, probe_labels, gallery_labels) Log.info('Final Rank1 accuracy is {}'.format(r_acc)) Log.info('Final VR@FAR=0.1% accuracy is {}'.format(tpr))
def train(self): """ Train function of every epoch during train phase. """ self.gan_net.train() start_time = time.time() # Adjust the learning rate after every epoch. self.scheduler_G.step(self.runner_state['epoch']) self.scheduler_D.step(self.runner_state['epoch']) for i, data_dict in enumerate(self.train_loader): self.data_time.update(time.time() - start_time) # Forward pass. out_dict = self.gan_net(data_dict) # outputs = self.module_utilizer.gather(outputs) self.optimizer_G.zero_grad() loss_G = out_dict['loss_G'].mean() loss_G.backward() self.optimizer_G.step() self.optimizer_D.zero_grad() loss_D = out_dict['loss_D'].mean() loss_D.backward() self.optimizer_D.step() loss = loss_G + loss_D self.train_losses.update(loss.item(), len(DCHelper.tolist(data_dict['meta']))) # Update the vars of the train phase. self.batch_time.update(time.time() - start_time) start_time = time.time() self.runner_state['iters'] += 1 # Print the log info & reset the states. if self.runner_state['iters'] % self.configer.get( 'solver', 'display_iter') == 0: Log.info( 'Train Epoch: {0}\tTrain Iteration: {1}\t' 'Time {batch_time.sum:.3f}s / {2}iters, ({batch_time.avg:.3f})\t' 'Data load {data_time.sum:.3f}s / {2}iters, ({data_time.avg:3f})\n' 'Learning rate = {3}\tLoss = {loss.val:.8f} (ave = {loss.avg:.8f})\n' .format(self.runner_state['epoch'], self.runner_state['iters'], self.configer.get('solver', 'display_iter'), [ RunnerHelper.get_lr(self.optimizer_G), RunnerHelper.get_lr(self.optimizer_D) ], batch_time=self.batch_time, data_time=self.data_time, loss=self.train_losses)) self.batch_time.reset() self.data_time.reset() self.train_losses.reset() if self.configer.get('solver', 'lr')['metric'] == 'iters' \ and self.runner_state['iters'] == self.configer.get('solver', 'max_iters'): break # Check to val the current model. if self.runner_state['iters'] % self.configer.get( 'solver', 'test_interval') == 0: self.val() self.runner_state['epoch'] += 1