├── .gitignore ├── LICENSE ├── README.md ├── config ├── __init__.py ├── pascal_voc_2012_multi_scale.py └── pascal_voc_aug_multi_scale.py ├── evaluate.py ├── example.jpg ├── get_dataset.sh ├── infer.py ├── lib ├── __init__.py ├── loss.py ├── model.py ├── optimizer.py ├── pascal_voc.py ├── pascal_voc_aug.py └── transform.py ├── train.py └── utils ├── AttrDict.py ├── __init__.py ├── colormap.py ├── convert_pascal_aug.py ├── crf.py └── logger.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | parts/ 18 | sdist/ 19 | var/ 20 | wheels/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | MANIFEST 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *.cover 45 | .hypothesis/ 46 | .pytest_cache/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | db.sqlite3 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # Environments 83 | .env 84 | .venv 85 | env/ 86 | venv/ 87 | ENV/ 88 | env.bak/ 89 | venv.bak/ 90 | 91 | # Spyder project settings 92 | .spyderproject 93 | .spyproject 94 | 95 | # Rope project settings 96 | .ropeproject 97 | 98 | # mkdocs documentation 99 | /site 100 | 101 | # mypy 102 | .mypy_cache/ 103 | 104 | ## coin: 105 | data 106 | data/ 107 | old/ 108 | pytorch-caffe/ 109 | pretrained/ 110 | example1.png 111 | res/ 112 | adj.txt 113 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deeplab-LFOV 2 | 3 | 4 | This is my implementation of [Deeplab-LargeFOV](https://arxiv.org/pdf/1412.7062.pdf). 5 | 6 | 7 | ## Get Pascal VOC2012 and VOG_AUG dataset 8 | Run the script to download the dataset: 9 | ``` 10 | $ sh get_dataset.sh 11 | ``` 12 | This will download and extract the VOC2012 dataset together with the augumented VOC dataset. In the paper, the author used the aug version dataset to train the model and then test on the standard VOC2012 val set. 13 | 14 | 15 | ## Train and evaluate the model 16 | Just run the training script and evaluating script: 17 | ``` 18 | $ python3 train.py --cfg config/pascal_voc_2012_multi_scale.py 19 | $ python3 evaluate.py --cfg config/pascal_voc_2012_multi_scale.py 20 | ``` 21 | Then you will see the mIOU result as reported by the authors(57.25 mIOU for deeplab-largeFOV). 22 | 23 | If you want to see the result reported by the authors, use the configuration file `pascal_voc_aug_multi_scale.py`: 24 | ``` 25 | $ python3 train.py --cfg config/pascal_voc_aug_multi_scale.py 26 | $ python3 eval.py --cfg config/pascal_voc_aug_multi_scale.py 27 | ``` 28 | This will train on the augmented dataset, which is also what the authors used in the paper. 29 | 30 | 31 | ## Inference 32 | The script `infer.py` is an example how we could use the trained model to implement segmentation on the picture of `example.jpg`. Just run it to see the performance of this model: 33 | ``` 34 | $ python3 infer.py 35 | ``` 36 | And you will see the result picture. 37 | 38 | 39 | ## Notes: 40 | 1. The authors claimed to use the weight pretrained on imagenet to initialize the model, and they provided the [initial model](http://www.cs.jhu.edu/~alanlab/ccvl/init_models) which is exported from the framework of caffe. So far, I found no easy way to convert caffe pretrained weights to that of pytorch, so I employ the following tricks as a remedy: 41 | 42 | * Initialize weights of the common parts of the 'deeplab vgg' and 'pytorch standard vgg' with the weights from pytorch model zoo. 43 | 44 | * Initialize the weights of the extraly appended layers with the [msra](https://arxiv.org/abs/1502.01852) normal distribution random numbers. 45 | 46 | * Implement warmup with the linear strategy mentioned in this [paper](https://arxiv.org/abs/1706.02677) 47 | 48 | * Upsample the output logits of the model instead of downsample the ground truth as does in [deeplabv3](https://arxiv.org/abs/1706.05587). 49 | 50 | * Use the exponential lr scheduler as does in the [deeplabv3](https://arxiv.org/abs/1706.05587). 51 | 52 | * Do multi-scale training and multi-scale testing(with flip). The images are cropped to be (497, 497). The training scales are: [0.75, 1, 1.25, 1.5, 1.75, 2.], and the testing scales are: [0.5, 0.75, 1, 1.25, 1.5, 1.75]. 53 | 54 | * Since we do not expect the crop size of the inference is too far away from what we use in the training process, I use crop evaluation. 55 | 56 | * the images are also augmented with random variance of brightness, contrast and saturation. 57 | 58 | * Considering the imbalance between the amount of different pixels, I used the on-line hard example mining loss to train the model. 59 | 60 | With these tricks, my model achieves **68.72** mIOU(without crf), modestly better than the result reported by the authors. 61 | 62 | 63 | ## By the way 64 | I also tried to use [mixup](https://arxiv.org/abs/1710.09412) in hopes of some further boost to the performance, but the result just gave a big slap on my face. I left the mixup code in the program and if you have special insights on this trick, please feel free to add a pull request or open an issue. Many thanks ! 65 | -------------------------------------------------------------------------------- /config/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoinCheung/Deeplab-Large-FOV/d9fde31ceec99ca5acbbfe281718ce7884a0aa52/config/__init__.py -------------------------------------------------------------------------------- /config/pascal_voc_2012_multi_scale.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | # import sys 5 | # print(sys.path) 6 | from utils.AttrDict import AttrDict 7 | 8 | 9 | cfg = AttrDict( 10 | ## model and loss 11 | ignore_label = 255, 12 | n_classes = 21, 13 | ## dataset 14 | dataset = 'PascalVoc', 15 | datapth = './data/', 16 | crop_size = 321, 17 | batchsize = 16, 18 | n_workers = 4, 19 | ## optimizer 20 | warmup_iter = 1000, 21 | warmup_start_lr = 1e-6, 22 | start_lr = 1e-3, 23 | iter_num = 7500, 24 | power = 0.9, 25 | momentum = 0.9, 26 | weight_decay = 5e-4, 27 | ## training control 28 | train_scales = (0.75, 1, 1.25, 1.5, 1.75, 2.), 29 | color_brightness = 0.5, 30 | color_contrast = 0.5, 31 | color_saturation = 0.5, 32 | log_iter = 20, 33 | use_mixup = False, 34 | alpha = 0.1, 35 | res_pth = './res/voc2012', 36 | ## test 37 | test_after_train = True, 38 | test_scales = (0.5, 0.75, 1, 1.25, 1.5, 1.75), 39 | flip = True, 40 | use_crf = False, 41 | ) 42 | -------------------------------------------------------------------------------- /config/pascal_voc_aug_multi_scale.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | from utils.AttrDict import AttrDict 5 | 6 | 7 | cfg = AttrDict( 8 | ## model and loss 9 | ignore_label = 255, 10 | n_classes = 21, 11 | ## dataset 12 | dataset = 'PascalVoc_Aug', 13 | datapth = './data/', 14 | crop_size = 497, 15 | batchsize = 16, 16 | n_workers = 4, 17 | ## optimizer 18 | warmup_iter = 1000, 19 | warmup_start_lr = 1e-6, 20 | start_lr = 1e-3, 21 | iter_num = 25000, 22 | power = 0.9, 23 | momentum = 0.9, 24 | weight_decay = 5e-4, 25 | ## training control 26 | train_scales = (0.75, 1, 1.25, 1.5, 1.75, 2.), 27 | color_brightness = 0.5, 28 | color_contrast = 0.5, 29 | color_saturation = 0.5, 30 | log_iter = 20, 31 | use_mixup = False, 32 | alpha = 0.1, 33 | res_pth = './res/voc_aug', 34 | ## test 35 | test_after_train = True, 36 | test_scales = (0.5, 0.75, 1, 1.25, 1.5, 1.75), 37 | flip = True, 38 | use_crf = False, 39 | ) 40 | -------------------------------------------------------------------------------- /evaluate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | import torch 6 | import torch.nn.functional as F 7 | from torch.utils.data import DataLoader 8 | 9 | import numpy as np 10 | import cv2 11 | from PIL import Image 12 | from tqdm import tqdm 13 | import logging 14 | import importlib 15 | import argparse 16 | import os.path as osp 17 | import sys 18 | import math 19 | 20 | from lib.model import DeepLabLargeFOV 21 | from lib.pascal_voc import PascalVoc 22 | from lib.pascal_voc_aug import PascalVoc_Aug 23 | # from utils.crf import crf 24 | 25 | 26 | def get_args(): 27 | parser = argparse.ArgumentParser(description='Train a network') 28 | parser.add_argument( 29 | '--cfg', 30 | dest = 'cfg', 31 | type = str, 32 | default = 'config/pascal_voc_aug_multi_scale.py', 33 | help = 'config file used in training' 34 | ) 35 | return parser.parse_args() 36 | 37 | 38 | 39 | def compute_iou(mask, lb, ignore_lb = (255, )): 40 | assert mask.shape == lb.shape, 'prediction and gt do not agree in shape' 41 | classes = set(np.unique(lb).tolist()) 42 | for cls in ignore_lb: 43 | if cls in classes: 44 | classes.remove(cls) 45 | 46 | iou_cls = [] 47 | for cls in classes: 48 | gt = lb == cls 49 | pred = mask == cls 50 | intersection = np.logical_and(gt, pred) 51 | union = np.logical_or(gt, pred) 52 | iou = float(np.sum(intersection)) / float(np.sum(union)) 53 | iou_cls.append(iou) 54 | return sum(iou_cls) / len(iou_cls) 55 | 56 | 57 | def eval_model(net, cfg): 58 | logger = logging.getLogger(__name__) 59 | ## dataset 60 | dsval = PascalVoc(cfg, mode='val') 61 | ## evaluator 62 | evaluator = MscEval( 63 | dsval = dsval, 64 | scales = cfg.test_scales, 65 | n_classes = cfg.n_classes, 66 | lb_ignore = cfg.ignore_label, 67 | flip = cfg.flip, 68 | crop_size = cfg.crop_size, 69 | n_workers = 4, 70 | ) 71 | ## inference 72 | logger.info('evaluating on standard voc2012 val set') 73 | mIOU = evaluator(net) 74 | 75 | return mIOU 76 | 77 | 78 | class MscEval(object): 79 | def __init__(self, 80 | dsval, 81 | scales = [0.5, 0.75, 1, 1.25, 1.5, 1.75], 82 | n_classes = 19, 83 | lb_ignore = 255, 84 | flip = True, 85 | crop_size = 321, 86 | n_workers = 2, 87 | *args, **kwargs): 88 | self.scales = scales 89 | self.n_classes = n_classes 90 | self.lb_ignore = lb_ignore 91 | self.flip = flip 92 | self.crop_size = crop_size 93 | ## dataloader 94 | self.dsval = dsval 95 | self.net = None 96 | 97 | 98 | def pad_tensor(self, inten, size): 99 | N, C, H, W = inten.size() 100 | ## TODO: use zeros 101 | outten = torch.zeros(N, C, size[0], size[1]).cuda() 102 | outten.requires_grad = False 103 | margin_h, margin_w = size[0]-H, size[1]-W 104 | hst, hed = margin_h//2, margin_h//2+H 105 | wst, wed = margin_w//2, margin_w//2+W 106 | outten[:, :, hst:hed, wst:wed] = inten 107 | return outten, [hst, hed, wst, wed] 108 | 109 | 110 | def eval_chip(self, crop): 111 | with torch.no_grad(): 112 | out = self.net(crop) 113 | prob = F.softmax(out, 1) 114 | if self.flip: 115 | crop = torch.flip(crop, dims=(3,)) 116 | out = self.net(crop) 117 | out = torch.flip(out, dims=(3,)) 118 | prob += F.softmax(out, 1) 119 | prob = torch.exp(prob) 120 | return prob 121 | 122 | 123 | def crop_eval(self, im): 124 | cropsize = self.crop_size 125 | stride_rate = 5/6. 126 | N, C, H, W = im.size() 127 | long_size, short_size = (H,W) if H>W else (W,H) 128 | if long_size < cropsize: 129 | im, indices = self.pad_tensor(im, (cropsize, cropsize)) 130 | prob = self.eval_chip(im) 131 | prob = prob[:, :, indices[0]:indices[1], indices[2]:indices[3]] 132 | else: 133 | stride = math.ceil(cropsize*stride_rate) 134 | if short_size < cropsize: 135 | if H < W: 136 | im, indices = self.pad_tensor(im, (cropsize, W)) 137 | else: 138 | im, indices = self.pad_tensor(im, (H, cropsize)) 139 | N, C, H, W = im.size() 140 | n_x = math.ceil((W-cropsize)/stride)+1 141 | n_y = math.ceil((H-cropsize)/stride)+1 142 | prob = torch.zeros(N, self.n_classes, H, W).cuda() 143 | prob.requires_grad = False 144 | for iy in range(n_y): 145 | for ix in range(n_x): 146 | hed, wed = min(H, stride*iy+cropsize), min(W, stride*ix+cropsize) 147 | hst, wst = hed-cropsize, wed-cropsize 148 | chip = im[:, :, hst:hed, wst:wed] 149 | prob_chip = self.eval_chip(chip) 150 | prob[:, :, hst:hed, wst:wed] += prob_chip 151 | if short_size < cropsize: 152 | prob = prob[:, :, indices[0]:indices[1], indices[2]:indices[3]] 153 | return prob 154 | 155 | 156 | def scale_crop_eval(self, im, scale): 157 | N, C, H, W = im.size() 158 | new_hw = [int(H*scale), int(W*scale)] 159 | im = F.interpolate(im, new_hw, mode='bilinear', align_corners=True) 160 | prob = self.crop_eval(im) 161 | prob = F.interpolate(prob, (H, W), mode='bilinear', align_corners=True) 162 | return prob 163 | 164 | 165 | def compute_hist(self, pred, lb, lb_ignore=255): 166 | n_classes = self.n_classes 167 | keep = np.logical_not(lb==lb_ignore) 168 | merge = pred[keep] * n_classes + lb[keep] 169 | hist = np.bincount(merge, minlength=n_classes**2) 170 | hist = hist.reshape((n_classes, n_classes)) 171 | return hist 172 | 173 | def __call__(self, net): 174 | self.net = net 175 | ## evaluate 176 | hist = np.zeros((self.n_classes, self.n_classes), dtype=np.float32) 177 | for i, (imgs, label) in enumerate(tqdm(self.dsval)): 178 | N, _, H, W = imgs.size() 179 | probs = torch.zeros((N, self.n_classes, H, W)) 180 | probs.requires_grad = False 181 | imgs = imgs.cuda() 182 | for sc in self.scales: 183 | prob = self.scale_crop_eval(imgs, sc) 184 | probs += prob.detach().cpu() 185 | probs = probs.data.numpy() 186 | preds = np.argmax(probs, axis=1) 187 | 188 | hist_once = self.compute_hist(preds, label) 189 | hist = hist + hist_once 190 | IOUs = np.diag(hist) / (np.sum(hist, axis=0)+np.sum(hist, axis=1)-np.diag(hist)) 191 | mIOU = np.mean(IOUs) 192 | return mIOU 193 | 194 | 195 | def evaluate(args): 196 | ## set up logger and parse cfg 197 | FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s' 198 | logging.basicConfig(level=logging.INFO, format=FORMAT, stream=sys.stdout) 199 | logger = logging.getLogger(__name__) 200 | spec = importlib.util.spec_from_file_location('mod_cfg', args.cfg) 201 | mod_cfg = importlib.util.module_from_spec(spec) 202 | spec.loader.exec_module(mod_cfg) 203 | cfg = mod_cfg.cfg 204 | 205 | ## initialize model 206 | net = DeepLabLargeFOV(3, cfg.n_classes) 207 | net.eval() 208 | net.cuda() 209 | model_pth = osp.join(cfg.res_pth, 'model_final.pkl') 210 | net.load_state_dict(torch.load(model_pth)) 211 | 212 | ## evaluate 213 | mIOU = eval_model(net, cfg) 214 | logger.info('iou in whole is: {}'.format(mIOU)) 215 | 216 | 217 | if __name__ == "__main__": 218 | args = get_args() 219 | evaluate(args) 220 | -------------------------------------------------------------------------------- /example.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoinCheung/Deeplab-Large-FOV/d9fde31ceec99ca5acbbfe281718ce7884a0aa52/example.jpg -------------------------------------------------------------------------------- /get_dataset.sh: -------------------------------------------------------------------------------- 1 | 2 | # get pascal voc 3 | # standard voc 4 | mkdir -p data 5 | cd data 6 | wget -c http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar 7 | tar -xvf VOCtrainval_11-May-2012.tar 8 | wget -c http://pjreddie.com/media/files/VOC2012test.tar 9 | tar -xvf VOC2012test.tar 10 | 11 | # voc aug 12 | wget -c wget http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz 13 | tar -zxvf benchmark.tgz 14 | mkdir -p VOC_AUG VOC_AUG/images VOC_AUG/labels 15 | cp -riv benchmark_RELEASE/dataset/*txt VOC_AUG/ 16 | cp -riv benchmark_RELEASE/dataset/img/* VOC_AUG/images/ 17 | cd .. 18 | python3 utils/convert_pascal_aug.py 19 | 20 | # get pretrained init model 21 | # mkdir -p pretrained 22 | # cd pretrained 23 | # wget -c http://www.cs.jhu.edu/~alanlab/ccvl/init_models/vgg16_20M.caffemodel 24 | # wget -c http://liangchiehchen.com/projects/released/deeplab_coco_largefov/vgg16_20M_coco.caffemodel.zip 25 | # unzip vgg16_20M_coco.caffemodel.zip 26 | # cd .. 27 | -------------------------------------------------------------------------------- /infer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | import torch 6 | import torch.nn.functional as F 7 | import torchvision.transforms as transforms 8 | import numpy as np 9 | import os.path as osp 10 | import cv2 11 | from PIL import Image 12 | import argparse 13 | import importlib 14 | 15 | from lib.model import DeepLabLargeFOV 16 | # from utils.crf import crf 17 | from utils.colormap import color_map 18 | 19 | 20 | def parse_args(): 21 | parser = argparse.ArgumentParser(description='Train a network') 22 | parser.add_argument( 23 | '--cfg', 24 | dest = 'cfg', 25 | type = str, 26 | default = 'config/pascal_voc_aug_multi_scale.py', 27 | help = 'config file associated with the model' 28 | ) 29 | parser.add_argument( 30 | '--img', 31 | dest = 'impth', 32 | type = str, 33 | default = './example.jpg', 34 | help = 'image to be tested' 35 | ) 36 | return parser.parse_args() 37 | 38 | 39 | 40 | def infer(args): 41 | spec = importlib.util.spec_from_file_location('mod_cfg', args.cfg) 42 | mod_cfg = importlib.util.module_from_spec(spec) 43 | spec.loader.exec_module(mod_cfg) 44 | cfg = mod_cfg.cfg 45 | 46 | ## set up 47 | cm = color_map(N = cfg.n_classes) 48 | trans = transforms.Compose([ 49 | transforms.ToTensor(), 50 | transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), 51 | ]) 52 | 53 | ## image 54 | args.impth = './example.jpg' 55 | assert osp.exists(args.impth), '{} not exists !!'.format(args.impth) 56 | im = Image.open(args.impth) 57 | im_org = cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2BGR) 58 | im = trans(im).cuda().unsqueeze(0) 59 | 60 | ## network 61 | net = DeepLabLargeFOV(3, cfg.n_classes) 62 | net.eval() 63 | net.cuda() 64 | model_pth = osp.join(cfg.res_pth, 'model_final.pkl') 65 | net.load_state_dict(torch.load(model_pth)) 66 | 67 | ## inference 68 | scores = net(im) 69 | scores = F.interpolate(scores, im.size()[2:], mode='bilinear', align_corners=True) 70 | scores = F.softmax(scores, 1) 71 | scores = scores.detach().cpu().numpy() 72 | if cfg.use_crf: 73 | mask = crf(im_org, scores) 74 | else: 75 | mask = np.argmax(scores, axis = 1) 76 | mask = np.squeeze(mask, axis = 0) 77 | H, W = mask.shape 78 | pic = np.empty((H, W, 3)) 79 | for i in range(cfg.n_classes): 80 | pic[mask == i] = cm[i] 81 | 82 | ## show 83 | cv2.imshow('org', im_org) 84 | cv2.imshow('pred', pic) 85 | cv2.waitKey(0) 86 | 87 | 88 | if __name__ == "__main__": 89 | args = parse_args() 90 | infer(args) 91 | -------------------------------------------------------------------------------- /lib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoinCheung/Deeplab-Large-FOV/d9fde31ceec99ca5acbbfe281718ce7884a0aa52/lib/__init__.py -------------------------------------------------------------------------------- /lib/loss.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | import torch 6 | import torch.nn as nn 7 | import torch.nn.functional as F 8 | 9 | 10 | class OhemCELoss(nn.Module): 11 | def __init__(self, thresh, n_min, ignore_lb=255, *args, **kwargs): 12 | super(OhemCELoss, self).__init__() 13 | self.thresh = -torch.log(torch.tensor(thresh, dtype=torch.float)).cuda() 14 | self.n_min = n_min 15 | self.ignore_lb = ignore_lb 16 | self.criteria = nn.CrossEntropyLoss(ignore_index=ignore_lb, reduction='none') 17 | 18 | def forward(self, logits, labels): 19 | N, C, H, W = logits.size() 20 | loss = self.criteria(logits, labels).view(-1) 21 | loss, _ = torch.sort(loss, descending=True) 22 | if loss[self.n_min] > self.thresh: 23 | loss = loss[loss>self.thresh] 24 | else: 25 | loss = loss[:self.n_min] 26 | return torch.mean(loss) 27 | 28 | 29 | class SoftmaxFocalLoss(nn.Module): 30 | def __init__(self, gamma, ignore_lb=255, *args, **kwargs): 31 | super(SoftmaxFocalLoss, self).__init__() 32 | self.gamma = gamma 33 | self.nll = nn.NLLLoss(ignore_index=ignore_lb) 34 | 35 | def forward(self, logits, labels): 36 | scores = F.softmax(logits, dim=1) 37 | factor = torch.pow(1.-scores, self.gamma) 38 | log_score = F.log_softmax(logits, dim=1) 39 | log_score = factor * log_score 40 | loss = self.nll(log_score, labels) 41 | return loss 42 | 43 | 44 | 45 | if __name__ == '__main__': 46 | torch.manual_seed(15) 47 | criteria1 = OhemCELoss(thresh=0.7, n_min=16*20*20//16).cuda() 48 | criteria2 = OhemCELoss(thresh=0.7, n_min=16*20*20//16).cuda() 49 | focal1 = FocalLoss(alpha=0.25, gamma=1) 50 | net1 = nn.Sequential( 51 | nn.Conv2d(3, 19, kernel_size=3, stride=2, padding=1), 52 | ) 53 | net1.cuda() 54 | net1.train() 55 | net2 = nn.Sequential( 56 | nn.Conv2d(3, 19, kernel_size=3, stride=2, padding=1), 57 | ) 58 | net2.cuda() 59 | net2.train() 60 | 61 | with torch.no_grad(): 62 | inten = torch.randn(16, 3, 20, 20).cuda() 63 | lbs = torch.randint(0, 19, [16, 20, 20]).cuda() 64 | lbs[1, :, :] = 255 65 | 66 | logits1 = net1(inten) 67 | logits1 = F.interpolate(logits1, inten.size()[2:], mode='bilinear') 68 | logits2 = net2(inten) 69 | logits2 = F.interpolate(logits2, inten.size()[2:], mode='bilinear') 70 | 71 | # loss1 = criteria1(logits1, lbs) 72 | loss1 = focal1(logits1, lbs) 73 | loss2 = criteria2(logits2, lbs) 74 | loss = loss1 + loss2 75 | print(loss.detach().cpu()) 76 | loss.backward() 77 | -------------------------------------------------------------------------------- /lib/model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | import torchvision 6 | import torch 7 | import torch.nn as nn 8 | import torch.nn.functional as F 9 | 10 | 11 | 12 | class DeepLabLargeFOV(nn.Module): 13 | def __init__(self, in_dim, out_dim, *args, **kwargs): 14 | super(DeepLabLargeFOV, self).__init__(*args, **kwargs) 15 | vgg16 = torchvision.models.vgg16() 16 | 17 | layers = [] 18 | layers.append(nn.Conv2d(in_dim, 64, kernel_size = 3, stride = 1, padding = 1)) 19 | layers.append(nn.ReLU(inplace = True)) 20 | layers.append(nn.Conv2d(64, 64, kernel_size = 3, stride = 1, padding = 1)) 21 | layers.append(nn.ReLU(inplace = True)) 22 | layers.append(nn.MaxPool2d(3, stride = 2, padding = 1)) 23 | 24 | layers.append(nn.Conv2d(64, 128, kernel_size = 3, stride = 1, padding = 1)) 25 | layers.append(nn.ReLU(inplace = True)) 26 | layers.append(nn.Conv2d(128, 128, kernel_size = 3, stride = 1, padding = 1)) 27 | layers.append(nn.ReLU(inplace = True)) 28 | layers.append(nn.MaxPool2d(3, stride = 2, padding = 1)) 29 | 30 | layers.append(nn.Conv2d(128, 256, kernel_size = 3, stride = 1, padding = 1)) 31 | layers.append(nn.ReLU(inplace = True)) 32 | layers.append(nn.Conv2d(256, 256, kernel_size = 3, stride = 1, padding = 1)) 33 | layers.append(nn.ReLU(inplace = True)) 34 | layers.append(nn.Conv2d(256, 256, kernel_size = 3, stride = 1, padding = 1)) 35 | layers.append(nn.ReLU(inplace = True)) 36 | layers.append(nn.MaxPool2d(3, stride = 2, padding = 1)) 37 | 38 | layers.append(nn.Conv2d(256, 512, kernel_size = 3, stride = 1, padding = 1)) 39 | layers.append(nn.ReLU(inplace = True)) 40 | layers.append(nn.Conv2d(512, 512, kernel_size = 3, stride = 1, padding = 1)) 41 | layers.append(nn.ReLU(inplace = True)) 42 | layers.append(nn.Conv2d(512, 512, kernel_size = 3, stride = 1, padding = 1)) 43 | layers.append(nn.ReLU(inplace = True)) 44 | layers.append(nn.MaxPool2d(3, stride = 1, padding = 1)) 45 | 46 | layers.append(nn.Conv2d(512, 47 | 512, 48 | kernel_size = 3, 49 | stride = 1, 50 | padding = 2, 51 | dilation = 2)) 52 | layers.append(nn.ReLU(inplace = True)) 53 | layers.append(nn.Conv2d(512, 54 | 512, 55 | kernel_size = 3, 56 | stride = 1, 57 | padding = 2, 58 | dilation = 2)) 59 | layers.append(nn.ReLU(inplace = True)) 60 | layers.append(nn.Conv2d(512, 61 | 512, 62 | kernel_size = 3, 63 | stride = 1, 64 | padding = 2, 65 | dilation = 2)) 66 | layers.append(nn.ReLU(inplace = True)) 67 | layers.append(nn.MaxPool2d(3, stride = 1, padding = 1)) 68 | self.features = nn.Sequential(*layers) 69 | 70 | classifier = [] 71 | classifier.append(nn.AvgPool2d(3, stride = 1, padding = 1)) 72 | classifier.append(nn.Conv2d(512, 73 | 1024, 74 | kernel_size = 3, 75 | stride = 1, 76 | padding = 12, 77 | dilation = 12)) 78 | classifier.append(nn.ReLU(inplace=True)) 79 | classifier.append(nn.Conv2d(1024, 1024, kernel_size=1, stride=1, padding=0)) 80 | classifier.append(nn.ReLU(inplace=True)) 81 | classifier.append(nn.Dropout(p=0.5)) 82 | classifier.append(nn.Conv2d(1024, out_dim, kernel_size=1)) 83 | self.classifier = nn.Sequential(*classifier) 84 | 85 | self.init_weights() 86 | 87 | 88 | def forward(self, x): 89 | N, C, H, W = x.size() 90 | x = self.features(x) 91 | x = self.classifier(x) 92 | x = F.interpolate(x, (H, W), mode='bilinear', align_corners=True) 93 | return x 94 | 95 | def init_weights(self): 96 | vgg = torchvision.models.vgg16(pretrained=True) 97 | state_vgg = vgg.features.state_dict() 98 | self.features.load_state_dict(state_vgg) 99 | 100 | for ly in self.classifier.children(): 101 | if isinstance(ly, nn.Conv2d): 102 | nn.init.kaiming_normal_(ly.weight, a=1) 103 | nn.init.constant_(ly.bias, 0) 104 | 105 | 106 | if __name__ == "__main__": 107 | net = DeepLabLargeFOV(3, 10) 108 | in_ten = torch.randn(1, 3, 224, 224) 109 | out = net(in_ten) 110 | print(out.size()) 111 | 112 | in_ten = torch.randn(1, 3, 64, 64) 113 | mod = nn.Conv2d(3, 114 | 512, 115 | kernel_size = 3, 116 | stride = 1, 117 | padding = 2, 118 | dilation = 2) 119 | out = mod(in_ten) 120 | print(out.shape) 121 | 122 | -------------------------------------------------------------------------------- /lib/optimizer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | import torch 6 | import logging 7 | 8 | logger = logging.getLogger() 9 | 10 | class Optimizer(object): 11 | def __init__(self, 12 | params, 13 | warmup_start_lr, 14 | warmup_steps, 15 | lr0, 16 | max_iter, 17 | momentum, 18 | power, 19 | wd, 20 | *args, **kwargs): 21 | self.warmup_steps = warmup_steps 22 | self.warmup_start_lr = warmup_start_lr 23 | self.lr0 = lr0 24 | self.lr = self.lr0 25 | self.max_iter = float(max_iter) 26 | self.power = power 27 | self.it = 0 28 | self.optim = torch.optim.SGD( 29 | params, 30 | lr = lr0, 31 | momentum = momentum, 32 | weight_decay = wd) 33 | self.warmup_factor = (self.lr0/self.warmup_start_lr)**(1./self.warmup_steps) 34 | 35 | def get_lr(self): 36 | if self.it <= self.warmup_steps: 37 | lr = self.warmup_start_lr*(self.warmup_factor**self.it) 38 | else: 39 | factor = (1-(self.it-self.warmup_steps)/(self.max_iter-self.warmup_steps))**self.power 40 | lr = self.lr0 * factor 41 | return lr 42 | 43 | def step(self): 44 | self.lr = self.get_lr() 45 | for pg in self.optim.param_groups: 46 | pg['lr'] = self.lr 47 | self.optim.defaults['lr'] = self.lr 48 | self.it += 1 49 | self.optim.step() 50 | if self.it == self.warmup_steps+2: 51 | logger.info('==> warmup done, start to implement poly lr strategy') 52 | 53 | def zero_grad(self): 54 | self.optim.zero_grad() 55 | 56 | -------------------------------------------------------------------------------- /lib/pascal_voc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | import os.path as osp 6 | import torch 7 | import torchvision.transforms as transforms 8 | from torch.utils.data import Dataset 9 | 10 | from PIL import Image 11 | import cv2 12 | import numpy as np 13 | 14 | import lib.transform as T 15 | 16 | ''' 17 | 0: background 18 | 1: aeroplane 19 | 2: bicycle 20 | 3: bird 21 | 4: boat 22 | 5: bottle 23 | 6: bus 24 | 7: car 25 | 8: cat 26 | 9: chair 27 | 10: cow 28 | 11: diningtable 29 | 12: dog 30 | 13: horse 31 | 14: motorbike 32 | 15: person 33 | 16: pottedplant 34 | 17: sheep 35 | 18: sofa 36 | 19: train 37 | 20: tvmonitor 38 | ''' 39 | 40 | 41 | class PascalVoc(Dataset): 42 | def __init__(self, cfg, mode='train', *args, **kwargs): 43 | super(PascalVoc, self).__init__(*args, **kwargs) 44 | self.cfg = cfg 45 | self.mode = mode 46 | rootpath = osp.join(cfg.datapth, 'VOCdevkit/VOC2012/') 47 | if not osp.exists(rootpath): assert(False) 48 | if not self.mode in ('train', 'val', 'trainval', 'test'): assert(False) 49 | if mode == 'train': 50 | txtfile = osp.join(rootpath, 'ImageSets/Segmentation/train.txt') 51 | elif mode == 'val': 52 | txtfile = osp.join(rootpath, 'ImageSets/Segmentation/val.txt') 53 | elif mode == 'trainval': 54 | txtfile = osp.join(rootpath, 'ImageSets/Segmentation/trainval.txt') 55 | elif mode == 'test': 56 | txtfile = osp.join(rootpath, 'ImageSets/Segmentation/test.txt') 57 | else: assert(False) 58 | jpgpth = osp.join(rootpath, 'JPEGImages') 59 | lbpth = osp.join(rootpath, 'SegmentationClass') 60 | 61 | with open(txtfile, 'r') as fr: 62 | fns = fr.read().splitlines() 63 | self.len = len(fns) 64 | fns_img = ['{}.jpg'.format(el) for el in fns] 65 | self.fns_img = [osp.join(jpgpth, el) for el in fns_img] 66 | fns_lbs = ['{}.png'.format(el) for el in fns] 67 | self.fns_lbs = [osp.join(lbpth, el) for el in fns_lbs] 68 | 69 | self.trans = T.Compose([ 70 | T.RandomScale(cfg.train_scales), 71 | T.RandomCrop((cfg.crop_size, cfg.crop_size)), 72 | T.HorizontalFlip(), 73 | T.ColorJitter( 74 | brightness = cfg.color_brightness, 75 | contrast = cfg.color_contrast, 76 | saturation = cfg.color_saturation 77 | ), 78 | ]) 79 | self.to_tensor = transforms.Compose([ 80 | transforms.ToTensor(), 81 | transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), 82 | ]) 83 | 84 | def __getitem__(self, idx): 85 | iname = self.fns_img[idx] 86 | lname = self.fns_lbs[idx] 87 | img = Image.open(iname) 88 | label = Image.open(lname) 89 | im_lb = dict(im = img, lb = label) 90 | if self.mode in ('train', 'trainval'): 91 | im_lb = self.trans(im_lb) 92 | img, label = im_lb['im'], im_lb['lb'] 93 | img = self.to_tensor(img) 94 | label = np.array(label).astype(np.int64)[np.newaxis, :] 95 | if self.mode == 'val': 96 | img = torch.unsqueeze(img, 0) 97 | 98 | return img, label 99 | 100 | def __len__(self): 101 | return self.len 102 | 103 | 104 | if __name__ == '__main__': 105 | from torch.utils.data import DataLoader 106 | from config.pascal_voc_2012_multi_scale import cfg 107 | 108 | 109 | ds = PascalVoc(cfg, mode='val') 110 | im, lb = ds[110] 111 | print(type(lb)) 112 | print(lb.shape) 113 | dl = DataLoader(ds, 114 | batch_size = 20, 115 | shuffle = True, 116 | num_workers = 4, 117 | drop_last = True) 118 | 119 | for im, label in ds: 120 | if not im.size() == (20, 3, 513, 513): 121 | print(im.size()) 122 | if not label.shape == (20, 1, 513, 513): 123 | print(label.shape) 124 | label[label==255] = 0 125 | if label.max() > 20: 126 | print(label.max()) 127 | print(len(ds)) 128 | -------------------------------------------------------------------------------- /lib/pascal_voc_aug.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | import os.path as osp 6 | import os 7 | from PIL import Image 8 | import numpy as np 9 | 10 | from torch.utils.data import Dataset 11 | import torchvision.transforms as transforms 12 | import torch 13 | 14 | from lib.transform import HorizontalFlip, RandomCrop 15 | import lib.transform as T 16 | 17 | 18 | 19 | class PascalVoc_Aug(Dataset): 20 | def __init__(self, cfg, mode='train', *args, **kwargs): 21 | super(PascalVoc_Aug, self).__init__(*args, **kwargs) 22 | self.cfg = cfg 23 | self.mode = mode 24 | root_pth = osp.join(cfg.datapth, 'VOC_AUG') 25 | self.impth = osp.join(root_pth, 'images') 26 | self.lbpth = osp.join(root_pth, 'labels') 27 | if mode == 'train': 28 | txtpth = osp.join(root_pth, 'train.txt') 29 | elif mode == 'val': 30 | txtpth = osp.join(root_pth, 'val.txt') 31 | else: 32 | raise(ValueError) 33 | 34 | with open(txtpth, 'r') as fr: 35 | fns = fr.read().splitlines() 36 | self.len = len(fns) 37 | self.imgs = ['{}.jpg'.format(el) for el in fns] 38 | self.imgs = [osp.join(self.impth, el) for el in self.imgs] 39 | self.lbs = ['{}.png'.format(el) for el in fns] 40 | self.lbs = [osp.join(self.lbpth, el) for el in self.lbs] 41 | 42 | self.trans = T.Compose([ 43 | T.RandomScale(cfg.train_scales), 44 | T.RandomCrop((cfg.crop_size, cfg.crop_size)), 45 | T.HorizontalFlip(), 46 | T.ColorJitter( 47 | brightness = cfg.color_brightness, 48 | contrast = cfg.color_contrast, 49 | saturation = cfg.color_saturation 50 | ), 51 | ]) 52 | self.to_tensor = transforms.Compose([ 53 | transforms.ToTensor(), 54 | transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), 55 | ]) 56 | 57 | def __getitem__(self, idx): 58 | iname = self.imgs[idx] 59 | lname = self.lbs[idx] 60 | img = Image.open(iname) 61 | label = Image.open(lname) 62 | im_lb = dict(im = img, lb = label) 63 | if self.mode == 'train': 64 | im_lb = self.trans(im_lb) 65 | img, label = im_lb['im'], im_lb['lb'] 66 | img = self.to_tensor(img) 67 | label = np.array(label).astype(np.int64)[np.newaxis, :] 68 | if self.mode == 'val': 69 | img = torch.unsqueeze(img, 0) 70 | 71 | return img, label 72 | 73 | 74 | def __len__(self): 75 | return self.len 76 | 77 | 78 | 79 | 80 | if __name__ == '__main__': 81 | ds = PascalVoc_Aug('data/VOC_AUG/') 82 | im, lb = ds[11] 83 | for i, (im, lb) in enumerate(ds): 84 | print(im.size()) 85 | print(lb.shape) 86 | if i == 10: break 87 | -------------------------------------------------------------------------------- /lib/transform.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | from PIL import Image 6 | import PIL.ImageEnhance as ImageEnhance 7 | import random 8 | 9 | 10 | class Compose(object): 11 | def __init__(self, do_list): 12 | self.do_list = do_list 13 | 14 | def __call__(self, im_lb): 15 | for comp in self.do_list: 16 | im_lb = comp(im_lb) 17 | return im_lb 18 | 19 | 20 | class PadToSize(object): 21 | def __init__(self, size, *args, **kwargs): 22 | self.size = size 23 | 24 | def __call__(self, im_lb): 25 | im = im_lb['im'] 26 | lb = im_lb['lb'] 27 | assert im.size == lb.size 28 | W, H = self.size 29 | w, h = im.size 30 | if (W, H) == (w, h): return dict(im = im, lb = lb) 31 | 32 | newW, padW = w, 0 33 | if w < W: 34 | padW = (W-w)//2 35 | newW = W 36 | newH, padH = h, 0 37 | if h < H: 38 | padH = (H-h)//2 39 | newH = H 40 | new_im = Image.new('RGB', (newW, newH)) 41 | new_lb = Image.new('I', (newW, newH), color=255) 42 | new_im.paste(im, (padW, padH)) 43 | new_lb.paste(lb, (padW, padH)) 44 | return dict(im = new_im, 45 | lb = new_lb) 46 | 47 | 48 | class RandomCrop(object): 49 | def __init__(self, size, *args, **kwargs): 50 | self.size = size 51 | 52 | def __call__(self, im_lb): 53 | im = im_lb['im'] 54 | lb = im_lb['lb'] 55 | assert im.size == lb.size 56 | W, H = self.size 57 | w, h = im.size 58 | if (W, H) == (w, h): return dict(im = im, lb = lb) 59 | 60 | newW, padW = w, 0 61 | if w < W: 62 | padW = (W-w)//2 63 | newW = W 64 | newH, padH = h, 0 65 | if h < H: 66 | padH = (H-h)//2 67 | newH = H 68 | new_im = Image.new('RGB', (newW, newH)) 69 | new_lb = Image.new('I', (newW, newH), color=255) 70 | new_im.paste(im, (padW, padH)) 71 | new_lb.paste(lb, (padW, padH)) 72 | sw, sh = random.random() * (w - W), random.random() * (h - H) 73 | crop = int(sw), int(sh), int(sw) + W, int(sh) + H 74 | return dict(im = im.crop(crop), 75 | lb = lb.crop(crop)) 76 | 77 | 78 | 79 | class RandomScale(object): 80 | def __init__(self, scales = (1, ), *args, **kwargs): 81 | self.scales = scales 82 | 83 | def __call__(self, im_lb): 84 | im = im_lb['im'] 85 | lb = im_lb['lb'] 86 | W, H = im.size 87 | scale = random.choice(self.scales) 88 | w, h = int(W * scale), int(H * scale) 89 | return dict(im = im.resize((w, h), Image.BILINEAR), 90 | lb = lb.resize((w, h), Image.NEAREST), 91 | ) 92 | 93 | 94 | class ColorJitter(object): 95 | def __init__(self, brightness=None, contrast=None, saturation=None, *args, **kwargs): 96 | if not brightness is None and brightness>0: 97 | self.brightness = [max(1-brightness, 0), 1+brightness] 98 | if not contrast is None and contrast>0: 99 | self.contrast = [max(1-contrast, 0), 1+contrast] 100 | if not saturation is None and saturation>0: 101 | self.saturation = [max(1-saturation, 0), 1+saturation] 102 | 103 | def __call__(self, im_lb): 104 | im = im_lb['im'] 105 | lb = im_lb['lb'] 106 | r_brightness = random.uniform(self.brightness[0], self.brightness[1]) 107 | r_contrast = random.uniform(self.contrast[0], self.contrast[1]) 108 | r_saturation = random.uniform(self.saturation[0], self.saturation[1]) 109 | im = ImageEnhance.Brightness(im).enhance(r_brightness) 110 | im = ImageEnhance.Contrast(im).enhance(r_contrast) 111 | im = ImageEnhance.Color(im).enhance(r_saturation) 112 | return dict(im = im, 113 | lb = lb, 114 | ) 115 | 116 | 117 | class HorizontalFlip(object): 118 | def __init__(self, p = 0.5, *args, **kwargs): 119 | self.p = p 120 | 121 | def __call__(self, im_lb): 122 | if random.random() > self.p: 123 | return im_lb 124 | else: 125 | im = im_lb['im'] 126 | lb = im_lb['lb'] 127 | return dict(im = im.transpose(Image.FLIP_LEFT_RIGHT), 128 | lb = lb.transpose(Image.FLIP_LEFT_RIGHT), 129 | ) 130 | 131 | if __name__ == '__main__': 132 | flip = HorizontalFlip(p = 1) 133 | crop = RandomCrop((321, 321)) 134 | img = Image.open('data/img.jpg') 135 | lb = Image.open('data/label.png') 136 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | import torch 6 | import torch.nn as nn 7 | from torch.utils.data import DataLoader 8 | import torch.nn.functional as F 9 | import os 10 | import os.path as osp 11 | import time 12 | import sys 13 | import logging 14 | import numpy as np 15 | import argparse 16 | import importlib 17 | import json 18 | 19 | from lib.model import DeepLabLargeFOV 20 | from lib.pascal_voc import PascalVoc 21 | from lib.pascal_voc_aug import PascalVoc_Aug 22 | from lib.transform import RandomCrop 23 | from lib.optimizer import Optimizer 24 | from lib.loss import * 25 | from utils.logger import setup_logger 26 | from evaluate import eval_model 27 | 28 | 29 | 30 | torch.multiprocessing.set_sharing_strategy('file_system') 31 | 32 | def get_args(): 33 | parser = argparse.ArgumentParser(description='Train a network') 34 | parser.add_argument( 35 | '--cfg', 36 | dest = 'cfg', 37 | type = str, 38 | default = 'config/pascal_voc_aug_multi_scale.py', 39 | help = 'config file for training' 40 | ) 41 | return parser.parse_args() 42 | 43 | 44 | def train(args): 45 | ## setup cfg and logger 46 | spec = importlib.util.spec_from_file_location('mod_cfg', args.cfg) 47 | mod_cfg = importlib.util.module_from_spec(spec) 48 | spec.loader.exec_module(mod_cfg) 49 | cfg = mod_cfg.cfg 50 | cfg_str = json.dumps(cfg, ensure_ascii=False, indent=2) 51 | if not osp.exists(cfg.res_pth): os.makedirs(cfg.res_pth) 52 | setup_logger(cfg.res_pth) 53 | logger = logging.getLogger(__name__) 54 | logger.info(cfg_str) 55 | 56 | ## modules and losses 57 | logger.info('creating model and loss module') 58 | net = DeepLabLargeFOV(3, cfg.n_classes) 59 | net.train() 60 | net.cuda() 61 | if not torch.cuda.device_count() == 0: net = nn.DataParallel(net) 62 | n_min = (cfg.crop_size**2) * cfg.batchsize // 16 63 | criteria = OhemCELoss(0.7, n_min) 64 | criteria.cuda() 65 | 66 | ## dataset 67 | logger.info('creating dataset and dataloader') 68 | ds = eval(cfg.dataset)(cfg, mode='train') 69 | dl = DataLoader(ds, 70 | batch_size = cfg.batchsize, 71 | shuffle = True, 72 | num_workers = cfg.n_workers, 73 | drop_last = True) 74 | 75 | ## optimizer 76 | logger.info('creating optimizer') 77 | optimizer = Optimizer( 78 | params = net.parameters(), 79 | warmup_start_lr = cfg.warmup_start_lr, 80 | warmup_steps = cfg.warmup_iter, 81 | lr0 = cfg.start_lr, 82 | max_iter = cfg.iter_num, 83 | momentum = cfg.momentum, 84 | wd = cfg.weight_decay, 85 | power = cfg.power) 86 | 87 | ## train loop 88 | loss_avg = [] 89 | st = time.time() 90 | diter = iter(dl) 91 | logger.info('start training') 92 | for it in range(cfg.iter_num): 93 | try: 94 | im, lb = next(diter) 95 | if not im.size()[0] == cfg.batchsize: continue 96 | except StopIteration: 97 | diter = iter(dl) 98 | im, lb = next(diter) 99 | im = im.cuda() 100 | lb = lb.cuda() 101 | 102 | # if use_mixup: 103 | # lam = np.random.beta(alpha, alpha) 104 | # idx = torch.randperm(batchsize) 105 | # mix_im = im * lam + (1. - lam) * im[idx, :] 106 | # mix_lb = lb[idx, :] 107 | # optimizer.zero_grad() 108 | # out = net(mix_im) 109 | # out = F.interpolate(out, lb.size()[2:], mode = 'bilinear') # upsample to original size 110 | # lb = torch.squeeze(lb) 111 | # mix_lb = torch.squeeze(mix_lb) 112 | # loss = lam * Loss(out, lb) + (1. - lam) * Loss(out, mix_lb) 113 | # loss.backward() 114 | # optimizer.step() 115 | # else: 116 | # optimizer.zero_grad() 117 | # out = net(im) 118 | # out = F.interpolate(out, lb.size()[2:], mode = 'bilinear') # upsample to original size 119 | # lb = torch.squeeze(lb) 120 | # loss = Loss(out, lb) 121 | # loss.backward() 122 | # optimizer.step() 123 | 124 | optimizer.zero_grad() 125 | out = net(im) 126 | lb = torch.squeeze(lb) 127 | loss = criteria(out, lb) 128 | loss.backward() 129 | optimizer.step() 130 | 131 | loss = loss.detach().cpu().numpy() 132 | loss_avg.append(loss) 133 | ## log message 134 | if it%cfg.log_iter==0 and not it==0: 135 | loss_avg = sum(loss_avg) / len(loss_avg) 136 | ed = time.time() 137 | t_int = ed - st 138 | lr = optimizer.get_lr() 139 | msg = 'iter: {}/{}, loss: {:.4f}'.format(it, cfg.iter_num, loss_avg) 140 | msg = '{}, lr: {:4f}, time: {:.4f}'.format(msg, lr, t_int) 141 | logger.info(msg) 142 | st = ed 143 | loss_avg = [] 144 | 145 | ## dump model 146 | model_pth = osp.join(cfg.res_pth, 'model_final.pkl') 147 | net.cpu() 148 | state_dict = net.module.state_dict() if hasattr(net, 'module') else net.state_dict() 149 | torch.save(state_dict, model_pth) 150 | logger.info('training done, model saved to: {}'.format(model_pth)) 151 | 152 | ## test after train 153 | if cfg.test_after_train: 154 | net.cuda() 155 | mIOU = eval_model(net, cfg) 156 | logger.info('iou in whole is: {}'.format(mIOU)) 157 | 158 | 159 | if __name__ == "__main__": 160 | args = get_args() 161 | train(args) 162 | -------------------------------------------------------------------------------- /utils/AttrDict.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | class AttrDict(dict): 5 | def __init__(self, *args, **kwargs): 6 | super(AttrDict, self).__init__(*args, **kwargs) 7 | self.__dict__ = self 8 | 9 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CoinCheung/Deeplab-Large-FOV/d9fde31ceec99ca5acbbfe281718ce7884a0aa52/utils/__init__.py -------------------------------------------------------------------------------- /utils/colormap.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python implementation of the color map function for the PASCAL VOC data set. 3 | Official Matlab version can be found in the PASCAL VOC devkit 4 | http://host.robots.ox.ac.uk/pascal/VOC/voc2012/index.html#devkit 5 | """ 6 | import numpy as np 7 | 8 | def color_map(N = 256, normalized = False): 9 | def bitget(byteval, idx): 10 | return ((byteval & (1 << idx)) != 0) 11 | 12 | dtype = 'float32' if normalized else 'uint8' 13 | cmap = np.zeros((N, 3), dtype = dtype) 14 | for i in range(N): 15 | r = g = b = 0 16 | c = i 17 | for j in range(8): 18 | r = r | (bitget(c, 0) << 7-j) 19 | g = g | (bitget(c, 1) << 7-j) 20 | b = b | (bitget(c, 2) << 7-j) 21 | c = c >> 3 22 | 23 | cmap[i] = np.array([r, g, b]) 24 | 25 | cmap = cmap / 255 if normalized else cmap 26 | return cmap 27 | -------------------------------------------------------------------------------- /utils/convert_pascal_aug.py: -------------------------------------------------------------------------------- 1 | import os.path as osp 2 | import os 3 | import scipy.io as scio 4 | import cv2 5 | from PIL import Image 6 | from tqdm import tqdm 7 | 8 | 9 | 10 | def parse_pascal_voc_aug(pth): 11 | out_pth = osp.join(pth, 'VOC_AUG') 12 | ds_pth = osp.join(pth, 'benchmark_RELEASE/dataset') 13 | labels_pth = osp.join(ds_pth, 'cls') 14 | 15 | lbmats = os.listdir(labels_pth) 16 | print('converting mat files to png images') 17 | for lbmat in tqdm(lbmats): 18 | mat_pth = osp.join(labels_pth, lbmat) 19 | mat = scio.loadmat(mat_pth, 20 | mat_dtype = True, 21 | squeeze_me = True, 22 | struct_as_record = False) 23 | lb_arr = mat['GTcls'].Segmentation 24 | lb_name = osp.splitext(lbmat)[0] 25 | lb_fn = '{}.png'.format(lb_name) 26 | lb_save_pth = osp.join(out_pth, 'labels', lb_fn) 27 | lb = Image.fromarray(lb_arr) 28 | lb.save(lb_save_pth) 29 | 30 | 31 | if __name__ == '__main__': 32 | parse_pascal_voc_aug('./data') 33 | -------------------------------------------------------------------------------- /utils/crf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | from pydensecrf import densecrf as dcrf 6 | import numpy as np 7 | 8 | 9 | def crf(img, scores): 10 | ''' 11 | scores: prob numpy array after softmax with shape (_, C, H, W) 12 | img: image of shape (H, W, C) 13 | CRF parameters: bi_w = 4, bi_xy_std = 121, bi_rgb_std = 5, pos_w = 3, pos_xy_std = 3 14 | ''' 15 | pos_w = 3 16 | pos_xy_std = 3 17 | bi_w = 4 18 | bi_xy_std = 121 19 | bi_rgb_std = 5 20 | 21 | scores = np.ascontiguousarray(scores[0]) 22 | img = np.ascontiguousarray(img) 23 | n_classes, h, w = scores.shape 24 | 25 | d = dcrf.DenseCRF2D(w, h, n_classes) 26 | U = -np.log(scores) 27 | U = U.reshape((n_classes, -1)) 28 | d.setUnaryEnergy(U) 29 | 30 | d.addPairwiseGaussian(sxy=pos_xy_std, compat=pos_w) 31 | d.addPairwiseBilateral(sxy=bi_xy_std, srgb=bi_rgb_std, rgbim=img, compat=bi_w) 32 | 33 | Q = d.inference(10) 34 | Q = np.argmax(np.array(Q), axis=0).reshape((h, w)) 35 | 36 | return Q 37 | -------------------------------------------------------------------------------- /utils/logger.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- encoding: utf-8 -*- 3 | 4 | 5 | import os.path as osp 6 | import time 7 | import sys 8 | import logging 9 | 10 | 11 | def setup_logger(logpth): 12 | logfile = 'deeplab_lfov-{}.log'.format(time.strftime('%Y-%m-%d-%H-%M-%S')) 13 | logfile = osp.join(logpth, logfile) 14 | FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s' 15 | logging.basicConfig(level=logging.INFO, format=FORMAT, filename=logfile) 16 | logging.root.addHandler(logging.StreamHandler()) 17 | 18 | 19 | --------------------------------------------------------------------------------