├── .gitattributes ├── .gitignore ├── Detectors_Segmentation.py ├── LICENSE ├── Main_Model.py ├── README.md ├── Setting.py ├── modules ├── ACPD.py ├── Depthawaregate.py ├── Spectralawaregate.py ├── Test modules.py └── non_localgate.py ├── networks └── BackboneNetwork.py ├── test └── Building Instance segmentation vision.py ├── training ├── Boundingbox dataset Transform.py ├── Generator.py └── Model_loss.py └── utils └── gaussian_radius.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.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 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 105 | __pypackages__/ 106 | 107 | # Celery stuff 108 | celerybeat-schedule 109 | celerybeat.pid 110 | 111 | # SageMath parsed files 112 | *.sage.py 113 | 114 | # Environments 115 | .env 116 | .venv 117 | env/ 118 | venv/ 119 | ENV/ 120 | env.bak/ 121 | venv.bak/ 122 | 123 | # Spyder project settings 124 | .spyderproject 125 | .spyproject 126 | 127 | # Rope project settings 128 | .ropeproject 129 | 130 | # mkdocs documentation 131 | /site 132 | 133 | # mypy 134 | .mypy_cache/ 135 | .dmypy.json 136 | dmypy.json 137 | 138 | # Pyre type checker 139 | .pyre/ 140 | 141 | # pytype static type analyzer 142 | .pytype/ 143 | 144 | # Cython debug symbols 145 | cython_debug/ 146 | 147 | # PyCharm 148 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 149 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 150 | # and can be added to the global gitignore or merged into this file. For a more nuclear 151 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 152 | #.idea/ 153 | -------------------------------------------------------------------------------- /Detectors_Segmentation.py: -------------------------------------------------------------------------------- 1 | 2 | def Mean_WH(y2): 3 | x=tf.sort(y2[:,:,:,0:4],direction='DESCENDING',axis=-1)[:,:,:,0:2] 4 | x=tf.expand_dims(tf.math.reduce_mean(x,axis=-1 ), axis=-1) 5 | y=tf.sort(y2[:,:,:,4: ],direction='DESCENDING',axis=-1)[:,:,:,0:2] 6 | y=tf.expand_dims(tf.math.reduce_mean(y,axis=-1 ),axis=-1) 7 | y2_=tf.concat([x, y], axis=-1) 8 | return y2_ 9 | 10 | def centernet_head(image_input,num_classes): 11 | #-------------------------------# 12 | # Decoder 13 | #-------------------------------# 14 | 15 | C5,C4,C3,C2 = ResNet50(image_input) 16 | 17 | # Feature fusion Pyramid 18 | x=Conv2D(1024, 1, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))( C5) 19 | x = BatchNormalization()(x) 20 | x = Activation('relu')(x) 21 | x=Lambda(lambda x: tf.image.resize(x, (32, 32)))(x) 22 | C4=layers.add([C4, x]) 23 | 24 | x=Conv2D(512, 1, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))( C4) 25 | x = BatchNormalization()(x) 26 | x = Activation('relu')(x) 27 | x=Lambda(lambda x: tf.image.resize(x, (64, 64)))(x) 28 | C3=layers.add([C3, x]) 29 | 30 | 31 | nonlocalg=non_localgate( [2,4,6,8],C2) 32 | x= nonlocalg([C4, C2] ) 33 | C2=layers.add([C2, x]) 34 | 35 | x = Dropout(rate=0.5)(C2) 36 | 37 | """ 38 | num_filters = 256 39 | # 16, 16, 2048 -> 32, 32, 256 -> 64, 64, 128 -> 128, 128, 64 40 | 41 | for i in range(3): 42 | # upsampling 43 | x = Conv2DTranspose(num_filters // pow(2, i), (4, 4), strides=2, use_bias=False, padding='same', 44 | kernel_initializer='he_normal', 45 | kernel_regularizer=l2(5e-4))(x) 46 | x = BatchNormalization()(x) 47 | x = Activation('relu')(x) 48 | """ 49 | 50 | # Get the features from 128,128,64 layers 51 | # wh header 52 | y2 = Conv2D(64, 3, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(x) 53 | y2 = BatchNormalization()(y2) 54 | y2 = Activation('relu')(y2) 55 | y2 = Conv2D(8, 1, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(y2) 56 | y2_= Lambda(Mean_WH, name='Mean_WH')(y2) 57 | 58 | 59 | 60 | # hm header enhance 61 | 62 | y1 = Conv2D(64, 3, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(x) 63 | 64 | #---------------# 65 | #get_roipooling=DeformROIPooling( filters=64, pooled_height=3, pooled_width=3 ) 66 | #y1_=get_roipooling([y1,y2]) 67 | #---------------# 68 | #y1_= Lambda( Deformoffset, name='Deformoffset')( [ y1, y2]) 69 | acpd=ACPD(y1 ) 70 | y1_= acpd([y1, y2]) 71 | fusion = layers.add([y1, y1_]) # 72 | 73 | y1 = Conv2D(32, 3, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(fusion)#fusion 74 | y1 = BatchNormalization()(y1) 75 | y1 = Activation('relu')(y1) 76 | y1 = Conv2D(num_classes, 1,padding='same', kernel_initializer='he_normal', kernel_regularizer=l2(5e-4), activation='sigmoid')(y1) 77 | 78 | # wh rectification 79 | y2_re = Conv2D(2, 3, padding='same', kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(fusion) 80 | y2 = layers.add([y2_,y2_re]) # 81 | #y2=y2_ 82 | 83 | 84 | # reg header 85 | y3 = Conv2D(64, 3, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(x) 86 | y3 = BatchNormalization()(y3) 87 | y3 = Activation('relu')(y3) 88 | y3 = Conv2D(2, 1, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(y3) 89 | 90 | 91 | # binary classification 92 | size_before4 = tf.keras.backend.int_shape(image_input) 93 | featurere = Lambda(lambda xx:tf.image.resize(xx,size_before4[1:3]))(x) #resize_images 94 | featurere = Conv2D(2, 3, padding='same', use_bias=False, 95 | kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(featurere) 96 | featurere= Reshape((-1,2))(featurere) 97 | featurere = Softmax(axis=-1)(featurere) 98 | """ 99 | # Prototype mask 100 | x_ = CoordinateChannel2D()(x) 101 | mask_coeff = Conv2D(100, 3, padding='same',activation='tanh', use_bias=False, 102 | kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(x_) 103 | featurere = Conv2D(100, 3, padding='same',activation='relu', use_bias=False, 104 | kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(x_) 105 | featurere= Reshape((K.int_shape(featurere)[1]*K.int_shape(featurere)[2],100))(featurere) 106 | featurere = Softmax(axis=1)(featurere) 107 | """ 108 | return y1, y2, y3, featurere 109 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Main_Model.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def building_instance_segmentation(input_shape, num_classes=1, backbone='resnet50', max_objects=100, mode="train"): 5 | assert backbone in ['resnet50', 'resnet101'] 6 | output_size = input_shape[0] // 4 7 | image_input = Input(shape=input_shape) 8 | hm_input = Input(shape=(output_size, output_size, num_classes)) 9 | wh_input = Input(shape=(max_objects, 2)) 10 | reg_input = Input(shape=(max_objects, 2)) 11 | reg_mask_input = Input(shape=(max_objects,)) 12 | index_input = Input(shape=(max_objects,)) 13 | masks_true=Input(shape=(input_shape[0],input_shape[0],2)) 14 | 15 | if backbone=='resnet50': 16 | 17 | 18 | y1, y2, y3, mask_pred = centernet_head(image_input, num_classes) 19 | 20 | 21 | if mode=="train": 22 | loss_ = Lambda(loss, name='centernet_loss')([y1, y2, y3, hm_input, wh_input, reg_input, reg_mask_input, index_input,mask_pred,masks_true]) 23 | model = Model(inputs=[image_input, hm_input, wh_input, reg_input, reg_mask_input, index_input,masks_true], outputs=[loss_]) 24 | return model 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Building-instance-segmentation 2 | 3 | This is a building instance segmentation network combining multi-task deep learning and multi-modal remote sensing data including LiDAR features and optical image features. The backbone network is fed with multispectral images based on resnet50, and the branch network is input with LiDAR products based on resnet18. In the module files, the Depthawaregate layer and Spectralawaregate layer are embedded into the residual network structure to fuse the multi-modal features. The non_localgate layer construct a cross level global context model. ACPD is a detector based on CenterNet, which introduces deformation convolution operation in supervised learning. 4 | 5 | For method details, please refer to the paper "https://www.mdpi.com/2072-4292/14/19/4920". The code is completed by Tensorflow-Keras 2.0. Rasterio / GDAL require installation to load data. 6 | 7 | ![image](https://user-images.githubusercontent.com/15941731/183735499-82258816-ba97-4853-9bdf-06da5c215077.png) 8 | 9 | We established a building instance segmentation dataset (BISM) using multimodal remote sensing data. The BISM dataset covers 60 square kilometers in Boston, Massachusetts, USA, and contains about 39527 building objects. BISM can be downloaded via http://bismdataset.mikecrm.com/Yc5qJZD. The metadata information follows as table: 10 | 11 | ![metadata information](https://user-images.githubusercontent.com/15941731/183740607-24427d53-6b9d-4295-b9f9-51df8f1df82f.jpg) 12 | LiDAR/image ![image](https://user-images.githubusercontent.com/15941731/183751773-a3bc4f2b-e411-4cb0-a6c7-0ba9a522a9da.png) ![image](https://user-images.githubusercontent.com/15941731/183759807-768f595f-91e5-4a70-b8e9-450bb7b95bdf.png) NDVI ![image](https://user-images.githubusercontent.com/15941731/183759907-ec2f2790-2f38-4940-bb91-f34c2067bbfd.png) DEM ![image](https://user-images.githubusercontent.com/15941731/183760246-e57dbba4-27bd-4482-b6e1-f2c6595210f5.png) Ground-truth. 13 | 14 | If you use our dataset, we recommend you might cite our work: 15 | 16 | Yuan Q, Mohd Shafri HZ. Multi-Modal Feature Fusion Network with Adaptive Center Point Detector for Building Instance Extraction. Remote Sensing. 2022; 14(19):4920. https://doi.org/10.3390/rs14194920 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Setting.py: -------------------------------------------------------------------------------- 1 | 2 | import os 3 | import sys 4 | import random 5 | import itertools 6 | import colorsys 7 | 8 | import numpy as np 9 | from skimage.measure import find_contours 10 | import matplotlib.pyplot as plt 11 | from matplotlib import patches, lines 12 | from matplotlib.patches import Polygon 13 | import IPython.display 14 | 15 | import rasterio 16 | import gdal 17 | from rasterio.plot import show 18 | import cv2.imshow 19 | os.chdir('/Builings instance segmentation') 20 | 21 | ! pip install rasterio-1.2.8-cp37-cp37m-manylinux1_x86_64.whl 22 | ! pip install h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl 23 | 24 | #%tensorflow_version 2.0 25 | import tensorflow as tf 26 | tf.__version__ 27 | -------------------------------------------------------------------------------- /modules/ACPD.py: -------------------------------------------------------------------------------- 1 | 2 | from keras import backend as K 3 | from keras.layers import Layer 4 | class ACPD(Layer): 5 | def __init__(self, fmap, **kwargs): 6 | 7 | self.filters=64 8 | self.kernelsize=3 9 | self.dilated_rates=1 10 | self.B = K.int_shape(fmap)[0] 11 | self.H = K.int_shape(fmap)[1] 12 | self.W = K.int_shape(fmap)[2] 13 | super(ACPD, self).__init__(**kwargs) 14 | 15 | def call(self,arg): 16 | fmap,y2=arg 17 | 18 | B,H,W,C = K.int_shape(fmap) #y2.get_shape().as_list() 19 | 20 | x= K.clip( tf.sort(y2[:,:,:,0:4],direction='DESCENDING',axis=-1)[:,:,:,0:2], 1, W-1 ) 21 | y= K.clip( tf.sort(y2[:,:,:,4: ],direction='DESCENDING',axis=-1)[:,:,:,0:2], 1, H-1 ) 22 | rx=self.dilated_rates*self.kernelsize # dilated rates of abscissa 23 | ry=self.dilated_rates*self.kernelsize # ditated rates of ordinate 24 | 25 | w= tf.reduce_sum(x, axis =-1, keepdims=True ) 26 | h= tf.reduce_sum(y, axis =-1, keepdims=True ) 27 | 28 | # create coordinates grid 29 | row= K.reshape(K.arange(0,H, dtype=tf.float32),[-1,1]) 30 | row= K.expand_dims( K.tile( row, [1,W]), -1) 31 | row = K.reshape(row,[H*W,1]) 32 | 33 | column= K.reshape( K.arange(0,W, dtype=tf.float32), [1,-1]) 34 | column= K.expand_dims( K.tile( column, [H,1]), -1) 35 | column = K.reshape(column,[H*W,1]) 36 | 37 | # get the dilated grid coordinates 38 | x_1=column-1-K.reshape(w/rx, [-1,H*W,1]) 39 | x_0=column+K.reshape(w*1e-10, [-1,H*W,1]) 40 | x_2=column+1+K.reshape(w/rx, [-1,H*W,1]) 41 | x = tf.concat([x_1, x_0, x_2], axis=-1) 42 | x = tf.reshape(x,[-1,H,W,1]) 43 | x = K.tile(x,[1,1,1,self.kernelsize]) 44 | 45 | y_1= row-1-K.reshape(h/ry, [-1,H*W,1]) 46 | y_0=row+K.reshape(h*1e-10, [-1,H*W,1]) 47 | y_2= row+1+ K.reshape(h/ry, [-1,H*W,1]) 48 | y=tf.concat([y_1, y_0, y_2], axis=-1) 49 | y= tf.reshape(y,[-1,H,W,1]) 50 | y = K.tile(y,[1,1,1,self.kernelsize]) 51 | 52 | 53 | # create coordinates of interploation 54 | 55 | x_left=K.clip(tf.math.floor(x),0,W-1) 56 | x_right=K.clip(tf.math.ceil(x),0,W-1) 57 | y_top=K.clip(tf.math.floor(y),0,H-1) 58 | y_bottom=K.clip(tf.math.ceil(y),0,H-1) 59 | # calculate coordinates increment of interploation 60 | x_right_x=K.tile( K.expand_dims( tf.reshape(x_right-x,[-1,W*H*self.kernelsize*self.kernelsize]),-1), [1,1,C]) 61 | x_left_x=K.tile( K.expand_dims(tf.reshape(x-x_left,[-1,W*H*self.kernelsize*self.kernelsize]),-1), [1,1,C]) 62 | y_top_y=K.tile( K.expand_dims(tf.reshape(y-y_top,[-1,W*H*self.kernelsize*self.kernelsize]),-1), [1,1,C]) 63 | y_bottom_y=K.tile( K.expand_dims( tf.reshape(y_bottom-y,[-1,W*H*self.kernelsize*self.kernelsize]),-1), [1,1,C]) 64 | 65 | 66 | # indices of interplolation 67 | left_top=tf.cast(tf.reshape(y_top*W+x_left, [-1,W*H*self.kernelsize*self.kernelsize]),dtype=tf.int32) 68 | right_top=tf.cast(tf.reshape(y_top*W+x_right, [-1,W*H*self.kernelsize*self.kernelsize]),dtype=tf.int32) 69 | left_bottom=tf.cast(tf.reshape(y_bottom*W+x_left, [-1,W*H*self.kernelsize*self.kernelsize]),dtype=tf.int32) 70 | right_bottom=tf.cast(tf.reshape(y_bottom*W+x_right, [-1,W*H*self.kernelsize*self.kernelsize]),dtype=tf.int32) 71 | # get feature value from interplation coordinates 72 | fmap=tf.reshape(fmap,[-1,W*H,C]) 73 | f_left_top=tf.gather(fmap, left_top, batch_dims=1) 74 | f_right_top=tf.gather(fmap, right_top, batch_dims=1) 75 | f_left_bottom=tf.gather(fmap, left_bottom, batch_dims=1) 76 | f_right_bottom=tf.gather(fmap, right_bottom, batch_dims=1) 77 | # calculate bilinear interpolation 78 | f_resize=(x_right_x*f_left_top+ 79 | x_left_x*f_left_bottom)*y_bottom_y +(x_right_x*f_right_top+ 80 | x_left_x*f_right_bottom)*y_top_y 81 | f_resize=K.reshape(f_resize,[-1,H*self.kernelsize,W*self.kernelsize,C]) 82 | 83 | f_resize= Conv2D(filters=self.filters, kernel_size= self.kernelsize, 84 | strides=(self.kernelsize,self.kernelsize), padding='valid', 85 | use_bias=False, kernel_initializer='he_normal', 86 | kernel_regularizer=l2(5e-4))(f_resize) 87 | f_resize = BatchNormalization()(f_resize) 88 | f_resize= Activation('relu')(f_resize) 89 | 90 | return f_resize 91 | 92 | def compute_output_shape(self, input_shape): 93 | return (self.B, self.H, self.W, self.filters ) 94 | 95 | #Test ACPD 96 | image=rasterio.open('/test3/image/241.TIF') #247 185 146 206 97 | image=np.moveaxis(image.read()[0:3],0,2) 98 | 99 | 100 | photo = tf.cast(np.expand_dims(image, 101 | axis=0),dtype=tf.float32) 102 | photo = Lambda(lambda x: tf.image.resize(x, (128, 128)))(photo) 103 | y2 = Conv2D(64, 3, padding='same', use_bias=False, kernel_initializer='he_normal', 104 | kernel_regularizer=l2(5e-4))(photo) 105 | x=y2 106 | y2 = BatchNormalization()(y2) 107 | y2 = Activation('relu')(y2) 108 | y2 = Conv2D(8, 1, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(y2) 109 | 110 | #f_resize = Deformoffset( [x, y2]) 111 | acpd=ACPD(x ) 112 | featuremap= acpd([x, y2]) 113 | plt.imshow( K.eval(featuremap)[0][:,:,30]) 114 | -------------------------------------------------------------------------------- /modules/Depthawaregate.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from keras import backend as K 4 | from keras.layers import Layer 5 | class Depthawaregate(Layer): 6 | 7 | def __init__(self,fmapS,**kwargs): 8 | 9 | self.kernelsize=3 10 | self.stride=1 11 | self.a=-2 12 | self.fmapS=fmapS 13 | super(Depthawaregate, self).__init__(**kwargs) 14 | 15 | def spatial_attention(self, channel_refined_feature): 16 | maxpool_spatial = Lambda(lambda x: K.max(x, axis=-1, keepdims=True))(channel_refined_feature) 17 | avgpool_spatial = Lambda(lambda x: K.mean(x, axis=-1, keepdims=True))(channel_refined_feature) 18 | max_avg_pool_spatial = tf.concat([maxpool_spatial, avgpool_spatial],axis=-1) 19 | return Conv2D(filters=1, kernel_size=(5, 5), padding="same", 20 | activation=None, kernel_initializer='he_normal', use_bias=False)(max_avg_pool_spatial) 21 | 22 | def call(self,arg): 23 | 24 | fmapD,fmapS=arg 25 | fmapD=self.spatial_attention(fmapD ) 26 | B,H,W,C=K.int_shape(fmapS) 27 | 28 | res1=tf.image.extract_patches( 29 | images=fmapD, 30 | sizes=[1, self.kernelsize, self.kernelsize, 1], 31 | strides=[1, self.stride, self.stride, 1], 32 | rates=[1, 1, 1, 1], 33 | padding='SAME') 34 | res2=tf.image.extract_patches( 35 | images=fmapS, 36 | sizes=[1, self.kernelsize, self.kernelsize, 1], 37 | strides=[1, self.stride, self.stride, 1], 38 | rates=[1, 1, 1, 1], 39 | padding='SAME') 40 | res2=K.reshape(res2,[-1,self.kernelsize*H,self.kernelsize*W,C]) 41 | 42 | res1=K.reshape( res1,[-1,H*W*self.kernelsize*self.kernelsize]) 43 | res1_=K.reshape(K.tile(fmapD,[1,1,1,self.kernelsize**2] ), [-1,H*W*self.kernelsize*self.kernelsize]) 44 | depthaware=tf.reshape( tf.math.exp( self.a*tf.abs(res1-res1_) ), [-1,self.kernelsize*H,self.kernelsize*W,1] ) 45 | refmap= res2*depthaware 46 | 47 | refmap = Conv2D(C, (3, 3), strides=(self.kernelsize, self.kernelsize), use_bias=False)(refmap) 48 | refmap = BatchNormalization()(refmap) 49 | refmap = Activation('relu')(refmap) 50 | refmap = layers.add([refmap,fmapS]) 51 | return refmap 52 | 53 | 54 | def compute_output_shape(self): 55 | B,H,W,C=K.int_shape(self.fmapS) 56 | return (B, H, W, C ) 57 | -------------------------------------------------------------------------------- /modules/Spectralawaregate.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from keras import backend as K 4 | from keras.layers import Layer 5 | class Spectralawaregate(Layer): 6 | def __init__(self,kernelsize,stride, fmapD,**kwargs): 7 | self.kernelsize=kernelsize 8 | self.stride=stride 9 | self.fmapD= fmapD 10 | super(Spectralawaregate, self).__init__(**kwargs) 11 | 12 | def call(self, arg): 13 | 14 | fmapD,fmapS=arg 15 | B,H,W,C=K.int_shape(fmapD) 16 | 17 | 18 | fmapS1=AveragePooling2D(pool_size=(self.kernelsize, self.kernelsize), 19 | strides=self.stride, padding='same', data_format=None)(fmapS) 20 | fmapS2=MaxPooling2D(pool_size=(self.kernelsize, self.kernelsize), 21 | strides=self.stride, padding='same', data_format=None)(fmapS) 22 | fmapS= layers.add([fmapS1, fmapS2]) 23 | 24 | fmapS=Conv2D(filters=self.kernelsize**2, kernel_size=1, padding='same', use_bias=False, kernel_initializer='he_normal', 25 | kernel_regularizer=l2(5e-4))( fmapS) 26 | fmapS = BatchNormalization()(fmapS) 27 | fmapS = Activation('relu')(fmapS) 28 | 29 | res1=K.reshape( fmapS, [-1,H*W*self.kernelsize*self.kernelsize,1]) 30 | res2=tf.image.extract_patches( 31 | images=fmapD, 32 | sizes=[1, self.kernelsize, self.kernelsize, 1], 33 | strides=[1, self.stride, self.stride, 1], 34 | rates=[1, 1, 1, 1], 35 | padding='SAME') 36 | 37 | res2=K.reshape(res2,[-1,H*W*self.kernelsize*self.kernelsize,C]) 38 | 39 | refmap = K.reshape(res1*res2, [-1,self.kernelsize*H,self.kernelsize*W,C]) 40 | refmap = Conv2D(C, (3, 3), strides=(3, 3), use_bias=False)(refmap) 41 | refmap = BatchNormalization()(refmap) 42 | refmap = Activation('relu')(refmap) 43 | refmap = layers.add([refmap,fmapD]) 44 | return refmap 45 | def compute_output_shape(self): 46 | 47 | B,H,W,C=K.int_shape(self.fmapD) 48 | 49 | return (B, H, W, C ) 50 | -------------------------------------------------------------------------------- /modules/Test modules.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #Test modules 4 | image=rasterio.open('/test3/image/241.TIF') #247 185 146 206 5 | image=np.moveaxis(image.read()[0:3],0,2) 6 | 7 | 8 | photo = tf.cast(np.expand_dims(image, 9 | axis=0),dtype=tf.float32) 10 | photo = Lambda(lambda x: tf.image.resize(x, (128, 128)))(photo) 11 | y2 = Conv2D(64, 3, padding='same', use_bias=False, kernel_initializer='he_normal', 12 | kernel_regularizer=l2(5e-4))(photo) 13 | x=y2 14 | y2 = BatchNormalization()(y2) 15 | y2 = Activation('relu')(y2) 16 | y2 = Conv2D(64, 1, kernel_initializer='he_normal', kernel_regularizer=l2(5e-4))(y2) 17 | 18 | plt.subplot(1, 3, 1) 19 | plt.title("Depthawaregate") 20 | 21 | depare=Depthawaregate(x) 22 | fmaps=depare( [x, y2] ) 23 | plt.imshow( K.eval(fmaps)[0][:,:,2]) 24 | 25 | plt.subplot(1, 3, 2) 26 | plt.title("Spectralawaregate") 27 | specaware=Spectralawaregate( 3,1,x) 28 | fmaps=specaware( [x, y2]) 29 | 30 | plt.imshow( K.eval(fmaps)[0][:,:,2]) 31 | 32 | plt.subplot(1, 3, 3) 33 | plt.title("non_localgate") 34 | nonlocalg=non_localgate( [2,4,6,8],x) 35 | fmaps= nonlocalg([x, y2] ) 36 | plt.imshow( K.eval(fmaps)[0][:,:,2]) 37 | -------------------------------------------------------------------------------- /modules/non_localgate.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class non_localgate(Layer): 4 | def __init__(self,pool_factors,fmapS,**kwargs): 5 | 6 | self.fmapS= fmapS 7 | self.pool_factors=pool_factors 8 | super(non_localgate, self).__init__(**kwargs) 9 | 10 | def pool_pyramid(self,feats,H,W, pool_factor,out_channel): 11 | pool_outs=[] 12 | 13 | for p in pool_factor: 14 | 15 | pool_size = strides = [int(np.round(float(H)/p)),int(np.round(float(W)/p))] 16 | pooled = AveragePooling2D(pool_size=pool_size,strides=strides,padding='same')(feats) 17 | pooled = tf.image.resize(pooled,(p,p)) 18 | pooled = K.reshape(pooled,[-1,p**2,out_channel] ) 19 | pool_outs.append(pooled) 20 | 21 | pool_outs= tf.concat(pool_outs,axis=1) 22 | return pool_outs 23 | 24 | def call(self, arg ): 25 | 26 | fmapD,fmapS=arg 27 | B,H,W,C_=K.int_shape(fmapS) 28 | C=C_//4 29 | kernelsize=3 30 | stride=1 31 | pool_factors= [2,3,6,8] 32 | 33 | # B,H,W,C_=====> B,S,C =====>B,C,S 34 | fmapD1=Conv2D(C, kernel_size=1, padding='same', use_bias=False, kernel_initializer='he_normal', 35 | kernel_regularizer=l2(5e-4))( fmapD) 36 | fmapD1=self.pool_pyramid(feats=fmapD1,H=H,W=W, pool_factor=self.pool_factors, out_channel=C) 37 | fmapD1_=tf.transpose(fmapD1,[0,2,1] ) 38 | 39 | # B,H,W,C_=====> B,HW,C 40 | fmapS1=Conv2D(C, kernel_size=1, padding='same', use_bias=False, kernel_initializer='he_normal', 41 | kernel_regularizer=l2(5e-4))( fmapS) 42 | fmapS1=K.reshape(fmapS1,[-1,H*W,C]) 43 | 44 | # [B,HW,C] * [B,C,S]=====>[B,HW,S] 45 | non_localS = tf.matmul(fmapS1,fmapD1_) 46 | non_localS = Softmax(axis=-1)(non_localS) 47 | 48 | 49 | # [B,HW,S]* [B,S,C]=====>[B,H,W,C] 50 | fS=K.reshape( tf.matmul(non_localS,fmapD1), [-1,H,W,C]) 51 | fS=Conv2D(C_, kernel_size=1, padding='same', use_bias=False, kernel_initializer='he_normal', 52 | kernel_regularizer=l2(5e-4))( fS) 53 | fS = BatchNormalization()(fS) 54 | fS=layers.add( [ fS,fmapS] ) 55 | return fS 56 | 57 | def compute_output_shape(self): 58 | 59 | B,H,W,C=K.int_shape(self.fmapS) 60 | 61 | return (B, H, W, C ) 62 | -------------------------------------------------------------------------------- /networks/BackboneNetwork.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #-------------------------------------------------------------# 4 | # ResNet50/18 5 | #-------------------------------------------------------------# 6 | from __future__ import print_function 7 | 8 | import keras.backend as K 9 | import numpy as np 10 | from keras import layers 11 | from keras.applications.imagenet_utils import (decode_predictions,preprocess_input) 12 | from keras.layers import (Activation,Reshape, AveragePooling2D, BatchNormalization,Concatenate, 13 | Softmax, Conv2D, Conv2DTranspose, Dense, Dropout, Flatten, 14 | Input, MaxPooling2D, ZeroPadding2D, Lambda, AveragePooling2D) 15 | from keras.models import Model 16 | from keras.preprocessing import image 17 | from keras.regularizers import l2 18 | from keras.utils.data_utils import get_file 19 | 20 | def lidar_block(input_tensor, kernel_size, filters,N): 21 | 22 | filters1, filters2 = filters 23 | for i in range(N): 24 | x = Conv2D(filters1, kernel_size,padding='same', use_bias=False)(input_tensor) 25 | x = BatchNormalization()(x) 26 | x = Activation('relu')(x) 27 | 28 | x = Conv2D(filters2, kernel_size,padding='same', use_bias=False)(x) 29 | x = BatchNormalization()(x) 30 | x = Activation('relu')(x) 31 | 32 | x = layers.add([x, input_tensor]) 33 | x = Activation('relu')(x) 34 | x = MaxPooling2D((3, 3), strides=(2, 2), padding="same")(x) 35 | return x 36 | 37 | def identity_block(input_tensor, kernel_size, filters, stage, block): 38 | 39 | filters1, filters2, filters3 = filters 40 | 41 | conv_name_base = 'res' + str(stage) + block + '_branch' 42 | bn_name_base = 'bn' + str(stage) + block + '_branch' 43 | 44 | x = Conv2D(filters1, (1, 1), name=conv_name_base + '2a', use_bias=False)(input_tensor) 45 | x = BatchNormalization(name=bn_name_base + '2a')(x) 46 | x = Activation('relu')(x) 47 | 48 | x = Conv2D(filters2, kernel_size,padding='same', name=conv_name_base + '2b', use_bias=False)(x) 49 | x = BatchNormalization(name=bn_name_base + '2b')(x) 50 | x = Activation('relu')(x) 51 | 52 | x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c', use_bias=False)(x) 53 | x = BatchNormalization(name=bn_name_base + '2c')(x) 54 | 55 | x = layers.add([x, input_tensor]) 56 | x = Activation('relu')(x) 57 | return x 58 | 59 | 60 | def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)): 61 | 62 | filters1, filters2, filters3 = filters 63 | 64 | conv_name_base = 'res' + str(stage) + block + '_branch' 65 | bn_name_base = 'bn' + str(stage) + block + '_branch' 66 | 67 | x = Conv2D(filters1, (1, 1), strides=strides, 68 | name=conv_name_base + '2a', use_bias=False)(input_tensor) 69 | x = BatchNormalization(name=bn_name_base + '2a')(x) 70 | x = Activation('relu')(x) 71 | 72 | x = Conv2D(filters2, kernel_size, padding='same', 73 | name=conv_name_base + '2b', use_bias=False)(x) 74 | x = BatchNormalization(name=bn_name_base + '2b')(x) 75 | x = Activation('relu')(x) 76 | 77 | x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c', use_bias=False)(x) 78 | x = BatchNormalization(name=bn_name_base + '2c')(x) 79 | 80 | shortcut = Conv2D(filters3, (1, 1), strides=strides, 81 | name=conv_name_base + '1', use_bias=False)(input_tensor) 82 | shortcut = BatchNormalization(name=bn_name_base + '1')(shortcut) 83 | 84 | x = layers.add([x, shortcut]) 85 | x = Activation('relu')(x) 86 | return x 87 | 88 | 89 | def ResNet50(inputs): 90 | # 512x512x3 91 | x = ZeroPadding2D((3, 3))(inputs) 92 | # 256,256,64 93 | fs = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', use_bias=False)(x[:,:,:,0:4]) 94 | fs = BatchNormalization(name='bn_conv1')(fs) 95 | fs = Activation('relu')(fs) 96 | fd = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', use_bias=False)(tf.expand_dims(x[:,:,:,4],axis=-1)) 97 | fd = BatchNormalization(name='bn_conv1')(fd) 98 | fd = Activation('relu')(fd) 99 | 100 | # 256,256,64 -> 128,128,64 101 | fs = MaxPooling2D((3, 3), strides=(2, 2), padding="same")(fs) 102 | fd = MaxPooling2D((3, 3), strides=(2, 2), padding="same")(fd) 103 | 104 | 105 | # 128,128,64 -> 128,128,256 106 | x = conv_block(fs, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1)) 107 | x = identity_block(x, 3, [64, 64, 256], stage=2, block='b') 108 | C2S = identity_block(x, 3, [64, 64, 256], stage=2, block='c') 109 | 110 | 111 | # multi-modal feature fusion in stage2 112 | C2S = Conv2D(32, (1, 1), use_bias=False)(C2S) 113 | C2D = Conv2D(32, (1, 1), use_bias=False)(C2S) 114 | depare=Depthawaregate(C2S) 115 | C2S_=depare( [C2D, C2S] ) 116 | specaware=Spectralawaregate( 3,1,C2D) 117 | C2D=specaware( [C2D, C2S]) 118 | C2 = Conv2D(256, (1, 1), use_bias=False)(C2S_) 119 | C2D = Conv2D(128, (1, 1), use_bias=False)(C2S_) 120 | 121 | # 128,128,256 -> 64,64,512 122 | x = conv_block(C2, 3, [128, 128, 512], stage=3, block='a') 123 | x = identity_block(x, 3, [128, 128, 512], stage=3, block='b') 124 | #x = identity_block(x, 3, [128, 128, 512], stage=3, block='c') 125 | C3S = identity_block(x, 3, [128, 128, 512], stage=3, block='d') 126 | C3D= lidar_block(C2D, 3, [128,128],2) 127 | 128 | # multi-modal feature fusion in stage3 129 | C3S = Conv2D(64, (1, 1), use_bias=False)(C3S) 130 | C3D = Conv2D(64, (1, 1), use_bias=False)(C3D) 131 | depare=Depthawaregate(C3S) 132 | C3S_=depare( [C3D, C3S] ) 133 | specaware=Spectralawaregate( 3,1,C3D) 134 | C3D=specaware( [C3D, C3S]) 135 | C3 = Conv2D(512, (1, 1), use_bias=False)(C3S_) 136 | 137 | # 64,64,512 -> 32,32,1024 138 | x = conv_block(C3, 3, [256, 256, 1024], stage=4, block='a') 139 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='b') 140 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='c') 141 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='d') 142 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='e') 143 | C4 = identity_block(x, 3, [256, 256, 1024], stage=4, block='f') 144 | 145 | # 32,32,1024 -> 16,16,2048 146 | x = conv_block(C4, 3, [512, 512, 2048], stage=5, block='a') 147 | x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b') 148 | C5 = identity_block(x, 3, [512, 512, 2048], stage=5, block='c') 149 | 150 | return C5,C4,C3,C2 151 | -------------------------------------------------------------------------------- /test/Building Instance segmentation vision.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from matplotlib.axes._axes import _log as matplotlib_axes_logger 4 | matplotlib_axes_logger.setLevel('ERROR') 5 | 6 | def apply_mask(image, mask, color, alpha=0.7): 7 | """Apply the given mask to the image. 8 | """ 9 | for c in range(3): 10 | image[:, :, c] = np.where(mask == 0 ,image[:, :, c], 11 | image[:, :, c] *(1 - alpha) + alpha * color[c] * 255) 12 | 13 | return image 14 | 15 | def random_colors(N, bright=True): 16 | """ 17 | Generate random colors. 18 | To get visually distinct colors, generate them in HSV space then 19 | convert to RGB. 20 | """ 21 | brightness = 1.0 if bright else 0.7 22 | hsv = [(i / N, 1, brightness) for i in range(N)] 23 | colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv)) 24 | random.shuffle(colors) 25 | return colors 26 | 27 | def get_box( line ): 28 | j=0 29 | box=np.zeros((len(line[1:]),4)) 30 | for i in line[1:]: 31 | a =np.asarray(i.split(',')).astype(np.float32).reshape(1,5)[0] 32 | box[j]=[a[0],a[3],a[1],a[2]] 33 | j=j+1 34 | return box 35 | 36 | # read bounding box coordinates 37 | 38 | import numpy as np 39 | 40 | txt_path = '/Building instance segmentation/train1.txt' # txt文本路径 /content/drive/MyDrive/test3/train.txt 41 | f = open(txt_path) 42 | data_lists = f.readlines() #读出的是str类型 43 | 44 | line=data_lists[1082].strip('\n').split(' ') 45 | dataset=get_box( line ) 46 | print('Bounding box coordinates shape:',dataset.shape) 47 | 48 | # transform bounding box coordinates 49 | img=rasterio.open("/Building instance segmentation/image/1186.TIF") #247 185 146 206 50 | img_label=rasterio.open("/Building instance segmentation/label/1186.TIF") 51 | img_label=np.moveaxis(img_label.read(),0,2)[:,:,0] 52 | scores=np.random.randint(96,100,size= dataset.shape[0] )/100 53 | 54 | old_img=np.moveaxis(img.read()[0:3],0,2).astype(np.int32) 55 | Image=old_img 56 | #old_img = np.uint8( (cv2.cvtColor(old_img[:,:,0:3], cv2.COLOR_BGR2RGB))*255 ) 57 | 58 | colors = random_colors(dataset.shape[0]) 59 | red=(1.0, 0.0, 0.1200000000000001) 60 | 61 | height, width = old_img.shape[:2] 62 | masks=np.zeros((old_img.shape[0],old_img.shape[1], dataset.shape[0] )) 63 | masked_image = old_img 64 | 65 | fig, ax = plt.subplots(1, figsize=(10,10)) 66 | 67 | for i in range(dataset.shape[0]): 68 | color =red #colors[i] 69 | x1, y1, x2, y2 = dataset[i] 70 | 71 | 72 | p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=4, 73 | alpha=0.8, linestyle="dashed", 74 | edgecolor=colors[i], facecolor='none') 75 | ax.add_patch(p) 76 | 77 | ax.scatter([x1,x2], [y1,y2], c=color, marker='o') 78 | ax.scatter([(x1+x2)/2], [(y1+y2)/2], c=color, marker='^') 79 | 80 | label = 'Bulding'+str(i+1) 81 | caption = "{} {:.2f}".format(label, scores[i]) 82 | """ 83 | ax.text(x1, y2-2, caption, 84 | color='w', size=9, backgroundcolor='none',alpha=1,rotation=90,bbox ={'facecolor': color, 85 | 'alpha':0.3, 'pad':1}) 86 | """ 87 | a= np.trunc(x1 ).astype(int) 88 | b= np.trunc(y1 ).astype(int) 89 | c= np.trunc(x2 ).astype(int) 90 | d= np.trunc(y2 ).astype(int) 91 | #print(a,b,c,d) 92 | 93 | masks[b:d+1,a:c+1,i]= img_label[b:d+1,a:c+1]/255 94 | 95 | masked_image = apply_mask(masked_image, masks[:, :, i], colors[i],alpha=0.5) 96 | 97 | """ 98 | padded_mask = np.zeros( 99 | (masks.shape[0] + 2, masks.shape[1] + 2), dtype=np.uint8) 100 | padded_mask[1:-1, 1:-1] = masks[:, :, i] 101 | contours = find_contours(padded_mask, 0.5) 102 | for verts in contours: 103 | # Subtract the padding and flip (y, x) to (x, y) 104 | verts = np.fliplr(verts) - 1 105 | p = Polygon(verts, facecolor="none", edgecolor=color) 106 | ax.add_patch(p) 107 | """ 108 | 109 | 110 | ax.set_ylim(height + 8, -8) 111 | ax.set_xlim(-8, width + 8) 112 | ax.axis('on') 113 | #ax.set_title('Building Instance Segmentation') 114 | ax.imshow(masked_image.astype(np.uint8)) 115 | ax.set_xticks([]) 116 | ax.set_yticks([]) 117 | #plt.scatter(datasetaffine[:,0],datasetaffine[:,2]) 118 | #plt.scatter(datasetaffine[:,1],datasetaffine[:,3]) 119 | #fig.savefig('/content/drive/MyDrive/146.jpg', dpi=150) 120 | -------------------------------------------------------------------------------- /training/Boundingbox dataset Transform.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # read bounding box coordinates 4 | 5 | import numpy as np 6 | 7 | txt_path = '/Building instance segmentation/boxes.txt' # txt path 8 | image_path = '/Building instance segmentation/label/' # Image path 9 | saveBasePath = '/Building instance segmentation/' 10 | f = open(txt_path) 11 | ftrain = open(os.path.join(saveBasePath,'train1.txt'), 'w') 12 | data_lists = f.readlines() #str 13 | 14 | dataset= [ ] 15 | j=int(data_lists[0].split(',')[0]) 16 | k=0 17 | 18 | while k!=len(data_lists): 19 | 20 | ftrain.write(data_lists[k].split(',')[0]) 21 | if data_lists[k].split(',')[1] == '\n': 22 | ftrain.write(" "+"0,0,0,0,0"+"\n") 23 | k=k+1 24 | j=int(data_lists[k].split(',')[0]) 25 | else: 26 | 27 | while j ==int(data_lists[k].split(',')[0]) : 28 | 29 | data1 = data_lists[k].strip('\n').strip(',').split(',') #Remove the line breaks at the beginning and "," as spacers 30 | data2 = data_lists[k+1].strip('\n').strip(',').split(',') 31 | x1,y1=np.array(data1[2:4]).astype("float") 32 | x2,y2=np.array(data2[2:4]).astype("float") 33 | xmin, xmax= np.sort([x1,x2]) 34 | ymin, ymax= np.sort([y1,y2]) 35 | 36 | 37 | img_label=rasterio.open(image_path+data2[0]+".TIF") 38 | affineT=np.linalg.inv(np.asarray(img_label.transform).reshape(3,3)) 39 | Y=np.array( [ [xmin, xmax],[ymin, ymax] ] ) 40 | YT=np.dot(affineT,np.vstack(( Y,np.array([1,1]))) ) # d = np.hstack((a,b)) 41 | 42 | ftrain.write(" "+",".join( [item for item in YT[0:2,:].reshape(1,4)[0].astype(np.str)])+ ','+"1" ) 43 | 44 | k=k+2 45 | if k==len(data_lists): 46 | break 47 | 48 | 49 | if k==len(data_lists): 50 | break 51 | else: 52 | ftrain.write("\n") 53 | j=int(data_lists[k].split(',')[0]) 54 | 55 | 56 | 57 | ftrain.close() 58 | 59 | 60 | #dataset = np.array(dataset).astype("float").reshape(-1,4) 61 | #print('Bounding box coordinates shape:',dataset.shape) 62 | 63 | from matplotlib.axes._axes import _log as matplotlib_axes_logger 64 | matplotlib_axes_logger.setLevel('ERROR') 65 | def random_colors(N, bright=True): 66 | """ 67 | Generate random colors. 68 | To get visually distinct colors, generate them in HSV space then 69 | convert to RGB. 70 | """ 71 | brightness = 1.0 if bright else 0.7 72 | hsv = [(i / N, 1, brightness) for i in range(N)] 73 | colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv)) 74 | random.shuffle(colors) 75 | return colors 76 | 77 | # Test transformed data 78 | from utils.utils import draw_gaussian, gaussian_radius 79 | import math 80 | img=rasterio.open("/Building instance segmentation/image/1944.TIF") #247 185 146 206 173 81 | old_img=np.moveaxis(img.read()[0:3],0,2).astype(np.int32) 82 | #old_img = np.uint8( (cv2.cvtColor(old_img[:,:,0:3], cv2.COLOR_BGR2RGB))*255 ) 83 | Boxex=open('/Building instance segmentation/train1.txt').readlines() 84 | line=Boxex[1765].split() 85 | 86 | box=np.zeros((len(line[1:]),4)) 87 | j=0 88 | fig, ax = plt.subplots(1, figsize=(10,10)) 89 | colors = random_colors(box.shape[0]) 90 | heatmap=np.zeros((512,512)) 91 | for i in line[1:]: 92 | box[j]=np.asarray(i.split(',')).astype(float).reshape(1,5)[0][0:4] 93 | x1, x2, y1, y2 = box[j] 94 | #print(x1, x2, y1, y2 ) 95 | color = colors[2] 96 | 97 | p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=4, 98 | alpha=0.7, linestyle="dashed", 99 | edgecolor=color, facecolor='none') 100 | ax.scatter([x1,x2], [y1,y2], c=color, marker='o') 101 | 102 | ax.add_patch(p) 103 | 104 | # get heatmaps 105 | h=y2-y1 106 | w=x2-x1 107 | ct = np.array([(x1+x2) / 2, (y1+y2) / 2], dtype=np.float32) 108 | ct_int = ct.astype(np.int32) 109 | radius = gaussian_radius((math.ceil(h), math.ceil(w))) 110 | radius = max(0, int(radius)) 111 | heatmap = draw_gaussian(heatmap, ct_int, radius) 112 | 113 | 114 | j=j+1 115 | 116 | 117 | ax.imshow(old_img) 118 | ax.axis('off') 119 | 120 | plt.figure(figsize=(5,5)) 121 | plt.imshow(heatmap) 122 | plt.axis('off') 123 | #plt.scatter([(box[:,0]+box[:,1])/2], [(box[:,2]+box[:,3])/2], c='r', marker='o',linewidths=0.001) 124 | 125 | heatmap1 = np.uint8(heatmap*255) 126 | heatmap1 = cv2.applyColorMap(heatmap1, cv2.COLORMAP_JET) 127 | alpha=0.7 128 | fused=alpha*old_img+(1-alpha)*heatmap1 129 | 130 | cv2_imshow(fused) 131 | -------------------------------------------------------------------------------- /training/Generator.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import math 4 | from random import shuffle 5 | 6 | import cv2 7 | import keras.backend as K 8 | import numpy as np 9 | import tensorflow as tf 10 | from matplotlib.colors import hsv_to_rgb, rgb_to_hsv 11 | from PIL import Image 12 | from gaussian_radius 13 | 14 | 15 | 16 | class Generator(object): 17 | def __init__(self,batch_size,train_lines,val_lines, 18 | input_size,num_classes,image_path,label_path,max_objects=100): 19 | 20 | self.batch_size = batch_size 21 | self.train_lines = train_lines 22 | self.val_lines = val_lines 23 | self.input_size = input_size 24 | self.output_size = (int(input_size[0]/4) , int(input_size[1]/4)) 25 | self.num_classes = num_classes 26 | self.max_objects = max_objects 27 | 28 | def get_box( self, line ): 29 | j=0 30 | box=np.zeros((len(line[1:]),5)) 31 | for i in line[1:]: 32 | a =np.asarray(i.split(',')).astype(np.float32).reshape(1,5)[0] 33 | box[j]=[a[0],a[3],a[1],a[2],a[4]] 34 | j=j+1 35 | return box 36 | 37 | 38 | 39 | def get_random_data(self, image_path,label_path,annotation_line): 40 | 41 | line = annotation_line.split( ) 42 | #image = Image.open(image_path+line[0]) 43 | image=rasterio.open(image_path+line[0]+".TIF") #247 185 146 206 44 | image=np.moveaxis(image.read()[0:self.input_size[2]],0,2) 45 | img_label=rasterio.open(label_path+line[0]+".TIF") 46 | img_label=np.moveaxis(img_label.read(),0,2)[:,:,0]/255 47 | #image = np.uint8( (cv2.cvtColor(image[:,:,0:3], cv2.COLOR_BGR2RGB))*255 ) 48 | box = self.get_box( line ) 49 | 50 | return image,box,img_label 51 | 52 | def generate(self, train=True): 53 | while True: 54 | if train: 55 | # 打乱 56 | shuffle(self.train_lines) 57 | lines = self.train_lines 58 | else: 59 | shuffle(self.val_lines) 60 | lines = self.val_lines 61 | 62 | batch_images = np.zeros((self.batch_size, self.input_size[0], self.input_size[1], self.input_size[2]), dtype=np.float32) 63 | batch_hms = np.zeros((self.batch_size, self.output_size[0], self.output_size[1], self.num_classes), dtype=np.float32) 64 | batch_whs = np.zeros((self.batch_size, self.max_objects, 2), dtype=np.float32) 65 | batch_regs = np.zeros((self.batch_size, self.max_objects, 2), dtype=np.float32) 66 | batch_reg_masks = np.zeros((self.batch_size, self.max_objects), dtype=np.float32) 67 | batch_indices = np.zeros((self.batch_size, self.max_objects), dtype=np.float32) 68 | #batch_masks = np.zeros((self.batch_size, self.input_size[0], self.input_size[1],self.max_objects), dtype=np.float32) 69 | batch_masks = np.zeros((self.batch_size,self.input_size[0], self.input_size[1],2)) 70 | 71 | b = 0 72 | for annotation_line in lines: 73 | 74 | 75 | img,y,img_label = self.get_random_data(image_path,label_path, annotation_line) 76 | 77 | 78 | if len(y)!=0: 79 | boxes = np.array(y[:,:4],dtype=np.float32) 80 | dataset= np.array(y[:,:4],dtype=np.float32) 81 | 82 | boxes[:,0] = boxes[:,0]/self.input_size[1]*self.output_size[1] 83 | boxes[:,1] = boxes[:,1]/self.input_size[0]*self.output_size[0] 84 | boxes[:,2] = boxes[:,2]/self.input_size[1]*self.output_size[1] 85 | boxes[:,3] = boxes[:,3]/self.input_size[0]*self.output_size[0] 86 | 87 | for i in range(len(y)): 88 | bbox = boxes[i].copy() 89 | bbox = np.array(bbox) 90 | bbox[[0, 2]] = np.clip(bbox[[0, 2]], 0, self.output_size[1] - 1) 91 | bbox[[1, 3]] = np.clip(bbox[[1, 3]], 0, self.output_size[0] - 1) 92 | cls_id = int(y[i,-1])-1 93 | 94 | h, w = bbox[3] - bbox[1], bbox[2] - bbox[0] 95 | if h > 0 and w > 0: 96 | ct = np.array([(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2], dtype=np.float32) 97 | ct_int = ct.astype(np.int32) 98 | 99 | # Get heatmap 100 | radius = gaussian_radius((math.ceil(h), math.ceil(w))) 101 | radius = max(0, int(radius)) 102 | batch_hms[b, :, :, cls_id] = draw_gaussian(batch_hms[b, :, :, cls_id], ct_int, radius) 103 | batch_whs[b, i] = 1. * w, 1. * h 104 | 105 | 106 | 107 | # Compute centeroffsets 108 | batch_regs[b, i] = ct - ct_int 109 | 110 | 111 | # Mark index to 1 to remove 0 samples 112 | batch_reg_masks[b, i] = 1 113 | 114 | batch_indices[b, i] = ct_int[1] * self.output_size[1] + ct_int[0] 115 | """ 116 | # Generate masks 117 | x1, y1, x2, y2 = dataset[i] 118 | 119 | A= np.trunc(x1 ).astype(int) 120 | B= np.trunc(y1 ).astype(int) 121 | C= np.trunc(x2 ).astype(int) 122 | D= np.trunc(y2 ).astype(int) 123 | batch_masks[b,B:D+1,A:C+1,i]= img_label[B:D+1,A:C+1] 124 | """ 125 | 126 | 127 | batch_masks[b,: , : , 0 ] = (img_label == 1 ).astype(int) 128 | batch_masks[b,: , : , 1 ] = (img_label == 0 ).astype(int) 129 | 130 | 131 | # origninal data BGR images 132 | batch_images[b] = img 133 | b = b + 1 134 | if b == self.batch_size: 135 | b = 0 136 | yield [batch_images, batch_hms, batch_whs, batch_regs, batch_reg_masks, batch_indices, batch_masks], np.zeros((self.batch_size,)) # 137 | 138 | batch_images = np.zeros((self.batch_size, self.input_size[0], self.input_size[1], self.input_size[2]), dtype=np.float32) 139 | 140 | batch_hms = np.zeros((self.batch_size, self.output_size[0], self.output_size[1], self.num_classes), 141 | dtype=np.float32) 142 | batch_whs = np.zeros((self.batch_size, self.max_objects, 2), dtype=np.float32) 143 | batch_regs = np.zeros((self.batch_size, self.max_objects, 2), dtype=np.float32) 144 | batch_reg_masks = np.zeros((self.batch_size, self.max_objects), dtype=np.float32) 145 | batch_indices = np.zeros((self.batch_size, self.max_objects), dtype=np.float32) 146 | #batch_masks = np.zeros((self.batch_size, self.input_size[0], self.input_size[1],self.max_objects), dtype=np.float32) 147 | batch_masks = np.zeros((self.batch_size,self.input_size[0], self.input_size[1], 2)) 148 | -------------------------------------------------------------------------------- /training/Model_loss.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # model loss 4 | def focal_loss(hm_pred, hm_true): 5 | #-------------------------------------------------------------------------# 6 | # find PT and PN in each image 7 | 8 | #-------------------------------------------------------------------------# 9 | pos_mask = tf.cast(tf.equal(hm_true, 1), tf.float32) 10 | neg_mask = tf.cast(tf.less(hm_true, 1), tf.float32) 11 | #-------------------------------------------------------------------------# 12 | 13 | neg_weights = tf.pow(1 - hm_true, 4) 14 | 15 | #-------------------------------------------------------------------------# 16 | # Focal loss 17 | #-------------------------------------------------------------------------# 18 | pos_loss = -tf.math.log(tf.clip_by_value(hm_pred, 1e-6, 1.)) * tf.pow(1 - hm_pred, 2) * pos_mask 19 | neg_loss = -tf.math.log(tf.clip_by_value(1 - hm_pred, 1e-6, 1.)) * tf.pow(hm_pred, 2) * neg_weights * neg_mask 20 | 21 | num_pos = tf.reduce_sum(pos_mask) 22 | pos_loss = tf.reduce_sum(pos_loss) 23 | neg_loss = tf.reduce_sum(neg_loss) 24 | 25 | #-------------------------------------------------------------------------# 26 | # normalization 27 | #-------------------------------------------------------------------------# 28 | cls_loss = tf.cond(tf.greater(num_pos, 0), lambda: (pos_loss + neg_loss) / num_pos, lambda: neg_loss) 29 | return cls_loss 30 | 31 | 32 | def reg_l1_loss(y_pred, y_true, indices, mask): 33 | #b = tf.shape(y_pred)[0] 34 | 35 | #k = tf.shape(indices)[1] 36 | #c = tf.shape(y_pred)[-1] 37 | #y_pred = tf.reshape(y_pred, (b, -1, c)) 38 | y_pred = tf.reshape(y_pred, (-1, K.int_shape(y_pred)[1]*K.int_shape(y_pred)[2], K.int_shape(y_pred)[3])) 39 | 40 | indices = tf.cast(indices, tf.int32) 41 | y_pred = tf.gather(y_pred, indices, batch_dims=1) 42 | mask = tf.tile(tf.expand_dims(mask, axis=-1), (1, 1, 2)) 43 | total_loss = tf.reduce_sum(tf.abs(y_true * mask - y_pred * mask)) 44 | reg_loss = total_loss / (tf.reduce_sum(mask) + 1e-4) 45 | return reg_loss 46 | 47 | def binary_crossentropy(y_true, y_pred): 48 | size = tf.keras.backend.int_shape(y_true) 49 | y_true = tf.reshape( y_true, [-1,size[1]*size[2],2] ) 50 | loss = K.binary_crossentropy(y_true,y_pred) #K.categorical_crossentropy(y_true,y_pred) 51 | loss=K.mean(loss) 52 | return loss 53 | 54 | def mask_crossentropy(y_true, y_pred,mask_coeff,indices,mask): 55 | # resize y_true 56 | size = tf.keras.backend.int_shape(mask_coeff) 57 | y_true = Lambda(lambda xx:tf.image.resize_images(xx,size[1:3]))(y_true) 58 | y_true = Reshape( (-1, K.int_shape(mask_coeff)[3]) )(y_true) 59 | 60 | # compute reconstructed feature using mask_coeff and prototype 61 | indices = tf.cast(indices, tf.int32) 62 | mask_coeff = Reshape( (-1, K.int_shape(mask_coeff)[3]) )(mask_coeff) 63 | mask_coeff_ = tf.gather(mask_coeff, indices, batch_dims=1) 64 | mask_coeff_ = tf.tile(tf.expand_dims(mask_coeff_, axis=2), (1, 1, K.int_shape(y_pred)[1], 1)) 65 | y_pred = tf.expand_dims(y_pred, axis=1) 66 | feature = tf.reduce_sum( y_pred*mask_coeff_, axis=-1) 67 | feature = tf.transpose (feature,[0,2,1] ) 68 | 69 | # compute binary_crossentropy loss 70 | 71 | mask = tf.expand_dims(mask, axis=1) 72 | loss = K.binary_crossentropy(y_true,feature*mask) 73 | loss = K.mean(loss) 74 | 75 | return loss 76 | 77 | 78 | 79 | def dice_coef_loss(y_true, y_pred, smooth): 80 | intersection = K.sum(y_true * y_pred, axis=[1,2,3]) 81 | union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3]) 82 | dice_coef=(2. * intersection + smooth) / (union + smooth) 83 | 84 | return K.mean( 1-dice_coef, axis=0) 85 | 86 | def loss(args): 87 | 88 | #-----------------------------------------------------------------------------------------------------------------# 89 | # hm_pred: (batch_size, 128, 128, num_classes) 90 | # wh_pred: (batch_size, 128, 128, 2) 91 | # reg_pred:center offset (batch_size, 128, 128, 2) 92 | # hm_true:heatmap (batch_size, 128, 128, num_classes) 93 | # wh_true: (batch_size, max_objects, 2) 94 | # reg_true: (batch_size, max_objects, 2) 95 | # reg_mask: (batch_size, max_objects) 96 | # indices: (batch_size, max_objects) 97 | #-----------------------------------------------------------------------------------------------------------------# 98 | #y1, y2, y3, hm_input, wh_input, reg_input, reg_mask_input, index_input, masks 99 | hm_pred, wh_pred, reg_pred, hm_true,wh_true,reg_true,reg_mask,indices,mask_pred,masks_true = args 100 | hm_loss = focal_loss(hm_pred, hm_true) 101 | wh_loss = 0.1 * reg_l1_loss(wh_pred, wh_true, indices, reg_mask) 102 | reg_loss = reg_l1_loss(reg_pred, reg_true, indices, reg_mask) 103 | #mask_loss = dice_coef_loss(masks_true, mask_pred, smooth=0.01) 104 | mask_loss=binary_crossentropy(masks_true, mask_pred) 105 | #mask_loss= mask_crossentropy(masks_true, mask_pred,mask_coeff,indices,reg_mask) 106 | total_loss = hm_loss + wh_loss + reg_loss+3*mask_loss 107 | 108 | return total_loss 109 | -------------------------------------------------------------------------------- /utils/gaussian_radius.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def gaussian_radius(det_size, min_overlap=0.7): 4 | height, width = det_size 5 | 6 | a1 = 1 7 | b1 = (height + width) 8 | c1 = width * height * (1 - min_overlap) / (1 + min_overlap) 9 | sq1 = np.sqrt(b1 ** 2 - 4 * a1 * c1) 10 | r1 = (b1 + sq1) / 2 11 | 12 | a2 = 4 13 | b2 = 2 * (height + width) 14 | c2 = (1 - min_overlap) * width * height 15 | sq2 = np.sqrt(b2 ** 2 - 4 * a2 * c2) 16 | r2 = (b2 + sq2) / 2 17 | 18 | a3 = 4 * min_overlap 19 | b3 = -2 * min_overlap * (height + width) 20 | c3 = (min_overlap - 1) * width * height 21 | sq3 = np.sqrt(b3 ** 2 - 4 * a3 * c3) 22 | r3 = (b3 + sq3) / 2 23 | return min(r1, r2, r3) 24 | --------------------------------------------------------------------------------