├── dataset └── .gitkeep ├── pretrained_model └── .gitkeep ├── model ├── hrcnet_base │ ├── __init__.py │ └── my_net.py └── general │ ├── sync_batchnorm │ ├── __init__.py │ ├── unittest.py │ ├── replicate.py │ ├── comm.py │ └── batchnorm.py │ ├── backbone │ ├── resnet.py │ └── resnet_lz.py │ └── general.py ├── test.jpg ├── requirements.txt ├── .gitignore ├── README.md ├── dataloader_cut.py ├── annotator.py ├── inference.py ├── main.py ├── utils.py ├── LICENSE ├── helpers.py └── my_custom_transforms.py /dataset/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pretrained_model/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /model/hrcnet_base/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frazerlin/focuscut/HEAD/test.jpg -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch>=0.4.1 2 | torchvision>=0.2.1 3 | scipy 4 | scikit-image 5 | matplotlib 6 | pycocotools 7 | tqdm 8 | opencv-python 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | snapshot 2 | snapshot_ui 3 | dataset/* 4 | !dataset/.gitkeep 5 | pretrained_model/* 6 | !pretrained_model/.gitkeep 7 | **/__pycache__ 8 | **/_ext 9 | **/*.so 10 | record.ods 11 | **/pretrained 12 | -------------------------------------------------------------------------------- /model/general/sync_batchnorm/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # File : __init__.py 3 | # Author : Jiayuan Mao 4 | # Email : maojiayuan@gmail.com 5 | # Date : 27/01/2018 6 | # 7 | # This file is part of Synchronized-BatchNorm-PyTorch. 8 | # https://github.com/vacancy/Synchronized-BatchNorm-PyTorch 9 | # Distributed under MIT License. 10 | 11 | from .batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d 12 | from .replicate import DataParallelWithCallback, patch_replication_callback -------------------------------------------------------------------------------- /model/general/sync_batchnorm/unittest.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # File : unittest.py 3 | # Author : Jiayuan Mao 4 | # Email : maojiayuan@gmail.com 5 | # Date : 27/01/2018 6 | # 7 | # This file is part of Synchronized-BatchNorm-PyTorch. 8 | # https://github.com/vacancy/Synchronized-BatchNorm-PyTorch 9 | # Distributed under MIT License. 10 | 11 | import unittest 12 | 13 | import numpy as np 14 | from torch.autograd import Variable 15 | 16 | 17 | def as_numpy(v): 18 | if isinstance(v, Variable): 19 | v = v.data 20 | return v.cpu().numpy() 21 | 22 | 23 | class TorchTestCase(unittest.TestCase): 24 | def assertTensorClose(self, a, b, atol=1e-3, rtol=1e-3): 25 | npa, npb = as_numpy(a), as_numpy(b) 26 | self.assertTrue( 27 | np.allclose(npa, npb, atol=atol), 28 | 'Tensor close check failed\n{}\n{}\nadiff={}, rdiff={}'.format(a, b, np.abs(npa - npb).max(), np.abs((npa - npb) / np.fmax(npa, 1e-5)).max()) 29 | ) 30 | -------------------------------------------------------------------------------- /model/hrcnet_base/my_net.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from model.general.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d 5 | from model.general.backbone import resnet_lz as resnet 6 | from model.general.general import * 7 | 8 | ########################################[ Net ]######################################## 9 | 10 | class MyNet(MyNetBaseHR): 11 | def __init__(self,input_channel=5, output_stride=16, if_sync_bn=False, if_freeze_bn=False, special_lr=0.1,remain_lr=1.0,size=512,aux_parameter={}): 12 | BatchNorm = SynchronizedBatchNorm2d if if_sync_bn else nn.BatchNorm2d 13 | set_default_dict(aux_parameter,{'into_layer':-1,'if_pre_pred':True,'backward_each':False,'backbone':'resnet50'}) 14 | super(MyNet, self).__init__(input_channel,output_stride,if_sync_bn,if_freeze_bn,special_lr,remain_lr,size,aux_parameter) 15 | print(self.aux_parameter) 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FocusCut 2 | The official PyTorch implementation of oral paper ["FocusCut: Diving into a Focus View in Interactive Segmentation"](https://openaccess.thecvf.com/content/CVPR2022/papers/Lin_FocusCut_Diving_Into_a_Focus_View_in_Interactive_Segmentation_CVPR_2022_paper.pdf) in CVPR2022. 3 | 4 | ## Prepare 5 | See requirements.txt for the environment. 6 | ```shell 7 | pip3 install -r requirements.txt 8 | ``` 9 | Put the pretrained models into the folder "pretrained_model" and the unzipped datasets into the folder "dataset". 10 | 11 | ### Train: 12 | ```shell 13 | CUDA_VISIBLE_DEVICES=0 python main.py -rf -ap "backbone='resnet50'" 14 | ``` 15 | 16 | ### Evalution: 17 | ```shell 18 | CUDA_VISIBLE_DEVICES=0 python main.py -v -r focuscut-resnet50.pth -ap "backbone='resnet50'" -hrv -dv GrabCut,Berkeley,DAVIS 19 | ``` 20 | ### Demo with UI: 21 | ```shell 22 | CUDA_VISIBLE_DEVICES=0 python annotator.py -r focuscut-resnet50.pth -ap "backbone='resnet50'" -hrv -img test.jpg 23 | ``` 24 | 25 | ## Datasets 26 | *(These datasets are organized into a unified format, our Interactive Segmentation Format (ISF)* 27 | - GrabCut ( [GoogleDrive](https://drive.google.com/file/d/1CKzgFbk0guEBpewgpMUaWrM_-KSVSUyg/view?usp=sharing) | [BaiduYun](https://pan.baidu.com/s/1Sc3vcHrocYQr9PCvti1Heg?pwd=2hi9) ) 28 | - Berkeley ([GoogleDrive](https://drive.google.com/file/d/16GD6Ko3IohX8OsSHvemKG8zqY07TIm_i/view?usp=sharing) | [BaiduYun](https://pan.baidu.com/s/16kAidalC5UWy9payMvlTRA?pwd=4w5g) ) 29 | - DAVIS ([GoogleDrive](https://drive.google.com/file/d/1-ZOxk3AJXb4XYIW-7w1-AXtB9c8b3lvi/view?usp=sharing) | [BaiduYun](https://pan.baidu.com/s/1hXXxIfFhpaO8P0YqjQEnvQ?pwd=b5kh) ) 30 | - SBD ([GoogleDrive](https://drive.google.com/file/d/1trmUNY_qI151GiNS3Aqfkskb6kbpam3o/view?usp=sharing) | [BaiduYun](https://pan.baidu.com/s/1ik1pIWCwyKBDq6zsiA0iRA?pwd=t1gk) ) 31 | 32 | ## Pretrained models 33 | - focuscut-resnet50 ([GoogleDrive](https://drive.google.com/file/d/1cNt84bF7p8XYVuVudQlVaTgQyJszw_GC/view?usp=sharing) | [BaiduYun](https://pan.baidu.com/s/14L8AHh4S1bQsxujfNv1xVA?pwd=jjmu) ) 34 | - focuscut-resnet101 ([GoogleDrive](https://drive.google.com/file/d/1tmetXPTWnakghDHhm0uToQUsz2cZIfEL/view?usp=sharing) | [BaiduYun](https://pan.baidu.com/s/1MIE4YhdEmYLxbJya6HqmPQ?pwd=ebmv ) ) 35 | 36 | 37 | ## Citation 38 | If you find this work or code is helpful in your research, please cite: 39 | ``` 40 | @inproceedings{lin2022focuscut, 41 | title={FocusCut: Diving into a Focus View in Interactive Segmentation}, 42 | author={Lin, Zheng and Duan, Zheng-Peng and Zhang, Zhao and Guo, Chun-Le and Cheng, Ming-Ming}, 43 | booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, 44 | pages={2637--2646}, 45 | year={2022} 46 | } 47 | ``` 48 | ## Contact 49 | If you have any questions, feel free to contact me via: `frazer.linzheng(at)gmail.com`. 50 | Welcome to visit [the project page](http://mmcheng.net/focuscut/) or [my home page](https://www.lin-zheng.com/). 51 | 52 | ## License 53 | Licensed under a [Creative Commons Attribution-NonCommercial 4.0 International](https://creativecommons.org/licenses/by-nc/4.0/) for Non-commercial use only. 54 | Any commercial use should get formal permission first. -------------------------------------------------------------------------------- /model/general/sync_batchnorm/replicate.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # File : replicate.py 3 | # Author : Jiayuan Mao 4 | # Email : maojiayuan@gmail.com 5 | # Date : 27/01/2018 6 | # 7 | # This file is part of Synchronized-BatchNorm-PyTorch. 8 | # https://github.com/vacancy/Synchronized-BatchNorm-PyTorch 9 | # Distributed under MIT License. 10 | 11 | import functools 12 | 13 | from torch.nn.parallel.data_parallel import DataParallel 14 | 15 | __all__ = [ 16 | 'CallbackContext', 17 | 'execute_replication_callbacks', 18 | 'DataParallelWithCallback', 19 | 'patch_replication_callback' 20 | ] 21 | 22 | 23 | class CallbackContext(object): 24 | pass 25 | 26 | 27 | def execute_replication_callbacks(modules): 28 | """ 29 | Execute an replication callback `__data_parallel_replicate__` on each module created by original replication. 30 | The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)` 31 | Note that, as all modules are isomorphism, we assign each sub-module with a context 32 | (shared among multiple copies of this module on different devices). 33 | Through this context, different copies can share some information. 34 | We guarantee that the callback on the master copy (the first copy) will be called ahead of calling the callback 35 | of any slave copies. 36 | """ 37 | master_copy = modules[0] 38 | nr_modules = len(list(master_copy.modules())) 39 | ctxs = [CallbackContext() for _ in range(nr_modules)] 40 | 41 | for i, module in enumerate(modules): 42 | for j, m in enumerate(module.modules()): 43 | if hasattr(m, '__data_parallel_replicate__'): 44 | m.__data_parallel_replicate__(ctxs[j], i) 45 | 46 | 47 | class DataParallelWithCallback(DataParallel): 48 | """ 49 | Data Parallel with a replication callback. 50 | An replication callback `__data_parallel_replicate__` of each module will be invoked after being created by 51 | original `replicate` function. 52 | The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)` 53 | Examples: 54 | > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) 55 | > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1]) 56 | # sync_bn.__data_parallel_replicate__ will be invoked. 57 | """ 58 | 59 | def replicate(self, module, device_ids): 60 | modules = super(DataParallelWithCallback, self).replicate(module, device_ids) 61 | execute_replication_callbacks(modules) 62 | return modules 63 | 64 | 65 | def patch_replication_callback(data_parallel): 66 | """ 67 | Monkey-patch an existing `DataParallel` object. Add the replication callback. 68 | Useful when you have customized `DataParallel` implementation. 69 | Examples: 70 | > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) 71 | > sync_bn = DataParallel(sync_bn, device_ids=[0, 1]) 72 | > patch_replication_callback(sync_bn) 73 | # this is equivalent to 74 | > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False) 75 | > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1]) 76 | """ 77 | 78 | assert isinstance(data_parallel, DataParallel) 79 | 80 | old_replicate = data_parallel.replicate 81 | 82 | @functools.wraps(old_replicate) 83 | def new_replicate(module, device_ids): 84 | modules = old_replicate(module, device_ids) 85 | execute_replication_callbacks(modules) 86 | return modules 87 | 88 | data_parallel.replicate = new_replicate -------------------------------------------------------------------------------- /model/general/sync_batchnorm/comm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # File : comm.py 3 | # Author : Jiayuan Mao 4 | # Email : maojiayuan@gmail.com 5 | # Date : 27/01/2018 6 | # 7 | # This file is part of Synchronized-BatchNorm-PyTorch. 8 | # https://github.com/vacancy/Synchronized-BatchNorm-PyTorch 9 | # Distributed under MIT License. 10 | 11 | import queue 12 | import collections 13 | import threading 14 | 15 | __all__ = ['FutureResult', 'SlavePipe', 'SyncMaster'] 16 | 17 | 18 | class FutureResult(object): 19 | """A thread-safe future implementation. Used only as one-to-one pipe.""" 20 | 21 | def __init__(self): 22 | self._result = None 23 | self._lock = threading.Lock() 24 | self._cond = threading.Condition(self._lock) 25 | 26 | def put(self, result): 27 | with self._lock: 28 | assert self._result is None, 'Previous result has\'t been fetched.' 29 | self._result = result 30 | self._cond.notify() 31 | 32 | def get(self): 33 | with self._lock: 34 | if self._result is None: 35 | self._cond.wait() 36 | 37 | res = self._result 38 | self._result = None 39 | return res 40 | 41 | 42 | _MasterRegistry = collections.namedtuple('MasterRegistry', ['result']) 43 | _SlavePipeBase = collections.namedtuple('_SlavePipeBase', ['identifier', 'queue', 'result']) 44 | 45 | 46 | class SlavePipe(_SlavePipeBase): 47 | """Pipe for master-slave communication.""" 48 | 49 | def run_slave(self, msg): 50 | self.queue.put((self.identifier, msg)) 51 | ret = self.result.get() 52 | self.queue.put(True) 53 | return ret 54 | 55 | 56 | class SyncMaster(object): 57 | """An abstract `SyncMaster` object. 58 | - During the replication, as the data parallel will trigger an callback of each module, all slave devices should 59 | call `register(id)` and obtain an `SlavePipe` to communicate with the master. 60 | - During the forward pass, master device invokes `run_master`, all messages from slave devices will be collected, 61 | and passed to a registered callback. 62 | - After receiving the messages, the master device should gather the information and determine to message passed 63 | back to each slave devices. 64 | """ 65 | 66 | def __init__(self, master_callback): 67 | """ 68 | Args: 69 | master_callback: a callback to be invoked after having collected messages from slave devices. 70 | """ 71 | self._master_callback = master_callback 72 | self._queue = queue.Queue() 73 | self._registry = collections.OrderedDict() 74 | self._activated = False 75 | 76 | def __getstate__(self): 77 | return {'master_callback': self._master_callback} 78 | 79 | def __setstate__(self, state): 80 | self.__init__(state['master_callback']) 81 | 82 | def register_slave(self, identifier): 83 | """ 84 | Register an slave device. 85 | Args: 86 | identifier: an identifier, usually is the device id. 87 | Returns: a `SlavePipe` object which can be used to communicate with the master device. 88 | """ 89 | if self._activated: 90 | assert self._queue.empty(), 'Queue is not clean before next initialization.' 91 | self._activated = False 92 | self._registry.clear() 93 | future = FutureResult() 94 | self._registry[identifier] = _MasterRegistry(future) 95 | return SlavePipe(identifier, self._queue, future) 96 | 97 | def run_master(self, master_msg): 98 | """ 99 | Main entry for the master device in each forward pass. 100 | The messages were first collected from each devices (including the master device), and then 101 | an callback will be invoked to compute the message to be sent back to each devices 102 | (including the master device). 103 | Args: 104 | master_msg: the message that the master want to send to itself. This will be placed as the first 105 | message when calling `master_callback`. For detailed usage, see `_SynchronizedBatchNorm` for an example. 106 | Returns: the message to be sent back to the master device. 107 | """ 108 | self._activated = True 109 | 110 | intermediates = [(0, master_msg)] 111 | for i in range(self.nr_slaves): 112 | intermediates.append(self._queue.get()) 113 | 114 | results = self._master_callback(intermediates) 115 | assert results[0][0] == 0, 'The first result should belongs to the master.' 116 | 117 | for i, res in results: 118 | if i == 0: 119 | continue 120 | self._registry[i].result.put(res) 121 | 122 | for i in range(self.nr_slaves): 123 | assert self._queue.get() is True 124 | 125 | return results[0][1] 126 | 127 | @property 128 | def nr_slaves(self): 129 | return len(self._registry) 130 | -------------------------------------------------------------------------------- /dataloader_cut.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import random 4 | import numpy as np 5 | from PIL import Image 6 | from pathlib import Path 7 | from copy import deepcopy 8 | from torch.utils.data import Dataset 9 | from tqdm import tqdm 10 | 11 | #[dataset loader] 12 | class GeneralCutDataset(Dataset): 13 | def __init__(self,dataset_path, list_file='train.txt', 14 | max_num=0, batch_size=0, remove_small_obj=0, 15 | gt_mode='0255',transform=None, if_memory=False, data_loader_num=0): 16 | 17 | super().__init__() 18 | dataset_path=Path(dataset_path) 19 | self.img_paths, self.gt_paths = [], [] 20 | with open(dataset_path/'list'/list_file) as f: 21 | ids = f.read().splitlines() 22 | 23 | img_suffix_ref={file.stem:file.suffix for file in (dataset_path/'img').glob('*.*')} 24 | gt_suffix_ref={file.stem:file.suffix for file in (dataset_path/'gt').glob('*.*')} 25 | 26 | if remove_small_obj!=0: 27 | info_file=dataset_path/'list'/'{}_info.txt'.format(list_file.split('.')[0]) 28 | num_origin = len(ids) 29 | if os.path.exists(info_file): 30 | with open(info_file) as f: 31 | infos = f.read().splitlines() 32 | ids= [info.split()[0] for info in infos if int(info.split()[-1])>=remove_small_obj] 33 | else: 34 | ids = [id for id in tqdm(ids) if (np.array(Image.open(dataset_path/'gt'/(id+gt_suffix_ref[id])))==1).sum()>=remove_small_obj] 35 | 36 | remove_num=num_origin-len(ids) 37 | print('Removed {} objects whose pixel num < {}!'.format(remove_num, remove_small_obj)) 38 | print('Now have {} objects!'.format(len(ids))) 39 | 40 | for id in ids: 41 | self.img_paths.append(dataset_path/'img'/(id.split('#')[0]+img_suffix_ref[id.split('#')[0]])) 42 | self.gt_paths.append(dataset_path/'gt'/(id+gt_suffix_ref[id])) 43 | 44 | if max_num!=0 : 45 | indices= range(min(max_num[0],len(ids)-1), min(max_num[1],len(ids)-1)+1) if isinstance(max_num,(list,tuple)) else (random.sample(range(len(ids)),min(max_num,len(ids))) if max_num>0 else range(min(abs(max_num),len(ids)))) 46 | self.img_paths = [self.img_paths[i] for i in indices] 47 | self.gt_paths = [self.gt_paths[i] for i in indices] 48 | 49 | if batch_size!=0: 50 | actual_num= (len(self.img_paths)//abs(batch_size) + int(batch_size<0 and (len(self.img_paths)%abs(batch_size)!=0)))*abs(batch_size) 51 | self.img_paths= (self.img_paths*abs(batch_size))[:actual_num] 52 | self.gt_paths= (self.gt_paths*abs(batch_size))[:actual_num] 53 | 54 | if if_memory: self.samples=[ self.get_sample(index) for index in range(len(self.img_paths))] 55 | 56 | self.gt_mode,self.transform, self.if_memory= gt_mode, transform, if_memory 57 | 58 | self.ids=[str(Path(gt_path).stem) for gt_path in self.gt_paths] 59 | 60 | self.data_loader_num=data_loader_num 61 | 62 | self.set_index_hash() 63 | 64 | def __len__(self): 65 | return len(self.img_paths) if self.data_loader_num==0 else abs(self.data_loader_num) 66 | 67 | def __getitem__(self, index): 68 | if self.data_loader_num!=0: 69 | index=random.choice(range(len(self.img_paths))) if self.index_hash is None else self.index_hash[index] 70 | if self.if_memory: 71 | return self.transform(deepcopy(self.samples[index])) if self.transform !=None else deepcopy(self.samples[index]) 72 | else: 73 | return self.transform(self.get_sample(index)) if self.transform !=None else self.get_sample(index) 74 | 75 | def get_sample(self,index): 76 | img, gt = np.array(Image.open(self.img_paths[index]).convert('RGB')), np.array(Image.open(self.gt_paths[index])) 77 | if self.gt_mode=='01': 78 | gt=(gt==1).astype(np.uint8) 79 | elif self.gt_mode=='0255': 80 | gt=(gt==1).astype(np.uint8)*255 81 | elif self.gt_mode=='01255': 82 | vp=(gt==255).astype(np.uint8)*255 83 | gt=(gt==1).astype(np.uint8)*255 84 | sample={'img':img,'gt':gt,'vp':vp} if self.gt_mode=='01255' else {'img':img,'gt':gt} 85 | sample['meta']={'id': str(Path(self.gt_paths[index]).stem) ,'img_path': str(self.img_paths[index]), 86 | 'gt_path':str(self.gt_paths[index]), 'source_size':np.array(gt.shape[::-1])} 87 | return sample 88 | 89 | def get_size_div_ids(self,size_div=None): 90 | if size_div is not None and len(size_div): 91 | size_div=np.array(size_div+[1.0]) 92 | size_bucket=[[] for _ in range(len(size_div))] 93 | for gt_path in self.gt_paths: 94 | gt=np.uint8(np.array(Image.open(gt_path))==1) 95 | gt_bbox=cv2.boundingRect(gt) 96 | gt_ratio=(gt_bbox[2]*gt_bbox[3])/(gt.shape[0]*gt.shape[1]) 97 | size_bucket[np.argmax(size_div>=gt_ratio)].append(str(Path(gt_path).stem)) 98 | keys_ref={2:['smaller','larger'],3:['small','middle','large']} 99 | size_bucket_all={keys_ref[len(size_div)][i]:size_bucket[i] for i in range(len(size_div))} 100 | else: 101 | size_bucket_all={} 102 | 103 | size_bucket_all['all']= [str(Path(gt_path).stem) for gt_path in self.gt_paths] 104 | return size_bucket_all 105 | 106 | def set_index_hash(self): 107 | self.index_hash=random.sample(range(len(self.img_paths)),abs(self.data_loader_num)) if self.data_loader_num<0 else None 108 | -------------------------------------------------------------------------------- /annotator.py: -------------------------------------------------------------------------------- 1 | 2 | import cv2 3 | import argparse 4 | import numpy as np 5 | from PIL import Image 6 | from pathlib import Path 7 | import matplotlib as mpl 8 | import matplotlib.pyplot as plt 9 | from copy import deepcopy 10 | from scipy.ndimage.morphology import distance_transform_edt 11 | from torch.utils.data.dataloader import default_collate 12 | 13 | import torch 14 | import utils 15 | import helpers 16 | import my_custom_transforms as mtr 17 | from model.general.sync_batchnorm import patch_replication_callback 18 | 19 | import inference 20 | 21 | ########################################[ Interface ]######################################## 22 | 23 | def init_model(p): 24 | model = CutNet(output_stride=p['output_stride'],if_sync_bn=p['sync_bn'],special_lr=p['special_lr'],size=abs(p['ref_size']),aux_parameter=p['aux_parameter']) 25 | if not p['cpu']: model=model.cuda() 26 | model.eval() 27 | 28 | if p['resume'] is not None: 29 | state_dict=torch.load(p['resume']) if (not p['cpu']) else torch.load(p['resume'] ,map_location=lambda storage, loc: storage) 30 | model.load_state_dict(state_dict) 31 | print('load from [{}]!'.format(p['resume'] )) 32 | return model 33 | 34 | class Annotator(object): 35 | def __init__(self,p): 36 | self.p=p 37 | self.save_path=p['output'] 38 | self.if_cuda=not p['cpu'] 39 | self.model=init_model(p) 40 | self.file = Path(p['image']).name 41 | self.img = np.array(Image.open(p['image']).convert('RGB')) 42 | self.__reset() 43 | 44 | def __gene_merge(self,pred,img,clicks,r=0,cb=2,b=0,if_first=False): 45 | pred_mask=cv2.merge([pred*255,pred*255,np.zeros_like(pred)]) 46 | result= np.uint8(np.clip(img*0.7+pred_mask*0.3,0,255)) 47 | if b>0: 48 | contours,_=cv2.findContours(pred,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 49 | cv2.drawContours(result,contours,-1,(255,255,255),b) 50 | 51 | if r>0: 52 | for pt in clicks: 53 | cv2.circle(result,tuple(pt[:2]),r,(255,0,0) if pt[2]==1 else (0,0,255),-1) 54 | cv2.circle(result,tuple(pt[:2]),r,(255,255,255),cb) 55 | 56 | if if_first and len(clicks)!=0: 57 | cv2.circle(result,tuple(clicks[0,:2]),r,(0,255,0),cb) 58 | return result 59 | 60 | def __update(self): 61 | self.ax.imshow(self.merge) 62 | for t in self.point_show:t.remove() 63 | self.point_show=[] 64 | if len(self.clicks)>0: 65 | pos_clicks=self.clicks[self.clicks[:,2]==1,:] 66 | neg_clicks=self.clicks[self.clicks[:,2]==0,:] 67 | if len(pos_clicks)>0:self.point_show.append(self.ax.scatter(pos_clicks[:,0],pos_clicks[:,1],color='red')) 68 | if len(neg_clicks)>0:self.point_show.append(self.ax.scatter(neg_clicks[:,0],neg_clicks[:,1],color='green')) 69 | self.fig.canvas.draw() 70 | 71 | def __reset(self): 72 | self.clicks = np.empty([0,3],dtype=np.int64) 73 | self.pred = np.zeros(self.img.shape[:2],dtype=np.uint8) 74 | self.merge = self.__gene_merge(self.pred, self.img, self.clicks) 75 | self.sample={'img':self.img,'pre_pred':self.pred} 76 | self.sample['meta']={'id': str(Path(self.p['image']).stem),'img_path' : self.p['image'], 'source_size':np.array(self.img.shape[:2][::-1])} 77 | self.sample_backup=[] 78 | self.hr_points=[] 79 | self.point_show=[] 80 | 81 | def __predict(self): 82 | if len(self.clicks)==1 and self.p['zoom_in']==0: inference.predict_wo(self.p,self.model,self.sample,self.clicks) 83 | pred_tmp,result_tmp = inference.predict_wo(self.p,self.model,self.sample,self.clicks) 84 | 85 | if len(self.clicks)>1 and self.p['model'].startswith('hrcnet') and self.p['hr_val']: 86 | expand_r,if_hr=inference.cal_expand_r_new_final(self.clicks[-1],self.pred,pred_tmp) 87 | if if_hr: 88 | hr_point={'point_num':len(self.clicks),'pt_hr':self.clicks[-1],'expand_r':expand_r,'pre_pred_hr':None,'seq_points_hr':None,'hr_result_src':None,'hr_result_count_src':None} 89 | self.hr_points.append(hr_point) 90 | 91 | self.pred= inference.predict_hr_new_final(self.p,self.model,self.sample,self.clicks,self.hr_points,pred=pred_tmp,result=result_tmp) if len(self.hr_points)>0 else pred_tmp 92 | 93 | self.merge = self.__gene_merge(self.pred, self.img, self.clicks) 94 | self.__update() 95 | 96 | def __on_key_press(self,event): 97 | if event.key=='ctrl+z': 98 | if len(self.clicks)<=1: 99 | self.__reset() 100 | self.__update() 101 | else: 102 | self.clicks=self.clicks[:-1,:] 103 | self.sample_backup.pop() 104 | self.sample=deepcopy(self.sample_backup[-1]) 105 | self.__predict() 106 | 107 | elif event.key=='ctrl+r': 108 | self.__reset() 109 | self.__update() 110 | elif event.key=='escape': 111 | plt.close() 112 | elif event.key=='enter': 113 | if self.save_path is not None: 114 | Image.fromarray(self.pred*255).save(self.save_path) 115 | print('save mask in [{}]!'.format(self.save_path)) 116 | plt.close() 117 | 118 | def __on_button_press(self,event): 119 | if (event.xdata is None) or (event.ydata is None):return 120 | if event.button==1 or event.button==3: 121 | x,y= int(event.xdata+0.5), int(event.ydata+0.5) 122 | self.clicks=np.append(self.clicks,np.array([[x,y,(3-event.button)/2]],dtype=np.int64),axis=0) 123 | self.__predict() 124 | self.sample_backup.append(deepcopy(self.sample)) 125 | 126 | def main(self): 127 | self.fig = plt.figure('Annotator') 128 | self.fig.canvas.mpl_connect('key_press_event', self.__on_key_press) 129 | self.fig.canvas.mpl_connect("button_press_event", self.__on_button_press) 130 | self.fig.suptitle('( file : {} )'.format(self.file),fontsize=16) 131 | self.ax = self.fig.add_subplot(1,1,1) 132 | self.ax.axis('off') 133 | self.ax.imshow(self.merge) 134 | plt.show() 135 | 136 | 137 | if __name__ == "__main__": 138 | p=utils.create_parser() 139 | exec('from model.{}.my_net import MyNet as CutNet'.format(p['model'])) 140 | anno=Annotator(p) 141 | anno.main() 142 | -------------------------------------------------------------------------------- /inference.py: -------------------------------------------------------------------------------- 1 | 2 | import cv2 3 | import numpy as np 4 | from copy import deepcopy 5 | from scipy.ndimage.morphology import distance_transform_edt,distance_transform_cdt 6 | from torch.utils.data.dataloader import default_collate 7 | 8 | import math 9 | import torch 10 | import helpers 11 | import my_custom_transforms as mtr 12 | 13 | # [predict for the whole object] 14 | def predict_wo(p,model,sample,seq_points,mode='eval'): 15 | sample_cpy=deepcopy(sample) 16 | img_size=sample_cpy['img'].shape[:2][::-1] 17 | sample_cpy['seq_points']=seq_points.copy() 18 | 19 | if p['zoom_in']>=0 and len(seq_points)>p['zoom_in'] : mtr.ZoomInVal()(sample_cpy) 20 | 21 | if p['eval_resize_mode']!=-1: 22 | if p['eval_resize_mode']!=1: 23 | mtr.MatchSideResize(size=abs(p['eval_size']),if_short=(p['eval_resize_mode']==0) )(sample_cpy) 24 | else: 25 | mtr.Resize(size=abs(p['eval_size']))(sample_cpy) 26 | 27 | mtr.CatPointMask(mode=p['point_map_mode'], if_repair=False)(sample_cpy) 28 | mtr.ToTensor(div_list=['img'],elems_undo=['seq_points'])(sample_cpy) 29 | mtr.Normalize(mean_std=None if p['no_norm'] else [[0.485, 0.456, 0.406],[0.229, 0.224, 0.225]])(sample_cpy) 30 | sample_batched=default_collate([sample_cpy]) 31 | 32 | with torch.no_grad(): 33 | if p['eval_flip']: 34 | output = model(sample_batched,mode=mode,if_eval_flip=True) #eval flip 35 | else: 36 | output = model(sample_batched,mode=mode) 37 | 38 | result = model.get_result(output,index=0) 39 | 40 | if 'crop_bbox' in sample_cpy['meta']: 41 | sample['meta']['pre_crop_bbox']= sample_cpy['meta']['crop_bbox'] 42 | result=helpers.recover_from_bbox(result,sample_cpy['meta']['crop_bbox'],img_size[::-1]) 43 | else: 44 | result = cv2.resize(result,img_size, interpolation=cv2.INTER_LINEAR) 45 | 46 | pred = (result>p['pred_tsh']).astype(np.uint8) 47 | 48 | sample['pre_pred']=pred 49 | return pred,result 50 | 51 | # [calculate expand radius] 52 | def cal_expand_r_new_final(pt,pre_pred,pred): 53 | pred_delta = np.abs(pred.astype(np.int64) - pre_pred.astype(np.int64)) 54 | 55 | if pred_delta[pt[1],pt[0]]==0: 56 | d=distance_transform_cdt((pre_pred if pre_pred[pt[1],pt[0]]==1 else (1-pre_pred)))[pt[1],pt[0]] 57 | if_hr=True 58 | else: 59 | mask = np.zeros((pred.shape[0] + 2, pred.shape[1] + 2), np.uint8) 60 | pred_delta_new=pred_delta.astype(np.uint8) 61 | cv2.floodFill(pred_delta_new, mask, (pt[0],pt[1]),2) 62 | field = (pred_delta_new == 2).astype(np.uint8) 63 | k = pred.sum() 64 | q = field.sum() 65 | d= np.max(np.abs(np.argwhere(field>0)[:,::-1]- np.array([pt[:2]]))) 66 | if_hr=(q < 0.2 * k) 67 | 68 | d=max(d,5) 69 | return d,if_hr 70 | 71 | # [calculate the ratio of the next expand radius] 72 | def get_new_ratio_final(pre_pred,pred,tsh=5): 73 | r=pre_pred.shape[0]//2 74 | delta=np.uint8(np.abs(pre_pred.astype(np.int64)-pred.astype(np.int64))) 75 | dist=distance_transform_edt(delta) 76 | tsh=pre_pred.shape[0]*tsh/384.0 77 | if dist.max()>=tsh: 78 | dist_max=np.max(np.abs(np.argwhere(dist>=tsh)-np.array([[r,r]]))) 79 | return (dist_max/r)*1.1 80 | else: 81 | return None 82 | 83 | # [predict for the local view] 84 | def predict_hr_new_final(p,model,sample,seq_points,hr_points=[],mode='eval-hr',pred=None,result=None): 85 | initial_ratio=1.75 if p['hr_val_setting']['fv']<=0 else 1.00 86 | turn_num = int(abs(p['hr_val_setting']['pfs'])) 87 | img_size=sample['img'].shape[:2][::-1] 88 | hr_point_idx_ignore=[] 89 | scale_ratios=[initial_ratio]*len(hr_points) 90 | 91 | for turn in range(turn_num): 92 | if len(hr_points)>0: 93 | sample_hrs=[] 94 | for hr_point_idx,hr_point in enumerate(hr_points): 95 | pt_hr=hr_point['pt_hr'] 96 | scale_ratio=scale_ratios[hr_point_idx] 97 | if scale_ratio is None:continue 98 | expand_r=int(hr_point['expand_r']*scale_ratio) 99 | if expand_r<=5:continue 100 | sample_hr = deepcopy(sample) 101 | sample_hr['seq_points']=seq_points.copy() 102 | sample_hr['center_point']=np.array([pt_hr]) 103 | sample_hr['pre_pred']=pred.copy() 104 | crop_bbox=(pt_hr[0],pt_hr[1],2*expand_r+1,2*expand_r+1) 105 | mtr.Crop(crop_bbox,pad=expand_r,elems_point=['seq_points','center_point'])(sample_hr) 106 | if turn==0: 107 | if hr_point['pre_pred_hr'] is not None: 108 | miou=helpers.compute_iou(sample_hr['pre_pred'],hr_point['pre_pred_hr']) 109 | if miou>100000 and len(sample_hr['seq_points_hr'])==len(hr_point['seq_points_hr']) : 110 | hr_point_idx_ignore.append(hr_point_idx) 111 | continue 112 | hr_point['pre_pred_hr']=sample_hr['pre_pred'].copy() 113 | hr_point['seq_points_hr']=sample_hr['seq_points'].copy() 114 | hr_point['img_hr']=sample_hr['img'].copy() 115 | hr_point['crop_bbox_hr']=sample_hr['meta']['crop_bbox'].copy() 116 | hr_point['expand_r_real']=deepcopy(expand_r) 117 | if 'gt' in sample_hr.keys(): 118 | hr_point['gt_hr'] =sample_hr['gt'].copy() 119 | 120 | if hr_point_idx in hr_point_idx_ignore:continue 121 | mtr.Resize(abs(p['hr_size']),elems_point=['seq_points','center_point'])(sample_hr) 122 | sample_hr['img_hr'] = sample_hr.pop('img') 123 | if 'gt' in sample_hr.keys(): sample_hr['gt_hr'] = sample_hr.pop('gt') 124 | sample_hr['seq_points_hr'] = sample_hr.pop('seq_points') 125 | sample_hr['center_point_hr'] = sample_hr.pop('center_point') 126 | sample_hr['pre_pred_hr'] = sample_hr.pop('pre_pred') 127 | mtr.HRCatPointMask(mode=p['point_map_mode'])(sample_hr) 128 | mtr.ToTensor(div_list=['img_hr'],elems_undo=['seq_points_hr','center_point_hr'])(sample_hr) 129 | mtr.Normalize( mean_std= None if p['no_norm'] else [[0.485, 0.456, 0.406],[0.229, 0.224, 0.225]],elems_do=['img_hr'])(sample_hr) 130 | sample_hr['meta']['hr_point_idx']=hr_point_idx 131 | sample_hrs.append(sample_hr) 132 | 133 | if len(sample_hrs)>0: 134 | sample_batched_hr=default_collate(sample_hrs) 135 | with torch.no_grad(): output = model(sample_batched_hr,mode='eval-hr') 136 | 137 | hr_results = model.get_result(output,index=None) 138 | for hr_result, sample_hr in zip(hr_results,sample_hrs): 139 | hr_point_idx=sample_hr['meta']['hr_point_idx'] 140 | pt_hr = hr_points[hr_point_idx]['pt_hr'] 141 | 142 | scale_ratio=scale_ratios[hr_point_idx] 143 | expand_r = int(hr_points[hr_point_idx]['expand_r']*scale_ratio) 144 | 145 | hr_result_count=np.ones_like(hr_result) 146 | crop_bbox=(pt_hr[0],pt_hr[1],2*expand_r+1,2*expand_r+1) 147 | hr_points[hr_point_idx]['hr_result_src']=helpers.recover_from_bbox(hr_result,crop_bbox,np.array(img_size[::-1])+2*expand_r)[expand_r:-expand_r,expand_r:-expand_r] 148 | hr_points[hr_point_idx]['hr_result_count_src']=helpers.recover_from_bbox(hr_result_count,crop_bbox,np.array(img_size[::-1])+2*expand_r)[expand_r:-expand_r,expand_r:-expand_r] 149 | 150 | pfs_d=math.modf(abs(p['hr_val_setting']['pfs']))[0] 151 | 152 | if p['hr_val_setting']['if_fast']: 153 | assert((p['hr_val_setting']['pfs']<0) and (pfs_d>0.01)) 154 | ratio=pfs_d 155 | else: 156 | ratio = get_new_ratio_final(np.uint8(sample_hr['pre_pred_hr'].numpy()[0]>0.5),np.uint8(hr_result>0.5),tsh=2.0) 157 | 158 | if ratio is not None and pfs_d>0.01: 159 | ratio=pfs_d 160 | 161 | scale_ratios[hr_point_idx] = None if ratio is None else max((scale_ratios[hr_point_idx]*ratio),0.2) 162 | 163 | hr_result_src_all,hr_result_count_src_all=np.zeros(img_size[::-1],dtype=np.float64),np.zeros(img_size[::-1],dtype=np.float64) 164 | 165 | for hr_point in hr_points: 166 | hr_result_src_all+=hr_point['hr_result_src'] 167 | hr_result_count_src_all+=hr_point['hr_result_count_src'] 168 | 169 | hr_mask=(hr_result_count_src_all>0) 170 | result[hr_mask]=hr_result_src_all[hr_mask]/hr_result_count_src_all[hr_mask] 171 | 172 | if p['hr_val_setting']['pfs']>0: 173 | pred = (result>p['pred_tsh']).astype(np.uint8) 174 | 175 | pred = (result>p['pred_tsh']).astype(np.uint8) 176 | 177 | for hr_point_idx,hr_point in enumerate(hr_points): 178 | expand_r=hr_point['expand_r_real'] 179 | sample_tmp={'pred':pred.copy(),'meta':{}} 180 | mtr.Crop(crop_bbox=hr_point['crop_bbox_hr'],pad=expand_r)(sample_tmp) 181 | hr_point['pred_hr']=sample_tmp['pred'].copy() 182 | 183 | sample['pre_pred']=pred 184 | return pred 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | -------------------------------------------------------------------------------- /model/general/backbone/resnet.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch.nn as nn 3 | import torch.utils.model_zoo as model_zoo 4 | from model.general.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d 5 | 6 | 7 | class BasicBlock(nn.Module): 8 | expansion = 1 9 | 10 | def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, BatchNorm=None): 11 | super(BasicBlock, self).__init__() 12 | 13 | #self.conv1 = conv3x3(inplanes, planes, stride) 14 | self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 15 | self.bn1 = BatchNorm(planes) 16 | self.relu = nn.ReLU(inplace=True) 17 | 18 | 19 | #self.conv2 = conv3x3(planes, planes) 20 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, dilation=dilation, padding=dilation, bias=False) 21 | self.bn2 = BatchNorm(planes) 22 | self.downsample = downsample 23 | self.stride = stride 24 | 25 | def forward(self, x): 26 | residual = x 27 | 28 | out = self.conv1(x) 29 | out = self.bn1(out) 30 | out = self.relu(out) 31 | 32 | out = self.conv2(out) 33 | out = self.bn2(out) 34 | 35 | if self.downsample is not None: 36 | residual = self.downsample(x) 37 | 38 | out += residual 39 | out = self.relu(out) 40 | 41 | return out 42 | 43 | 44 | class Bottleneck(nn.Module): 45 | expansion = 4 46 | def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, BatchNorm=None): 47 | super(Bottleneck, self).__init__() 48 | self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) 49 | self.bn1 = BatchNorm(planes) 50 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, 51 | dilation=dilation, padding=dilation, bias=False) 52 | self.bn2 = BatchNorm(planes) 53 | self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) 54 | self.bn3 = BatchNorm(planes * 4) 55 | self.relu = nn.ReLU(inplace=True) 56 | self.downsample = downsample 57 | self.stride = stride 58 | self.dilation = dilation 59 | def forward(self, x): 60 | residual = x 61 | 62 | out = self.conv1(x) 63 | out = self.bn1(out) 64 | out = self.relu(out) 65 | 66 | out = self.conv2(out) 67 | out = self.bn2(out) 68 | out = self.relu(out) 69 | 70 | out = self.conv3(out) 71 | out = self.bn3(out) 72 | 73 | if self.downsample is not None: 74 | residual = self.downsample(x) 75 | 76 | out += residual 77 | out = self.relu(out) 78 | 79 | return out 80 | 81 | 82 | class ResNet(nn.Module): 83 | 84 | def __init__(self, block, layers, output_stride, BatchNorm, input_channel=4): 85 | self.input_channel = input_channel 86 | self.inplanes = 64 87 | super(ResNet, self).__init__() 88 | blocks = [1, 2, 4] 89 | if output_stride == 16: 90 | strides = [1, 2, 2, 1] 91 | dilations = [1, 1, 1, 2] 92 | elif output_stride == 8: 93 | strides = [1, 2, 1, 1] 94 | dilations = [1, 1, 2, 4] 95 | else: 96 | raise NotImplementedError 97 | 98 | # Modules 99 | self.conv1 = nn.Conv2d(input_channel, 64, kernel_size=7, stride=2, padding=3, 100 | bias=False) 101 | self.bn1 = BatchNorm(64) 102 | self.relu = nn.ReLU(inplace=True) 103 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 104 | 105 | self.layer1 = self._make_layer(block, 64, layers[0], stride=strides[0], dilation=dilations[0], BatchNorm=BatchNorm) 106 | self.layer2 = self._make_layer(block, 128, layers[1], stride=strides[1], dilation=dilations[1], BatchNorm=BatchNorm) 107 | self.layer3 = self._make_layer(block, 256, layers[2], stride=strides[2], dilation=dilations[2], BatchNorm=BatchNorm) 108 | self.layer4 = self._make_MG_unit(block, 512, blocks=blocks, stride=strides[3], dilation=dilations[3], BatchNorm=BatchNorm) 109 | # self.layer4 = self._make_layer(block, 512, layers[3], stride=strides[3], dilation=dilations[3], BatchNorm=BatchNorm) 110 | 111 | 112 | self._init_weight() 113 | 114 | 115 | def _make_layer(self, block, planes, blocks, stride=1, dilation=1, BatchNorm=None): 116 | downsample = None 117 | if stride != 1 or self.inplanes != planes * block.expansion: 118 | downsample = nn.Sequential( 119 | nn.Conv2d(self.inplanes, planes * block.expansion, 120 | kernel_size=1, stride=stride, bias=False), 121 | BatchNorm(planes * block.expansion), 122 | ) 123 | 124 | layers = [] 125 | layers.append(block(self.inplanes, planes, stride, dilation, downsample, BatchNorm)) 126 | self.inplanes = planes * block.expansion 127 | for i in range(1, blocks): 128 | layers.append(block(self.inplanes, planes, dilation=dilation, BatchNorm=BatchNorm)) 129 | 130 | return nn.Sequential(*layers) 131 | 132 | def _make_MG_unit(self, block, planes, blocks, stride=1, dilation=1, BatchNorm=None): 133 | downsample = None 134 | if stride != 1 or self.inplanes != planes * block.expansion: 135 | downsample = nn.Sequential( 136 | nn.Conv2d(self.inplanes, planes * block.expansion, 137 | kernel_size=1, stride=stride, bias=False), 138 | BatchNorm(planes * block.expansion), 139 | ) 140 | 141 | layers = [] 142 | layers.append(block(self.inplanes, planes, stride, dilation=blocks[0]*dilation, 143 | downsample=downsample, BatchNorm=BatchNorm)) 144 | self.inplanes = planes * block.expansion 145 | for i in range(1, len(blocks)): 146 | layers.append(block(self.inplanes, planes, stride=1, 147 | dilation=blocks[i]*dilation, BatchNorm=BatchNorm)) 148 | 149 | return nn.Sequential(*layers) 150 | 151 | def forward(self, input): 152 | x = self.conv1(input) 153 | x = self.bn1(x) 154 | x = self.relu(x) 155 | x = self.maxpool(x) 156 | 157 | x = self.layer1(x) 158 | l1=x 159 | #low_level_feat = x 160 | #print('l1',x.shape) 161 | x = self.layer2(x) 162 | l2=x 163 | #print('l2',x.shape) 164 | x = self.layer3(x) 165 | l3=x 166 | #print('l3',x.shape) 167 | x = self.layer4(x) 168 | l4=x 169 | #print('l4',x.shape) 170 | #return x, low_level_feat 171 | return l1,l2,l3,l4 172 | 173 | def _init_weight(self): 174 | for m in self.modules(): 175 | if isinstance(m, nn.Conv2d): 176 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 177 | m.weight.data.normal_(0, math.sqrt(2. / n)) 178 | elif isinstance(m, SynchronizedBatchNorm2d): 179 | m.weight.data.fill_(1) 180 | m.bias.data.zero_() 181 | elif isinstance(m, nn.BatchNorm2d): 182 | m.weight.data.fill_(1) 183 | m.bias.data.zero_() 184 | 185 | def _load_pretrained_model(self, pretrain_url): 186 | pretrain_dict = model_zoo.load_url(pretrain_url) 187 | model_dict = {} 188 | state_dict = self.state_dict() 189 | for k, v in pretrain_dict.items(): 190 | if k=='conv1.weight' and self.input_channel>3 : 191 | v_tmp=state_dict[k].clone() 192 | v_tmp[:,:3,:,:]=v.clone() 193 | model_dict[k] = v_tmp 194 | continue 195 | 196 | if k in state_dict: 197 | model_dict[k] = v 198 | state_dict.update(model_dict) 199 | self.load_state_dict(state_dict) 200 | 201 | 202 | 203 | def ResNet18(output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3): 204 | model = ResNet(BasicBlock, [2, 2, 2, 2], output_stride, BatchNorm, input_channel=input_channel) 205 | if pretrained: 206 | model._load_pretrained_model('https://download.pytorch.org/models/resnet18-5c106cde.pth') 207 | return model 208 | 209 | def ResNet34(output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3): 210 | model = ResNet(BasicBlock, [3, 4, 6, 3], output_stride, BatchNorm, input_channel=input_channel) 211 | if pretrained: 212 | model._load_pretrained_model('https://download.pytorch.org/models/resnet34-333f7ec4.pth') 213 | return model 214 | 215 | def ResNet50(output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3): 216 | model = ResNet(Bottleneck, [3, 4, 6, 3], output_stride, BatchNorm, input_channel=input_channel) 217 | if pretrained: 218 | model._load_pretrained_model('https://download.pytorch.org/models/resnet50-19c8e357.pth') 219 | return model 220 | 221 | def ResNet101(output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3): 222 | model = ResNet(Bottleneck, [3, 4, 23, 3], output_stride, BatchNorm, input_channel=input_channel) 223 | if pretrained: 224 | model._load_pretrained_model('https://download.pytorch.org/models/resnet101-5d3b4d8f.pth') 225 | return model 226 | 227 | def ResNet152(output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3): 228 | model = ResNet(Bottleneck, [3, 8, 36, 3], output_stride, BatchNorm, input_channel=input_channel) 229 | if pretrained: 230 | model._load_pretrained_model('https://download.pytorch.org/models/resnet152-b121ed2d.pth') 231 | return model 232 | 233 | 234 | 235 | if __name__ == "__main__": 236 | import torch 237 | model = ResNet101(BatchNorm=nn.BatchNorm2d, pretrained=True, output_stride=8) 238 | input = torch.rand(1, 3, 512, 512) 239 | output, low_level_feat = model(input) 240 | print(output.size()) 241 | print(low_level_feat.size()) 242 | -------------------------------------------------------------------------------- /model/general/backbone/resnet_lz.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch.nn as nn 3 | import torch.utils.model_zoo as model_zoo 4 | 5 | try: 6 | from model.general.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d 7 | except ImportError: 8 | from torch.nn import BatchNorm2d as SynchronizedBatchNorm2d 9 | 10 | class BasicBlock(nn.Module): 11 | expansion = 1 12 | 13 | def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, BatchNorm=None): 14 | super(BasicBlock, self).__init__() 15 | 16 | self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 17 | self.bn1 = BatchNorm(planes) 18 | self.relu = nn.ReLU(inplace=True) 19 | 20 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, dilation=dilation, padding=dilation, bias=False) 21 | self.bn2 = BatchNorm(planes) 22 | self.downsample = downsample 23 | self.stride = stride 24 | 25 | def forward(self, x): 26 | residual = x 27 | 28 | out = self.conv1(x) 29 | out = self.bn1(out) 30 | out = self.relu(out) 31 | 32 | out = self.conv2(out) 33 | out = self.bn2(out) 34 | 35 | if self.downsample is not None: 36 | residual = self.downsample(x) 37 | 38 | out += residual 39 | out = self.relu(out) 40 | 41 | return out 42 | 43 | 44 | class Bottleneck(nn.Module): 45 | expansion = 4 46 | def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, BatchNorm=None): 47 | super(Bottleneck, self).__init__() 48 | self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) 49 | self.bn1 = BatchNorm(planes) 50 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, 51 | dilation=dilation, padding=dilation, bias=False) 52 | self.bn2 = BatchNorm(planes) 53 | self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) 54 | self.bn3 = BatchNorm(planes * 4) 55 | self.relu = nn.ReLU(inplace=True) 56 | self.downsample = downsample 57 | self.stride = stride 58 | self.dilation = dilation 59 | def forward(self, x): 60 | residual = x 61 | 62 | out = self.conv1(x) 63 | out = self.bn1(out) 64 | out = self.relu(out) 65 | 66 | out = self.conv2(out) 67 | out = self.bn2(out) 68 | out = self.relu(out) 69 | 70 | out = self.conv3(out) 71 | out = self.bn3(out) 72 | 73 | if self.downsample is not None: 74 | residual = self.downsample(x) 75 | 76 | out += residual 77 | out = self.relu(out) 78 | 79 | return out 80 | 81 | 82 | class ResNet(nn.Module): 83 | 84 | def __init__(self, block, layers, output_stride, BatchNorm, input_channel=3,if_bloom=True): 85 | super(ResNet, self).__init__() 86 | self.input_channel = input_channel 87 | self.inplanes = 64 88 | 89 | if output_stride==32: 90 | strides = [1, 2, 2, 2] 91 | dilations = [1, 1, 1, 1] 92 | elif output_stride == 16: 93 | strides = [1, 2, 2, 1] 94 | dilations = [1, 1, 1, 2] 95 | elif output_stride == 8: 96 | strides = [1, 2, 1, 1] 97 | dilations = [1, 1, 2, 4] 98 | else: 99 | raise NotImplementedError 100 | 101 | if if_bloom :layers[3]=[1, 2, 4] if layers[3]==3 else [1,2] 102 | 103 | layer0=nn.Sequential( 104 | nn.Conv2d(input_channel, 64, kernel_size=7, stride=2, padding=3, bias=False), 105 | BatchNorm(64), 106 | nn.ReLU(inplace=True), 107 | nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 108 | ) 109 | 110 | layer1 = self._make_layer(block, 64, layers[0], stride=strides[0], dilation=dilations[0], BatchNorm=BatchNorm) 111 | layer2 = self._make_layer(block, 128, layers[1], stride=strides[1], dilation=dilations[1], BatchNorm=BatchNorm) 112 | layer3 = self._make_layer(block, 256, layers[2], stride=strides[2], dilation=dilations[2], BatchNorm=BatchNorm) 113 | layer4 = self._make_layer(block, 512, layers[3], stride=strides[3], dilation=dilations[3], BatchNorm=BatchNorm) 114 | 115 | self.layers=nn.ModuleList([layer0,layer1,layer2,layer3,layer4]) 116 | 117 | self._init_weight() 118 | 119 | 120 | def _make_layer(self, block, planes, blocks, stride=1, dilation=1, BatchNorm=None): 121 | if not isinstance(blocks,list):blocks=[1]*blocks 122 | downsample = None 123 | if stride != 1 or self.inplanes != planes * block.expansion: 124 | downsample = nn.Sequential( 125 | nn.Conv2d(self.inplanes, planes * block.expansion, 126 | kernel_size=1, stride=stride, bias=False), 127 | BatchNorm(planes * block.expansion), 128 | ) 129 | 130 | layers = [] 131 | layers.append(block(self.inplanes, planes, stride, dilation=blocks[0]*dilation, 132 | downsample=downsample, BatchNorm=BatchNorm)) 133 | self.inplanes = planes * block.expansion 134 | for i in range(1, len(blocks)): 135 | layers.append(block(self.inplanes, planes, stride=1, 136 | dilation=blocks[i]*dilation, BatchNorm=BatchNorm)) 137 | 138 | return nn.Sequential(*layers) 139 | 140 | def forward(self, x, return_idx=[1,2,3,4]): 141 | feats=[] 142 | for i in range(5): 143 | x = self.layers[i][:-1](x) if i==0 else self.layers[i](x) 144 | if i in return_idx: feats.append(x) 145 | if i==0:x=self.layers[i][-1](x) 146 | 147 | return feats[0] if len(return_idx)==1 else feats 148 | 149 | def _init_weight(self): 150 | for m in self.modules(): 151 | if isinstance(m, nn.Conv2d): 152 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 153 | m.weight.data.normal_(0, math.sqrt(2. / n)) 154 | elif isinstance(m, nn.BatchNorm2d): 155 | m.weight.data.fill_(1) 156 | m.bias.data.zero_() 157 | elif isinstance(m, SynchronizedBatchNorm2d): 158 | m.weight.data.fill_(1) 159 | m.bias.data.zero_() 160 | 161 | def _load_pretrained_model(self, pretrain_url): 162 | pretrained_model = model_zoo.load_url(pretrain_url) 163 | 164 | src_names=['conv1.weight','bn1.weight','bn1.bias','bn1.running_mean','bn1.running_var'] 165 | dst_names=['layer0.0.weight','layer0.1.weight','layer0.1.bias','layer0.1.running_mean','layer0.1.running_var'] 166 | 167 | for src_name,dst_name in zip(reversed(src_names),reversed(dst_names)): 168 | pretrained_model[dst_name] = pretrained_model.pop(src_name) 169 | pretrained_model.move_to_end(dst_name,last=False) 170 | 171 | pretrained_model.pop('fc.weight') 172 | pretrained_model.pop('fc.bias') 173 | 174 | for src_name in list(pretrained_model.keys()): 175 | pretrained_model['layers.'+ src_name[5:]] = pretrained_model.pop(src_name) 176 | 177 | init_conv=self.state_dict()['layers.0.0.weight'].clone() 178 | #init_conv[:,:,:,:]=0 179 | init_conv[:,:3,:,:]=pretrained_model['layers.0.0.weight'].clone() 180 | pretrained_model['layers.0.0.weight']=init_conv 181 | 182 | self.load_state_dict(pretrained_model) 183 | 184 | def ResNet18(output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3,if_bloom=True,retain_layers=[0,4]): 185 | model = ResNet(BasicBlock, [2, 2, 2, 2], output_stride, BatchNorm, input_channel=input_channel,if_bloom=if_bloom) 186 | if pretrained:model._load_pretrained_model('https://download.pytorch.org/models/resnet18-5c106cde.pth') 187 | model.layers=model.layers[retain_layers[0]:retain_layers[1]+1] 188 | return model 189 | 190 | def ResNet34(output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3,if_bloom=True,retain_layers=[0,4]): 191 | model = ResNet(BasicBlock, [3, 4, 6, 3], output_stride, BatchNorm, input_channel=input_channel,if_bloom=if_bloom) 192 | if pretrained:model._load_pretrained_model('https://download.pytorch.org/models/resnet34-333f7ec4.pth') 193 | model.layers=model.layers[retain_layers[0]:retain_layers[1]+1] 194 | return model 195 | 196 | def ResNet50(output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3,if_bloom=True,retain_layers=[0,4]): 197 | model = ResNet(Bottleneck, [3, 4, 6, 3], output_stride, BatchNorm, input_channel=input_channel,if_bloom=if_bloom) 198 | if pretrained:model._load_pretrained_model('https://download.pytorch.org/models/resnet50-19c8e357.pth') 199 | model.layers=model.layers[retain_layers[0]:retain_layers[1]+1] 200 | return model 201 | 202 | def ResNet101(output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3,if_bloom=True,retain_layers=[0,4]): 203 | model = ResNet(Bottleneck, [3, 4, 23, 3], output_stride, BatchNorm, input_channel=input_channel,if_bloom=if_bloom) 204 | if pretrained:model._load_pretrained_model('https://download.pytorch.org/models/resnet101-5d3b4d8f.pth') 205 | model.layers=model.layers[retain_layers[0]:retain_layers[1]+1] 206 | return model 207 | 208 | def ResNet152(output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3,if_bloom=True,retain_layers=[0,4]): 209 | model = ResNet(Bottleneck, [3, 8, 36, 3], output_stride, BatchNorm, input_channel=input_channel,if_bloom=if_bloom) 210 | if pretrained:model._load_pretrained_model('https://download.pytorch.org/models/resnet152-b121ed2d.pth') 211 | model.layers=model.layers[retain_layers[0]:retain_layers[1]+1] 212 | return model 213 | 214 | def get_resnet_backbone(name='resnet101',output_stride=16, BatchNorm=nn.BatchNorm2d, pretrained=True, input_channel=3,if_bloom=True,retain_layers=[0,4]): 215 | if name=='resnet18': 216 | return ResNet18(output_stride, BatchNorm, pretrained, input_channel,if_bloom,retain_layers) 217 | elif name=='resnet34': 218 | return ResNet34(output_stride, BatchNorm, pretrained, input_channel,if_bloom,retain_layers) 219 | elif name=='resnet50': 220 | return ResNet50(output_stride, BatchNorm, pretrained, input_channel,if_bloom,retain_layers) 221 | elif name=='resnet101': 222 | return ResNet101(output_stride, BatchNorm, pretrained, input_channel,if_bloom,retain_layers) 223 | elif name=='resnet152': 224 | return ResNet152(output_stride, BatchNorm, pretrained, input_channel,if_bloom,retain_layers) 225 | 226 | 227 | if __name__ == "__main__": 228 | import torch 229 | import torchvision 230 | 231 | input=torch.randn([4,3,224,224]) 232 | 233 | for backbone_name in ['resnet18','resnet34','resnet50','resnet101','resnet152'][0:]: 234 | model=get_resnet_backbone(backbone_name,output_stride=32,pretrained=True,input_channel=3,if_bloom=False) 235 | outputs=model(input,return_idx=[0,1,2,3,4]) 236 | 237 | exec('model_src=torchvision.models.{}(pretrained=True)'.format(backbone_name)) 238 | outputs_src=[] 239 | outputs_src.append(model_src.relu(model_src.bn1(model_src.conv1(input)))) 240 | outputs_src.append(model_src.layer1(model_src.maxpool(outputs_src[-1]))) 241 | outputs_src.append(model_src.layer2(outputs_src[-1])) 242 | outputs_src.append(model_src.layer3(outputs_src[-1])) 243 | outputs_src.append(model_src.layer4(outputs_src[-1])) 244 | 245 | print('-'*20+backbone_name+'-'*20) 246 | for output,output_src in zip(outputs,outputs_src): 247 | print(output.shape,output.sum().detach(),output_src.shape,output_src.sum().detach()) 248 | assert((output.shape==output_src.shape) and (output.sum().detach()==output_src.sum().detach())) 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #[General module] 2 | import os 3 | import time 4 | import random 5 | import shutil 6 | import numpy as np 7 | from tqdm import tqdm 8 | 9 | #[Other module] 10 | import torch 11 | from PIL import Image 12 | 13 | #[Personal module] 14 | import utils 15 | import helpers 16 | import my_custom_transforms as mtr 17 | from dataloader_cut import GeneralCutDataset 18 | from model.general.sync_batchnorm import patch_replication_callback 19 | import inference 20 | 21 | #[Basic setting] 22 | TORCH_VERSION=torch.__version__ 23 | torch.backends.cudnn.benchmark = True 24 | np.set_printoptions(precision=3, suppress=True) 25 | 26 | #[Trainer] 27 | class Trainer(object): 28 | def __init__(self,p): 29 | self.p=p 30 | 31 | self.transform_train = mtr.IIS(p) 32 | 33 | self.train_set = GeneralCutDataset(os.path.join(p['dataset_path'],p['dataset_train']),list_file='train.txt',max_num=p['max_num'], 34 | batch_size=-p['batch_size'], remove_small_obj=p['remove_small_obj'],gt_mode=p['gt_mode'],transform=self.transform_train, if_memory=p['if_memory']) 35 | 36 | self.val_robot_sets = [ GeneralCutDataset(os.path.join(p['dataset_path'],dataset_val),list_file='val.txt',max_num=p['max_num_robot_val'],batch_size=0, 37 | remove_small_obj=0,gt_mode=p['gt_mode'],transform=None, if_memory=p['if_memory']) for dataset_val in p['dataset_vals'] ] 38 | 39 | self.train_loader = torch.utils.data.DataLoader(self.train_set, batch_size=p['batch_size'], shuffle=True, num_workers=p['num_workers']) 40 | 41 | self.model = CutNet(output_stride=p['output_stride'],if_sync_bn=p['sync_bn'],special_lr=p['special_lr'],size=abs(p['ref_size']),aux_parameter=p['aux_parameter']).cuda() 42 | 43 | if len(p['gpu_ids'])>1: 44 | self.model = (torch.nn.DataParallel(self.model, device_ids = p['gpu_ids'])) 45 | patch_replication_callback(self.model) 46 | self.model_src=self.model.module 47 | else: 48 | self.model_src=self.model 49 | 50 | self.optimizer = utils.get_optimizer(p['optimizer'], self.model_src.get_train_params_lr(lr=p['learning_rate'])) 51 | self.scheduler = utils.get_lr_scheduler(p['lr_scheduler'], self.optimizer) 52 | self.best_metric = None 53 | 54 | if p['resume'] is not None: 55 | self.model.load_state_dict(torch.load(p['resume'])) 56 | print('Load model from [{}]!'.format(p['resume'])) 57 | 58 | def training(self, epoch): 59 | print('Training :') 60 | mtr.current_epoch = epoch 61 | loss_total,loss_show =0,'Loss: None' 62 | self.model.train() 63 | 64 | if self.p['hr_backbone_frozen']:self.model_src.freeze_main_bn() 65 | 66 | tbar = tqdm(self.train_loader) 67 | for i, sample_batched in enumerate(tbar): 68 | self.optimizer.zero_grad() 69 | 70 | if self.p['seq_mode']: 71 | output,loss_items=self.model(sample_batched) 72 | else: 73 | if self.p['model'].startswith('hrcnet'): 74 | output,loss_items=self.model(sample_batched) 75 | else: 76 | output=self.model(sample_batched) 77 | loss_items=self.model_src.get_loss_union(output,sample_batched=sample_batched) 78 | 79 | loss_total+=loss_items.mean(dim=0).cpu().numpy() 80 | self.optimizer.step() 81 | 82 | loss_show='Loss: {:.3f}{}'.format( loss_total.sum()/(i + 1), '' if len(loss_total)==1 else loss_total / (i + 1)) 83 | tbar.set_description(loss_show) 84 | 85 | if (self.p['itis_pro']>0) and (not self.p['seq_mode']): 86 | preds = np.uint8(self.model_src.get_result(output)>self.p['pred_tsh_itis']) 87 | for j in range(sample_batched['img'].shape[0]): 88 | id=sample_batched['meta']['id'][j] 89 | mtr.record_itis['pred'][id]= helpers.encode_mask(preds[j,:,:]) 90 | seq_points=sample_batched['seq_points'][j].numpy() 91 | mtr.record_itis['seq_points'][id]= seq_points[seq_points[:,2]!=-1].tolist() 92 | mtr.record_itis['crop_bbox'][id]= list(sample_batched['meta']['crop_bbox'][j].numpy()) 93 | 94 | if self.p['random_flip']:mtr.record_itis['if_flip'][id] = int(sample_batched['meta']['if_flip'][j]) 95 | if self.p['random_rotate']:mtr.record_itis['rotate'][id] = int(sample_batched['meta']['rotate'][j]) 96 | 97 | print(loss_show) 98 | 99 | def validation_robot(self, epoch,if_hrv=False): 100 | torch.backends.cudnn.benchmark = False 101 | print('+'*79) 102 | print('if_hrv : ',if_hrv) 103 | self.model.eval() 104 | for index, val_robot_set in enumerate(self.val_robot_sets): 105 | dataset=self.p['dataset_vals'][index] 106 | 107 | if dataset=='DAVIS': 108 | self.p['eval_size']=512 109 | self.p['hr_size']=512 110 | else: 111 | self.p['eval_size']=self.p['ref_size'] 112 | self.p['hr_size']=self.p['ref_size'] 113 | 114 | print('Validation Robot: [{}]'.format(dataset)) 115 | max_miou_target=max(self.p['miou_target'][index]) 116 | 117 | record_other_metrics = {} 118 | 119 | record_dict={} 120 | for i, sample in enumerate(tqdm(val_robot_set)): 121 | id = sample['meta']['id'] 122 | gt = np.array(Image.open(sample['meta']['gt_path'])) 123 | pred = np.zeros_like(gt) 124 | seq_points=np.empty([0,3],dtype=np.int64) 125 | id_preds,id_ious=[helpers.encode_mask(pred)],[0.0] 126 | 127 | id_other_metrics= {metric: [0.0] for metric in self.p['other_metric']} 128 | 129 | hr_points=[] 130 | sample['pre_pred']=pred 131 | 132 | if self.p['zoom_in']==0:inference.predict_wo(self.p,self.model_src,sample,np.array([helpers.get_next_anno_point(np.zeros_like(gt), gt)],dtype=np.int64)) #add -wo 133 | 134 | for point_num in range(1, self.p['max_point_num']+1): 135 | pt_next = helpers.get_next_anno_point(pred, gt, seq_points) 136 | seq_points=np.append(seq_points,[pt_next],axis=0) 137 | pred_tmp,result_tmp = inference.predict_wo(self.p,self.model_src,sample,seq_points) 138 | if point_num>1 and self.p['model'].startswith('hrcnet') and if_hrv and p['hr_val_setting']['pfs']!=0: 139 | expand_r,if_hr=inference.cal_expand_r_new_final(pt_next,pred,pred_tmp) 140 | if if_hr: 141 | hr_point={'point_num':point_num,'pt_hr':pt_next,'expand_r':expand_r,'pre_pred_hr':None,'seq_points_hr':None,'hr_result_src':None,'hr_result_count_src':None,'img_hr':None,'pred_hr':None,'gt_hr':None} 142 | hr_points.append(hr_point) 143 | 144 | pred= inference.predict_hr_new_final(self.p,self.model_src,sample,seq_points,hr_points,pred=pred_tmp,result=result_tmp) if len(hr_points)>0 else pred_tmp 145 | 146 | for metric in id_other_metrics: id_other_metrics[metric].append(helpers.get_metric(pred,gt,metric)) 147 | 148 | miou = ((pred==1)&(gt==1)).sum()/(((pred==1)|(gt==1))&(gt!=255)).sum() 149 | id_ious.append(miou) 150 | id_preds.append(helpers.encode_mask(pred)) 151 | if (np.array(id_ious)>=max_miou_target).any() and point_num>=self.p['record_point_num']:break 152 | 153 | record_dict[id]={'clicks':[None]+[tuple(pt) for pt in seq_points],'preds':id_preds,'ious':id_ious} 154 | record_other_metrics[id]=id_other_metrics 155 | 156 | # #[used for record result file] 157 | # if self.p['record_point_num']>5: 158 | # np.save('{}/{}~{}~{}~infos.npy'.format(self.p['snapshot_path'],'FocusCut',dataset,'val'),record_dict,allow_pickle=True) 159 | 160 | for size_key,size_ids in val_robot_set.get_size_div_ids(size_div=[0.045,0.230][:] if dataset in ['TBD'] else None).items(): 161 | print('[{}]({}):'.format(size_key,len(size_ids))) 162 | if len(size_ids)==0: print('N/A');continue 163 | noc_miou=helpers.get_noc_miou(record_dict,ids=size_ids,point_num=self.p['record_point_num']) 164 | mnoc=helpers.get_mnoc(record_dict,ids=size_ids,iou_targets=self.p['miou_target'][index]) 165 | print('NoC-mIoU : [{}]'.format(' '.join(['{:.3f}'.format(t) for t in noc_miou ]))) 166 | print('mNoC : {}'.format(' '.join(['{:.3f} (@{:.2f})'.format(t1,t2) for t1,t2 in zip(mnoc,self.p['miou_target'][index])]))) 167 | 168 | nof=helpers.get_nof(record_dict,ids=size_ids,iou_targets=self.p['miou_target'][index],max_point_num=self.p['max_point_num']) 169 | print('NoF : {}'.format(' '.join(['{} (@{:.2f})'.format(t1,t2) for t1,t2 in zip(nof,self.p['miou_target'][index])]))) 170 | 171 | for metric in self.p['other_metric']: 172 | metric_mean=np.array([v[metric][:self.p['record_point_num']+1] for v in record_other_metrics.values()]).mean(axis=0) 173 | print('{} : {}'.format(metric,metric_mean)) 174 | 175 | if index==0:current_metric=[mnoc[0],noc_miou] 176 | 177 | torch.backends.cudnn.benchmark = True 178 | return current_metric 179 | 180 | 181 | if __name__ == "__main__": 182 | p=utils.create_parser() 183 | 184 | random.seed(p['seed']) 185 | np.random.seed(p['seed']) 186 | torch.manual_seed(p['seed']) 187 | 188 | exec('from model.{}.my_net import MyNet as CutNet'.format(p['model'])) 189 | 190 | if p['clear_snapshot']:shutil.rmtree('./snapshot');exit() 191 | os.makedirs(p['snapshot_path'],exist_ok=False) 192 | if p['backup_code']: shutil.copytree('.', '{}/code'.format(p['snapshot_path']), ignore=shutil.ignore_patterns('snapshot','__pycache__')) 193 | utils.set_log_file('{}/log.txt'.format(p['snapshot_path'])) 194 | start_time=time.time() 195 | print('Start time : ',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(start_time))) 196 | print('---[ Note:({}) ]---'.format(p['note'])) 197 | print('Using net : [{}]'.format(p['model'])) 198 | print('-'*79,'\ninfos : ' , p, '\n'+'-'*79) 199 | 200 | mine =Trainer(p) 201 | 202 | if p['val']: 203 | mine.validation_robot(0,p['hr_val']) 204 | else: 205 | if TORCH_VERSION[0]=='0': mine.scheduler.step() 206 | for epoch in range(p['epochs']): 207 | lr_str = ['{:.7f}'.format(i) for i in mine.scheduler.get_lr()] 208 | print('-'*79+'\n'+'Epoch [{:03d}]=> |-lr:{}-| ({})\n'.format(epoch, lr_str,p['note'])) 209 | 210 | #training 211 | if p['train_only_epochs']>=0: 212 | mine.training(epoch) 213 | 214 | if (p['lr_scheduler_stop'] is None) or (isinstance(p['lr_scheduler_stop'],int) and epoch
p['lr_scheduler_stop']): 215 | mine.scheduler.step() 216 | 217 | if epoch
0 is standard version,<0 is fast version,pfs=0 is not do
152 | parser.add_argument('-hrvs','--hr_val_setting', type=str, default='pfs=3')
153 | parser.add_argument('-erm','--eval_resize_mode', type=int, default=0, help='-1= not resize,0=short ,1=fix, 2=long')
154 |
155 | #[for cocolvis]
156 | parser.add_argument('-lssi','--lr_scheduler_step_iteration', type=int, default=0)
157 | parser.add_argument('-ein','--epoch_iter_num', type=int, default=1)
158 |
159 | args = parser.parse_args()
160 | p=vars(args)
161 |
162 | #[default]
163 | p['gt_mode']='0255'
164 | p['if_memory']=False
165 | p['pred_tsh']=0.5
166 | p['pred_tsh_itis']=0.5
167 |
168 | from importlib import import_module
169 | p['seq_mode']=(import_module('model.{}.my_net'.format(p['model'])).MyNet.__base__.__name__=='MyNetBaseSeq')
170 |
171 | #[basic]
172 | if p['note'] is None: p['note'] = (' '.join(sys.argv[1:])).replace('/','\\')
173 | if p['test']: p['ref_size'],p['batch_size'],p['max_num']=64,2,'-4'
174 |
175 | #[path and dataset]
176 | if p['snapshot_path']=='auto':
177 | p['snapshot_path']= './snapshot/{}_[{}]_[{}]'.format(p['model'],p['note'],time.strftime('%Y-%m-%d_%H:%M:%S',time.localtime(time.time())))
178 |
179 | p['dataset_vals']=p['dataset_vals'].replace('DT',p['dataset_train']).split(',')
180 |
181 | #[net]
182 | p['aux_parameter']= eval('para2dict({})'.format(p['aux_parameter']))
183 |
184 | #[training data]
185 | p['max_num']=eval(p['max_num'])
186 | if p['max_num_robot_val'] is None: p['max_num_robot_val']= p['max_num']
187 |
188 | #[training process]
189 | p['gpu_ids']= list(range(torch.cuda.device_count())) if p['gpu_ids'] is None else [int(t) for t in p['gpu_ids'].split(',')]
190 | if p['lr_scheduler_stop'] is not None: p['lr_scheduler_stop']=eval(p['lr_scheduler_stop'])
191 |
192 |
193 | #[validation when training]
194 | if p['train_only_epochs'] is None: p['train_only_epochs']=p['epochs']-1
195 |
196 | #[validation only]
197 | if p['resume'] is not None:
198 | if p['resume']=='auto':p['resume']=p['model']
199 | if not p['resume'].endswith('.pth'):p['resume']+='.pth'
200 | if (not os.path.exists(p['resume'])): p['resume']=os.path.join('./pretrained_model',p['resume'])
201 |
202 | if p['eval_size'] is None: p['eval_size']=p['ref_size']
203 |
204 | #[iis]
205 | miou_target_dict={'PASCAL_VOC':[0.85,0.90],'GrabCut':[0.90],'Berkeley':[0.90],'PASCAL_SBD':[0.85,0.90],'SBD':[0.85],'COCO_UNSEEN':[0.85,0.90],'COCO_SEEN':[0.85,0.90],'CoCA':[0.85,0.90],'CoSOD3k':[0.85,0.90]}
206 | p['miou_target']=[ (miou_target_dict[dataset] if dataset in miou_target_dict else [0.85,0.90]) if p['miou_target'] is None else eval(p['miou_target']) for dataset in p['dataset_vals']]
207 | if p['simulate_strategy'] is None:p['simulate_strategy']='first' if p['seq_mode'] else 'fcanet'
208 |
209 | p['other_metric']=[] if p['other_metric'] is None else p['other_metric'].split(',')
210 |
211 | #[aug]
212 | if p['augmentation']=='all': p['augmentation']='bri,con,sat,hue,gam'
213 |
214 | #[focuscut]
215 | if p['hr_size'] is None: p['hr_size']=p['eval_size']
216 |
217 | p['temporary']= eval('para2dict({})'.format(p['temporary']))
218 |
219 | p['hr_val_setting']= eval('para2dict({})'.format(p['hr_val_setting']))
220 |
221 | # fv=-1 is adaptive
222 | hr_val_setting_default={'fv':-1,'pfs':3,'if_fast':False}
223 | for k,v in hr_val_setting_default.items():
224 | if k not in p['hr_val_setting']:
225 | p['hr_val_setting'][k]=v
226 |
227 | print('----->',p['hr_val_setting'])
228 | return p
229 |
230 | ########################################[ Log ]########################################
231 |
232 | class Logger(object):
233 | def __init__(self, filename='default.log', stream=sys.stdout):
234 | self.terminal = stream
235 | self.log = open(filename, 'w')
236 |
237 | def write(self, message):
238 | self.terminal.write(message)
239 | self.log.write(message)
240 |
241 | def flush(self):
242 | pass
243 |
244 | def set_log_file(file_path='log'):
245 | sys.stdout = Logger(file_path, sys.stdout)
246 |
247 | def print_random(num=10000):
248 | import random
249 | import numpy as np
250 | import torch
251 | print(random.randint(1,num),np.random.randint(1,num),torch.randint(num, (1,1)))
252 |
--------------------------------------------------------------------------------
/model/general/sync_batchnorm/batchnorm.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # File : batchnorm.py
3 | # Author : Jiayuan Mao
4 | # Email : maojiayuan@gmail.com
5 | # Date : 27/01/2018
6 | #
7 | # This file is part of Synchronized-BatchNorm-PyTorch.
8 | # https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
9 | # Distributed under MIT License.
10 |
11 | import collections
12 |
13 | import torch
14 | import torch.nn.functional as F
15 |
16 | from torch.nn.modules.batchnorm import _BatchNorm
17 | from torch.nn.parallel._functions import ReduceAddCoalesced, Broadcast
18 |
19 | from .comm import SyncMaster
20 |
21 | __all__ = ['SynchronizedBatchNorm1d', 'SynchronizedBatchNorm2d', 'SynchronizedBatchNorm3d']
22 |
23 |
24 | def _sum_ft(tensor):
25 | """sum over the first and last dimention"""
26 | return tensor.sum(dim=0).sum(dim=-1)
27 |
28 |
29 | def _unsqueeze_ft(tensor):
30 | """add new dementions at the front and the tail"""
31 | return tensor.unsqueeze(0).unsqueeze(-1)
32 |
33 |
34 | _ChildMessage = collections.namedtuple('_ChildMessage', ['sum', 'ssum', 'sum_size'])
35 | _MasterMessage = collections.namedtuple('_MasterMessage', ['sum', 'inv_std'])
36 |
37 |
38 | class _SynchronizedBatchNorm(_BatchNorm):
39 | def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True):
40 | super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine)
41 |
42 | self._sync_master = SyncMaster(self._data_parallel_master)
43 |
44 | self._is_parallel = False
45 | self._parallel_id = None
46 | self._slave_pipe = None
47 |
48 | def forward(self, input):
49 | # If it is not parallel computation or is in evaluation mode, use PyTorch's implementation.
50 | if not (self._is_parallel and self.training):
51 | return F.batch_norm(
52 | input, self.running_mean, self.running_var, self.weight, self.bias,
53 | self.training, self.momentum, self.eps)
54 |
55 | # Resize the input to (B, C, -1).
56 | input_shape = input.size()
57 | input = input.view(input.size(0), self.num_features, -1)
58 |
59 | # Compute the sum and square-sum.
60 | sum_size = input.size(0) * input.size(2)
61 | input_sum = _sum_ft(input)
62 | input_ssum = _sum_ft(input ** 2)
63 |
64 | # Reduce-and-broadcast the statistics.
65 | if self._parallel_id == 0:
66 | mean, inv_std = self._sync_master.run_master(_ChildMessage(input_sum, input_ssum, sum_size))
67 | else:
68 | mean, inv_std = self._slave_pipe.run_slave(_ChildMessage(input_sum, input_ssum, sum_size))
69 |
70 | # Compute the output.
71 | if self.affine:
72 | # MJY:: Fuse the multiplication for speed.
73 | output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std * self.weight) + _unsqueeze_ft(self.bias)
74 | else:
75 | output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std)
76 |
77 | # Reshape it.
78 | return output.view(input_shape)
79 |
80 | def __data_parallel_replicate__(self, ctx, copy_id):
81 | self._is_parallel = True
82 | self._parallel_id = copy_id
83 |
84 | # parallel_id == 0 means master device.
85 | if self._parallel_id == 0:
86 | ctx.sync_master = self._sync_master
87 | else:
88 | self._slave_pipe = ctx.sync_master.register_slave(copy_id)
89 |
90 | def _data_parallel_master(self, intermediates):
91 | """Reduce the sum and square-sum, compute the statistics, and broadcast it."""
92 |
93 | # Always using same "device order" makes the ReduceAdd operation faster.
94 | # Thanks to:: Tete Xiao (http://tetexiao.com/)
95 | intermediates = sorted(intermediates, key=lambda i: i[1].sum.get_device())
96 |
97 | to_reduce = [i[1][:2] for i in intermediates]
98 | to_reduce = [j for i in to_reduce for j in i] # flatten
99 | target_gpus = [i[1].sum.get_device() for i in intermediates]
100 |
101 | sum_size = sum([i[1].sum_size for i in intermediates])
102 | sum_, ssum = ReduceAddCoalesced.apply(target_gpus[0], 2, *to_reduce)
103 | mean, inv_std = self._compute_mean_std(sum_, ssum, sum_size)
104 |
105 | broadcasted = Broadcast.apply(target_gpus, mean, inv_std)
106 |
107 | outputs = []
108 | for i, rec in enumerate(intermediates):
109 | outputs.append((rec[0], _MasterMessage(*broadcasted[i * 2:i * 2 + 2])))
110 |
111 | return outputs
112 |
113 | def _compute_mean_std(self, sum_, ssum, size):
114 | """Compute the mean and standard-deviation with sum and square-sum. This
115 | also maintains the moving average on the master device."""
116 | assert size > 1, 'BatchNorm computes unbiased standard-deviation, which requires size > 1.'
117 | mean = sum_ / size
118 | sumvar = ssum - sum_ * mean
119 | unbias_var = sumvar / (size - 1)
120 | bias_var = sumvar / size
121 |
122 | self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean.data
123 | self.running_var = (1 - self.momentum) * self.running_var + self.momentum * unbias_var.data
124 |
125 | return mean, bias_var.clamp(self.eps) ** -0.5
126 |
127 |
128 | class SynchronizedBatchNorm1d(_SynchronizedBatchNorm):
129 | r"""Applies Synchronized Batch Normalization over a 2d or 3d input that is seen as a
130 | mini-batch.
131 | .. math::
132 | y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
133 | This module differs from the built-in PyTorch BatchNorm1d as the mean and
134 | standard-deviation are reduced across all devices during training.
135 | For example, when one uses `nn.DataParallel` to wrap the network during
136 | training, PyTorch's implementation normalize the tensor on each device using
137 | the statistics only on that device, which accelerated the computation and
138 | is also easy to implement, but the statistics might be inaccurate.
139 | Instead, in this synchronized version, the statistics will be computed
140 | over all training samples distributed on multiple devices.
141 |
142 | Note that, for one-GPU or CPU-only case, this module behaves exactly same
143 | as the built-in PyTorch implementation.
144 | The mean and standard-deviation are calculated per-dimension over
145 | the mini-batches and gamma and beta are learnable parameter vectors
146 | of size C (where C is the input size).
147 | During training, this layer keeps a running estimate of its computed mean
148 | and variance. The running sum is kept with a default momentum of 0.1.
149 | During evaluation, this running mean/variance is used for normalization.
150 | Because the BatchNorm is done over the `C` dimension, computing statistics
151 | on `(N, L)` slices, it's common terminology to call this Temporal BatchNorm
152 | Args:
153 | num_features: num_features from an expected input of size
154 | `batch_size x num_features [x width]`
155 | eps: a value added to the denominator for numerical stability.
156 | Default: 1e-5
157 | momentum: the value used for the running_mean and running_var
158 | computation. Default: 0.1
159 | affine: a boolean value that when set to ``True``, gives the layer learnable
160 | affine parameters. Default: ``True``
161 | Shape:
162 | - Input: :math:`(N, C)` or :math:`(N, C, L)`
163 | - Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input)
164 | Examples:
165 | >>> # With Learnable Parameters
166 | >>> m = SynchronizedBatchNorm1d(100)
167 | >>> # Without Learnable Parameters
168 | >>> m = SynchronizedBatchNorm1d(100, affine=False)
169 | >>> input = torch.autograd.Variable(torch.randn(20, 100))
170 | >>> output = m(input)
171 | """
172 |
173 | def _check_input_dim(self, input):
174 | if input.dim() != 2 and input.dim() != 3:
175 | raise ValueError('expected 2D or 3D input (got {}D input)'
176 | .format(input.dim()))
177 | super(SynchronizedBatchNorm1d, self)._check_input_dim(input)
178 |
179 |
180 | class SynchronizedBatchNorm2d(_SynchronizedBatchNorm):
181 | r"""Applies Batch Normalization over a 4d input that is seen as a mini-batch
182 | of 3d inputs
183 | .. math::
184 | y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
185 | This module differs from the built-in PyTorch BatchNorm2d as the mean and
186 | standard-deviation are reduced across all devices during training.
187 | For example, when one uses `nn.DataParallel` to wrap the network during
188 | training, PyTorch's implementation normalize the tensor on each device using
189 | the statistics only on that device, which accelerated the computation and
190 | is also easy to implement, but the statistics might be inaccurate.
191 | Instead, in this synchronized version, the statistics will be computed
192 | over all training samples distributed on multiple devices.
193 |
194 | Note that, for one-GPU or CPU-only case, this module behaves exactly same
195 | as the built-in PyTorch implementation.
196 | The mean and standard-deviation are calculated per-dimension over
197 | the mini-batches and gamma and beta are learnable parameter vectors
198 | of size C (where C is the input size).
199 | During training, this layer keeps a running estimate of its computed mean
200 | and variance. The running sum is kept with a default momentum of 0.1.
201 | During evaluation, this running mean/variance is used for normalization.
202 | Because the BatchNorm is done over the `C` dimension, computing statistics
203 | on `(N, H, W)` slices, it's common terminology to call this Spatial BatchNorm
204 | Args:
205 | num_features: num_features from an expected input of
206 | size batch_size x num_features x height x width
207 | eps: a value added to the denominator for numerical stability.
208 | Default: 1e-5
209 | momentum: the value used for the running_mean and running_var
210 | computation. Default: 0.1
211 | affine: a boolean value that when set to ``True``, gives the layer learnable
212 | affine parameters. Default: ``True``
213 | Shape:
214 | - Input: :math:`(N, C, H, W)`
215 | - Output: :math:`(N, C, H, W)` (same shape as input)
216 | Examples:
217 | >>> # With Learnable Parameters
218 | >>> m = SynchronizedBatchNorm2d(100)
219 | >>> # Without Learnable Parameters
220 | >>> m = SynchronizedBatchNorm2d(100, affine=False)
221 | >>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45))
222 | >>> output = m(input)
223 | """
224 |
225 | def _check_input_dim(self, input):
226 | if input.dim() != 4:
227 | raise ValueError('expected 4D input (got {}D input)'
228 | .format(input.dim()))
229 | super(SynchronizedBatchNorm2d, self)._check_input_dim(input)
230 |
231 |
232 | class SynchronizedBatchNorm3d(_SynchronizedBatchNorm):
233 | r"""Applies Batch Normalization over a 5d input that is seen as a mini-batch
234 | of 4d inputs
235 | .. math::
236 | y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
237 | This module differs from the built-in PyTorch BatchNorm3d as the mean and
238 | standard-deviation are reduced across all devices during training.
239 | For example, when one uses `nn.DataParallel` to wrap the network during
240 | training, PyTorch's implementation normalize the tensor on each device using
241 | the statistics only on that device, which accelerated the computation and
242 | is also easy to implement, but the statistics might be inaccurate.
243 | Instead, in this synchronized version, the statistics will be computed
244 | over all training samples distributed on multiple devices.
245 |
246 | Note that, for one-GPU or CPU-only case, this module behaves exactly same
247 | as the built-in PyTorch implementation.
248 | The mean and standard-deviation are calculated per-dimension over
249 | the mini-batches and gamma and beta are learnable parameter vectors
250 | of size C (where C is the input size).
251 | During training, this layer keeps a running estimate of its computed mean
252 | and variance. The running sum is kept with a default momentum of 0.1.
253 | During evaluation, this running mean/variance is used for normalization.
254 | Because the BatchNorm is done over the `C` dimension, computing statistics
255 | on `(N, D, H, W)` slices, it's common terminology to call this Volumetric BatchNorm
256 | or Spatio-temporal BatchNorm
257 | Args:
258 | num_features: num_features from an expected input of
259 | size batch_size x num_features x depth x height x width
260 | eps: a value added to the denominator for numerical stability.
261 | Default: 1e-5
262 | momentum: the value used for the running_mean and running_var
263 | computation. Default: 0.1
264 | affine: a boolean value that when set to ``True``, gives the layer learnable
265 | affine parameters. Default: ``True``
266 | Shape:
267 | - Input: :math:`(N, C, D, H, W)`
268 | - Output: :math:`(N, C, D, H, W)` (same shape as input)
269 | Examples:
270 | >>> # With Learnable Parameters
271 | >>> m = SynchronizedBatchNorm3d(100)
272 | >>> # Without Learnable Parameters
273 | >>> m = SynchronizedBatchNorm3d(100, affine=False)
274 | >>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45, 10))
275 | >>> output = m(input)
276 | """
277 |
278 | def _check_input_dim(self, input):
279 | if input.dim() != 5:
280 | raise ValueError('expected 5D input (got {}D input)'
281 | .format(input.dim()))
282 | super(SynchronizedBatchNorm3d, self)._check_input_dim(input)
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | ## creative commons
2 |
3 | # Attribution-NonCommercial 4.0 International
4 |
5 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
6 |
7 | ### Using Creative Commons Public Licenses
8 |
9 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
10 |
11 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
12 |
13 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
14 |
15 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License
16 |
17 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
18 |
19 | ### Section 1 – Definitions.
20 |
21 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
22 |
23 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
24 |
25 | c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
26 |
27 | d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
28 |
29 | e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
30 |
31 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
32 |
33 | g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
34 |
35 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
36 |
37 | i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
38 |
39 | j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
40 |
41 | k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
42 |
43 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
44 |
45 | ### Section 2 – Scope.
46 |
47 | a. ___License grant.___
48 |
49 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
50 |
51 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
52 |
53 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
54 |
55 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
56 |
57 | 3. __Term.__ The term of this Public License is specified in Section 6(a).
58 |
59 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
60 |
61 | 5. __Downstream recipients.__
62 |
63 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
64 |
65 | B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
66 |
67 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
68 |
69 | b. ___Other rights.___
70 |
71 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
72 |
73 | 2. Patent and trademark rights are not licensed under this Public License.
74 |
75 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
76 |
77 | ### Section 3 – License Conditions.
78 |
79 | Your exercise of the Licensed Rights is expressly made subject to the following conditions.
80 |
81 | a. ___Attribution.___
82 |
83 | 1. If You Share the Licensed Material (including in modified form), You must:
84 |
85 | A. retain the following if it is supplied by the Licensor with the Licensed Material:
86 |
87 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
88 |
89 | ii. a copyright notice;
90 |
91 | iii. a notice that refers to this Public License;
92 |
93 | iv. a notice that refers to the disclaimer of warranties;
94 |
95 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
96 |
97 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
98 |
99 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
100 |
101 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
102 |
103 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
104 |
105 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
106 |
107 | ### Section 4 – Sui Generis Database Rights.
108 |
109 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
110 |
111 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
112 |
113 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
114 |
115 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
116 |
117 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
118 |
119 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability.
120 |
121 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
122 |
123 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
124 |
125 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
126 |
127 | ### Section 6 – Term and Termination.
128 |
129 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
130 |
131 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
132 |
133 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
134 |
135 | 2. upon express reinstatement by the Licensor.
136 |
137 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
138 |
139 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
140 |
141 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
142 |
143 | ### Section 7 – Other Terms and Conditions.
144 |
145 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
146 |
147 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
148 |
149 | ### Section 8 – Interpretation.
150 |
151 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
152 |
153 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
154 |
155 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
156 |
157 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
158 |
159 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
160 | >
161 | > Creative Commons may be contacted at creativecommons.org
162 |
163 | Copyright (c) 2022 MCG-NKU
164 |
--------------------------------------------------------------------------------
/model/general/general.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | from model.general.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
5 | import random
6 | import numpy as np
7 | from model.general.backbone import resnet_lz as resnet
8 |
9 | ########################################[ Global Function ]########################################
10 |
11 | def init_weight(model):
12 | for m in model.modules():
13 | if isinstance(m, nn.Conv2d):
14 | torch.nn.init.kaiming_normal_(m.weight)
15 | elif isinstance(m, SynchronizedBatchNorm2d):
16 | m.weight.data.fill_(1)
17 | m.bias.data.zero_()
18 | elif isinstance(m, nn.BatchNorm2d):
19 | m.weight.data.fill_(1)
20 | m.bias.data.zero_()
21 |
22 | def freeze_bn(model):
23 | for m in model.modules():
24 | if isinstance(m, SynchronizedBatchNorm2d):
25 | m.eval()
26 | elif isinstance(m, nn.BatchNorm2d):
27 | m.eval()
28 |
29 | def gene_map_gauss(map_dist_src, sigma=10):
30 | return torch.exp(-2.772588722*(map_dist_src**2)/(sigma**2))
31 |
32 | def gene_map_dist(map_dist_src, max_dist=255):
33 | return 1.0-map_dist_src/max_dist
34 |
35 | def my_resize(input,ref):
36 | return F.interpolate(input, size=(ref if isinstance(ref,(list,tuple)) else ref.size()[2:]), mode='bilinear', align_corners=True)
37 |
38 | def make_list(input):
39 | return [] if input is None else (list(input) if isinstance(input,(list,tuple)) else [input])
40 |
41 | def point_resize(mask,ref,if_return_mask=True,tsh=0.5):
42 | mask_h, mask_w = mask.shape[2:4]
43 | ref_h, ref_w = ref if isinstance(ref,(tuple,list)) else ref.shape[2:4]
44 | indices=torch.nonzero(mask>tsh)
45 | if mask_h==ref_h and mask_w==ref_w:
46 | mask_new= mask
47 | else:
48 | mask_new=torch.zeros([mask.shape[0],mask.shape[1],ref_h,ref_w])
49 | if len(indices)!=0:
50 | indices = indices.float()
51 | indices[:,2] = torch.floor(indices[:,2]*ref_h/mask_h)
52 | indices[:,3] = torch.floor(indices[:,3]*ref_w/mask_w)
53 | indices = indices.long()
54 | mask_new[indices[:,0],indices[:,1],indices[:,2],indices[:,3]]=1
55 | return mask_new.float().cuda() if if_return_mask else indices
56 |
57 | def to_cuda(input):
58 | if isinstance(input,list):
59 | return [tmp.cuda() for tmp in input]
60 | elif isinstance(input,dict):
61 | return {key:input[key].cuda() for key in input}
62 | else:
63 | raise ValueError('Wrong Type!')
64 |
65 | def get_key_sample(sample_batched,keys=['img'],if_list=True,if_cuda=True):
66 | if not isinstance(keys,list): keys=[keys]
67 | key_sample=[sample_batched[key] for key in keys] if if_list else {key:sample_batched[key] for key in keys}
68 | if if_cuda: key_sample=to_cuda(key_sample)
69 | return key_sample
70 |
71 | def set_default_dict(src_dict, default_map):
72 | for k,v in default_map.items():
73 | if k not in src_dict:
74 | src_dict[k]=v
75 |
76 | def get_click_map(sample_batched,mode='dist',click_keys=None):
77 | mode_split=mode.split('-')
78 | if len(mode_split)==1:
79 | if_with_para=False
80 | else:
81 | if_with_para=True
82 | para=mode_split[-1]
83 |
84 | if mode.startswith('dist'):
85 | if click_keys is None: click_keys=['pos_map_dist_src','neg_map_dist_src']
86 | click_map = torch.cat([(gene_map_dist(t,int(para)) if if_with_para else gene_map_dist(t)) for t in get_key_sample(sample_batched,click_keys,if_list=True)],dim=1)
87 | elif mode.startswith('gauss'):
88 | if click_keys is None: click_keys=['pos_map_dist_src','neg_map_dist_src']
89 | click_map = torch.cat([(gene_map_gauss(t,int(para)) if if_with_para else gene_map_gauss(t)) for t in get_key_sample(sample_batched,click_keys,if_list=True)],dim=1)
90 | elif mode=='point':
91 | if click_keys is None: click_keys=['pos_points_mask','neg_points_mask']
92 | click_map = torch.cat(get_key_sample(sample_batched,click_keys,if_list=True), dim=1)
93 | elif mode=='first_point':
94 | if click_keys is None: click_keys=['first_point_mask']
95 | click_map = get_key_sample(sample_batched,click_keys,if_list=True)[0]
96 | elif mode=='first_dist':
97 | if click_keys is None: click_keys=['first_map_dist_src']
98 | click_map = gene_map_dist(get_key_sample(sample_batched,click_keys,if_list=True)[0])
99 | return click_map
100 |
101 | def get_input(sample_batched,mode='dist'):
102 | img=get_key_sample(sample_batched,['img'],if_list=True)[0]
103 | if mode in ['dist','gauss','point']:
104 | x= torch.cat((img, get_click_map(sample_batched,mode)),dim=1)
105 | elif mode in ['none','img']:
106 | x=img
107 | else:
108 | raise ValueError('mode')
109 | return x
110 |
111 | def get_stack_flip_feat(x,if_horizontal=True):
112 | x_flip= torch.flip(x,[3 if if_horizontal else 2])
113 | return torch.cat([x,x_flip],dim=0)
114 |
115 | def merge_stack_flip_result(x,if_horizontal=True,batch_num=1):
116 | return (x[:batch_num]+ torch.flip(x[batch_num:2*batch_num],[3 if if_horizontal else 2]))/2.0
117 |
118 |
119 | ########################################[ MultiConv ]########################################
120 |
121 | class MultiConv(nn.Module):
122 | def __init__(self,in_ch, channels, kernel_sizes=None, strides=None, dilations=None, paddings=None, BatchNorm=nn.BatchNorm2d,if_w_bn=True,if_end_wo_relu=False, block_kind='conv'):
123 | super(MultiConv, self).__init__()
124 | self.num=len(channels)
125 | if kernel_sizes is None: kernel_sizes=[ 3 for c in channels]
126 | if strides is None: strides=[ 1 for c in channels]
127 | if dilations is None: dilations=[ 1 for c in channels]
128 | if paddings is None: paddings = [ ( (kernel_sizes[i]//2) if dilations[i]==1 else (kernel_sizes[i]//2 * dilations[i]) ) for i in range(self.num)]
129 | convs_tmp=[]
130 | for i in range(self.num):
131 | if block_kind=='conv':
132 | if channels[i]==1 or if_end_wo_relu:
133 | convs_tmp.append(nn.Conv2d( in_ch if i==0 else channels[i-1] , channels[i], kernel_size=kernel_sizes[i], stride=strides[i], padding=paddings[i], dilation=dilations[i]))
134 | else:
135 | if if_w_bn:
136 | convs_tmp.append(nn.Sequential(nn.Conv2d( in_ch if i==0 else channels[i-1] , channels[i], kernel_size=kernel_sizes[i], stride=strides[i], padding=paddings[i], dilation=dilations[i],bias=False), BatchNorm(channels[i]), nn.ReLU(inplace=True)))
137 | else:
138 | convs_tmp.append(nn.Sequential(nn.Conv2d( in_ch if i==0 else channels[i-1] , channels[i], kernel_size=kernel_sizes[i], stride=strides[i], padding=paddings[i], dilation=dilations[i],bias=False), nn.ReLU(inplace=True)))
139 | elif block_kind=='bottleneck':
140 | in_ch_cur= in_ch if i==0 else channels[i-1]
141 | out_ch_cur=channels[i]
142 | down_sample_cur = None if in_ch_cur==out_ch_cur else nn.Sequential(nn.Conv2d(in_ch_cur,out_ch_cur,kernel_size=1, stride=strides[i], bias=False),BatchNorm(out_ch_cur))
143 | convs_tmp.append(resnet.Bottleneck(in_ch_cur,out_ch_cur//4,strides[i],dilations[i],down_sample_cur,BatchNorm))
144 |
145 | self.convs=nn.Sequential(*convs_tmp)
146 | init_weight(self)
147 | def forward(self, x):
148 | return self.convs(x)
149 |
150 | ########################################[ MyASPP ]########################################
151 |
152 | class _ASPPModule(nn.Module):
153 | def __init__(self, inplanes, planes, kernel_size, padding, dilation, BatchNorm=nn.BatchNorm2d):
154 | super(_ASPPModule, self).__init__()
155 | self.atrous_conv = nn.Conv2d(inplanes, planes, kernel_size=kernel_size, stride=1, padding=padding, dilation=dilation, bias=False)
156 | self.bn = BatchNorm(planes)
157 | self.relu = nn.ReLU(inplace=True)
158 | init_weight(self)
159 |
160 | def forward(self, x):
161 | x = self.relu(self.bn(self.atrous_conv(x)))
162 | return x
163 |
164 | class MyASPP(nn.Module):
165 | def __init__(self, in_ch, out_ch, dilations, BatchNorm=nn.BatchNorm2d, if_global=True):
166 | super(MyASPP, self).__init__()
167 | self.if_global = if_global
168 |
169 | if len(dilations)==4 and dilations[0]==1: dilations=dilations[1:]
170 | assert len(dilations)==3
171 |
172 | self.aspp1 = _ASPPModule(in_ch, out_ch, 1, padding=0, dilation=1, BatchNorm=BatchNorm)
173 | self.aspp2 = _ASPPModule(in_ch, out_ch, 3, padding=dilations[0], dilation=dilations[0], BatchNorm=BatchNorm)
174 | self.aspp3 = _ASPPModule(in_ch, out_ch, 3, padding=dilations[1], dilation=dilations[1], BatchNorm=BatchNorm)
175 | self.aspp4 = _ASPPModule(in_ch, out_ch, 3, padding=dilations[2], dilation=dilations[2], BatchNorm=BatchNorm)
176 |
177 | if if_global:
178 | self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
179 | nn.Conv2d(in_ch, out_ch, 1, stride=1, bias=False),
180 | BatchNorm(out_ch),
181 | nn.ReLU(inplace=True))
182 |
183 | merge_channel=out_ch*5 if if_global else out_ch*4
184 |
185 | self.conv1 = nn.Conv2d(merge_channel, out_ch, 1, bias=False)
186 | self.bn1 = BatchNorm(out_ch)
187 | self.relu = nn.ReLU(inplace=True)
188 | init_weight(self)
189 |
190 | def forward(self, x):
191 | x1 = self.aspp1(x)
192 | x2 = self.aspp2(x)
193 | x3 = self.aspp3(x)
194 | x4 = self.aspp4(x)
195 |
196 | if self.if_global:
197 | x5 = self.global_avg_pool(x)
198 | x5 = F.interpolate(x5, size=x4.size()[2:], mode='bilinear', align_corners=True)
199 | x = torch.cat((x1, x2, x3, x4, x5), dim=1)
200 | else:
201 | x = torch.cat((x1, x2, x3, x4), dim=1)
202 |
203 | x = self.conv1(x)
204 | x = self.bn1(x)
205 | x = self.relu(x)
206 | return x
207 |
208 | ########################################[ MyDecoder ]########################################
209 |
210 | class MyDecoder(nn.Module):
211 | def __init__(self, in_ch, in_ch_reduce, side_ch, side_ch_reduce, out_ch, BatchNorm=nn.BatchNorm2d, size_ref='side'):
212 | super(MyDecoder, self).__init__()
213 | self.size_ref=size_ref
214 | self.relu = nn.ReLU(inplace=True)
215 | self.in_ch_reduce, self.side_ch_reduce = in_ch_reduce, side_ch_reduce
216 |
217 | if in_ch_reduce is not None:
218 | self.in_conv = nn.Sequential( nn.Conv2d(in_ch, in_ch_reduce, 1, bias=False), BatchNorm(in_ch_reduce), nn.ReLU(inplace=True))
219 | if side_ch_reduce is not None:
220 | self.side_conv = nn.Sequential( nn.Conv2d(side_ch, side_ch_reduce, 1, bias=False), BatchNorm(side_ch_reduce), nn.ReLU(inplace=True))
221 |
222 | merge_ch= (in_ch_reduce if in_ch_reduce is not None else in_ch) + (side_ch_reduce if side_ch_reduce is not None else side_ch)
223 |
224 | self.merge_conv = nn.Sequential(nn.Conv2d(merge_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=False),
225 | BatchNorm(out_ch),
226 | nn.ReLU(inplace=True),
227 | nn.Conv2d(out_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=False),
228 | BatchNorm(out_ch),
229 | nn.ReLU(inplace=True))
230 | init_weight(self)
231 |
232 | def forward(self, input, side):
233 | if self.in_ch_reduce is not None:
234 | input=self.in_conv(input)
235 | if self.side_ch_reduce is not None:
236 | side=self.side_conv(side)
237 |
238 | if self.size_ref=='side':
239 | input=F.interpolate(input, size=side.size()[2:], mode='bilinear', align_corners=True)
240 | elif self.size_ref=='input':
241 | side=F.interpolate(side, size=input.size()[2:], mode='bilinear', align_corners=True)
242 |
243 | merge=torch.cat((input, side), dim=1)
244 | output=self.merge_conv(merge)
245 | return output
246 |
247 | ########################################[ PredDecoder ]########################################
248 |
249 | class PredDecoder(nn.Module):
250 | def __init__(self,in_ch,layer_num=1,BatchNorm=nn.BatchNorm2d,if_sigmoid=False):
251 | super(PredDecoder, self).__init__()
252 | convs_tmp=[]
253 | for i in range(layer_num-1):
254 | convs_tmp.append(nn.Sequential(nn.Conv2d(in_ch,in_ch//2,kernel_size=3,stride=1,padding=1,bias=False), BatchNorm(in_ch//2), nn.ReLU(inplace=True)))
255 | in_ch=in_ch//2
256 | convs_tmp.append(nn.Conv2d(in_ch,1,kernel_size=1,stride=1))
257 | if if_sigmoid: convs_tmp.append(nn.Sigmoid())
258 | self.pred_conv=nn.Sequential(*convs_tmp)
259 | init_weight(self)
260 | def forward(self, input):
261 | return self.pred_conv(input)
262 |
263 | ########################################[ Template for IIS ]########################################
264 |
265 | class MyNetBase(nn.Module):
266 | def __init__(self,special_lr=0.1,remain_lr=1.0,size=512,aux_parameter={}):
267 | super(MyNetBase, self).__init__()
268 | self.diy_lr=[]
269 | self.special_lr=special_lr
270 | self.remain_lr=remain_lr
271 | self.size=size
272 | self.aux_parameter=aux_parameter
273 |
274 | def get_params(self,modules):
275 | for i in range(len(modules)):
276 | for m in modules[i].named_modules():
277 | if isinstance(m[1], nn.Conv2d) or isinstance(m[1], nn.BatchNorm2d) or isinstance(m[1], SynchronizedBatchNorm2d):
278 | for p in m[1].parameters():
279 | if p.requires_grad:
280 | yield p
281 |
282 | def get_train_params_lr(self, lr):
283 | train_params,special_modules=[],[]
284 | for modules,ratio in self.diy_lr:
285 | train_params.append({'params':self.get_params(modules),'lr':lr*ratio})
286 | special_modules+=modules
287 | remain_modules=[ module for module in self.children() if module not in special_modules ]
288 | train_params.append({'params':self.get_params(remain_modules),'lr':lr*self.remain_lr})
289 | return train_params
290 |
291 | #can change
292 | def get_loss(self, output, gt=None,sample_batched=None,others=None):
293 | if gt is None:gt=sample_batched['gt'].cuda()
294 | losses = [F.binary_cross_entropy_with_logits(my_resize(t,gt),gt) for t in make_list(output)]
295 | return losses
296 |
297 | def get_loss_union(self,output,gt=None,sample_batched=None,others=None):
298 | losses=self.get_loss(output,gt,sample_batched,others)
299 | loss_items=torch.Tensor([loss.item() for loss in losses]).unsqueeze(0)
300 | losses=sum(losses)
301 | losses.backward()
302 | return loss_items
303 |
304 | def get_result(self, output, index=None):
305 | result = torch.sigmoid((make_list(output))[0]).data.cpu().numpy()
306 | return result[:,0,:,:] if index is None else result[index,0,:,:]
307 |
308 | def forward_union(self, sample_batched, mode='train'):
309 | output=self.forward(sample_batched,mode)
310 | if mode=='train':
311 | loss_items = self.get_loss(output,sample_batched=sample_batched)
312 | return output,loss_items
313 | else:
314 | return output
315 |
316 |
317 | ########################################[ Template for FocusCut ]########################################
318 |
319 | class MyNetBaseHR(MyNetBase):
320 | def __init__(self,input_channel=5, output_stride=16, if_sync_bn=False, if_freeze_bn=False, special_lr=0.1,remain_lr=1.0,size=512,aux_parameter={}):
321 | super(MyNetBaseHR, self).__init__(special_lr,remain_lr,size,aux_parameter)
322 |
323 | BatchNorm = SynchronizedBatchNorm2d if if_sync_bn else nn.BatchNorm2d
324 | default_map={'backbone':'resnet50','point_map':'gauss','into_layer':-1,'pretrained':True,'if_pre_pred':True,'weight_loss':False,'backward_each':False}
325 | set_default_dict(self.aux_parameter,default_map)
326 |
327 | side_chs=[64,256,512,1024,2048] if self.aux_parameter['backbone'] in ['resnet50','resnet101','resnet152'] else [64,64,128,256,512]
328 | self.backbone = resnet.get_resnet_backbone(self.aux_parameter['backbone'],output_stride,BatchNorm,self.aux_parameter['pretrained'],(3 if self.aux_parameter['into_layer']>=0 else (5+int(self.aux_parameter['if_pre_pred']))),True)
329 | self.my_aspp = MyASPP(in_ch=side_chs[-1],out_ch=side_chs[-1]//8,dilations=[int(i*size/512 + 0.5)*(16//output_stride) for i in [6, 12, 18]],BatchNorm=BatchNorm, if_global=True)
330 | self.my_decoder=MyDecoder(in_ch=side_chs[-1]//8, in_ch_reduce=None, side_ch=side_chs[-1]//8, side_ch_reduce=side_chs[1]//16*3,out_ch=side_chs[-1]//8,BatchNorm=BatchNorm)
331 | self.pred_decoder=PredDecoder(in_ch=side_chs[-1]//8, BatchNorm=BatchNorm)
332 |
333 | if self.aux_parameter['into_layer']!=-1:
334 | in_ch= 3 if self.aux_parameter['into_layer']==0 else side_chs[self.aux_parameter['into_layer']-1]
335 | self.encoder_anno=nn.Sequential( nn.Conv2d(in_ch+2+int(self.aux_parameter['if_pre_pred']),in_ch , 1, bias=False), BatchNorm(in_ch), nn.ReLU(inplace=True))
336 |
337 | self.diy_lr =[[[self.backbone],self.special_lr]]
338 | if if_freeze_bn:freeze_bn(self)
339 |
340 | self.side_chs=side_chs
341 |
342 | #return_list ['img',0,1,2,3,4,'aspp','decoder','pred_decoder']
343 | def backbone_forward(self,sample_batched,img_key,click_keys,pre_pred_key,return_list=['final']):
344 | def return_results_func(key,tmp):
345 | if key in return_list: return_results.append(tmp)
346 | return len(return_results)==len(return_list)
347 |
348 | return_results=[]
349 |
350 | img=sample_batched[img_key].cuda()
351 | if return_results_func('img',img): return return_results
352 |
353 | click_map=get_click_map(sample_batched,self.aux_parameter['point_map'],click_keys=click_keys)
354 | if return_results_func('click_map',click_map): return return_results
355 |
356 | pre_pred=sample_batched[pre_pred_key].cuda()
357 | if return_results_func('pre_pred',pre_pred): return return_results
358 |
359 | aux= torch.cat([click_map,pre_pred],dim=1) if self.aux_parameter['if_pre_pred'] else click_map
360 | if return_results_func('aux',aux): return return_results
361 |
362 | x=img
363 | if self.aux_parameter['into_layer']==-1:
364 | x=torch.cat((x,my_resize(aux,x)),dim=1)
365 |
366 | for i in range(5):
367 | if i==1:x=self.backbone.layers[0][-1](x)
368 |
369 | if self.aux_parameter['into_layer']==i:
370 | x=self.encoder_anno(torch.cat((x,my_resize(aux,x)),dim=1))
371 |
372 | x=self.backbone.layers[i][:-1](x) if i==0 else self.backbone.layers[i](x)
373 |
374 | if i==1:l1=x
375 |
376 | if i in return_list:
377 | if return_results_func(i,x):
378 | return return_results
379 |
380 | if self.aux_parameter['into_layer']==5:
381 | x=self.encoder_anno(torch.cat((x,my_resize(aux,x)),dim=1))
382 |
383 | x=self.my_aspp(x)
384 | if return_results_func('aspp',x): return return_results
385 |
386 | x=self.my_decoder(x,l1)
387 | if return_results_func('decoder',x): return return_results
388 |
389 | x=self.pred_decoder(x)
390 | if return_results_func('pred_decoder',x): return return_results
391 |
392 | x=my_resize(x, img)
393 | if return_results_func('final',x): return return_results
394 |
395 |
396 | def wo_forward(self,sample_batched):
397 | return self.backbone_forward(sample_batched,'img',['pos_map_dist_src','neg_map_dist_src'],'pre_pred')[0]
398 |
399 | def hr_forward(self,sample_batched):
400 | return self.backbone_forward(sample_batched,'img_hr',['pos_map_dist_src_hr','neg_map_dist_src_hr'],'pre_pred_hr')[0]
401 |
402 | def forward(self, sample_batched, mode='train'):
403 | if mode=='eval':mode='eval-wo'
404 | results,losses=[],[]
405 |
406 | for part in ['wo','hr']:
407 | if mode in ['train','eval-{}'.format(part)]:
408 | result_part=getattr(self,'{}_forward'.format(part))(sample_batched)
409 | if result_part is not None:
410 | results.append(result_part[0] if isinstance(result_part,(list,tuple)) else result_part)
411 | if mode in ['train']:
412 | loss_part=getattr(self,'get_{}_loss'.format(part))(result_part,sample_batched)
413 | losses.append(loss_part)
414 | if self.aux_parameter['backward_each']:
415 | loss_part.backward()
416 |
417 | if mode in ['train']:
418 | loss_items=torch.Tensor([loss.item() for loss in losses]).unsqueeze(0).cuda()
419 | if not self.aux_parameter['backward_each']:
420 | losses_sum=sum(losses)
421 | losses_sum.backward()
422 | return results,loss_items
423 | else:
424 | return results
425 |
426 | def get_wo_loss(self,output_wo,sample_batched):
427 | gt=sample_batched['gt'].cuda()
428 | wo_loss=F.binary_cross_entropy_with_logits(output_wo,gt)
429 | return wo_loss
430 |
431 | def get_hr_loss(self,output_hr,sample_batched):
432 | weight=sample_batched['gt_weight_hr'].cuda() if self.aux_parameter['weight_loss'] else None
433 | gt_hr=sample_batched['gt_hr'].cuda()
434 | hr_loss=F.binary_cross_entropy_with_logits(output_hr,gt_hr,weight=weight)
435 | return hr_loss
436 |
437 | def get_hr_params_lr(self, lr):
438 | train_params=[]
439 | ignore_modules=[self.backbone,self.my_aspp,self.my_decoder,self.pred_decoder]
440 | if self.aux_parameter['into_layer']!=-1: ignore_modules.append(self.encoder_anno)
441 | remain_modules=[ module for module in self.children() if module not in ignore_modules ]
442 | train_params.append({'params':self.get_params(remain_modules),'lr':lr})
443 | return train_params
444 |
445 | def freeze_main_bn(self):
446 | freeze_modules=[self.backbone,self.my_aspp,self.my_decoder,self.pred_decoder]
447 | if self.aux_parameter['into_layer']!=-1: freeze_modules.append(self.encoder_anno)
448 | for module in freeze_modules:
449 | freeze_bn(module)
450 |
451 |
452 |
--------------------------------------------------------------------------------
/helpers.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import math
3 | import random
4 | import numpy as np
5 | from PIL import Image
6 | from pycocotools import mask as coco_mask
7 | from scipy.ndimage.morphology import distance_transform_edt
8 |
9 | ########################################[ General ]########################################
10 |
11 | def show_anno_points(gt, pos_points, neg_points):
12 | gt_point_map=(gt==1).astype(np.uint8)
13 | for pt in pos_points: gt_point_map[pt[1], pt[0]] = 2
14 | for pt in neg_points: gt_point_map[pt[1], pt[0]] = 3
15 | return gt_point_map
16 |
17 | def get_points_mask(size, points=np.empty([0,2],dtype=np.int64)):
18 | mask=np.zeros(size[::-1]).astype(np.uint8)
19 | mask[points[:,1], points[:,0]]=1
20 | return mask
21 |
22 | def fill_up_list(arr,num=None,value=-1):
23 | if num is not None:
24 | if not isinstance(value,(list,np.ndarray)): value=[value]*(len(arr[0]) if len(arr)>0 else 3)
25 | arr=np.concatenate([arr,np.array([value]).repeat(num-len(arr),axis=0)],axis=0) if len(arr)