├── LICENSE ├── README.md ├── ckpt_convert.py ├── defect_inference.py ├── defect_train.py ├── imgs └── DefectSAM-model.png ├── mask_generator.ipynb ├── predictor.ipynb ├── test_set.txt ├── train_set.txt ├── utils.py └── val_set.txt /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. Copyright and Similar Rights means copyright and/or similar rights 88 | closely related to copyright including, without limitation, 89 | performance, broadcast, sound recording, and Sui Generis Database 90 | Rights, without regard to how the rights are labeled or 91 | categorized. For purposes of this Public License, the rights 92 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 93 | Rights. 94 | d. Effective Technological Measures means those measures that, in the 95 | absence of proper authority, may not be circumvented under laws 96 | fulfilling obligations under Article 11 of the WIPO Copyright 97 | Treaty adopted on December 20, 1996, and/or similar international 98 | agreements. 99 | 100 | e. Exceptions and Limitations means fair use, fair dealing, and/or 101 | any other exception or limitation to Copyright and Similar Rights 102 | that applies to Your use of the Licensed Material. 103 | 104 | f. Licensed Material means the artistic or literary work, database, 105 | or other material to which the Licensor applied this Public 106 | License. 107 | 108 | g. Licensed Rights means the rights granted to You subject to the 109 | terms and conditions of this Public License, which are limited to 110 | all Copyright and Similar Rights that apply to Your use of the 111 | Licensed Material and that the Licensor has authority to license. 112 | 113 | h. Licensor means the individual(s) or entity(ies) granting rights 114 | under this Public License. 115 | 116 | i. NonCommercial means not primarily intended for or directed towards 117 | commercial advantage or monetary compensation. For purposes of 118 | this Public License, the exchange of the Licensed Material for 119 | other material subject to Copyright and Similar Rights by digital 120 | file-sharing or similar means is NonCommercial provided there is 121 | no payment of monetary compensation in connection with the 122 | exchange. 123 | 124 | j. Share means to provide material to the public by any means or 125 | process that requires permission under the Licensed Rights, such 126 | as reproduction, public display, public performance, distribution, 127 | dissemination, communication, or importation, and to make material 128 | available to the public including in ways that members of the 129 | public may access the material from a place and at a time 130 | individually chosen by them. 131 | 132 | k. Sui Generis Database Rights means rights other than copyright 133 | resulting from Directive 96/9/EC of the European Parliament and of 134 | the Council of 11 March 1996 on the legal protection of databases, 135 | as amended and/or succeeded, as well as other essentially 136 | equivalent rights anywhere in the world. 137 | 138 | l. You means the individual or entity exercising the Licensed Rights 139 | under this Public License. Your has a corresponding meaning. 140 | 141 | 142 | Section 2 -- Scope. 143 | 144 | a. License grant. 145 | 146 | 1. Subject to the terms and conditions of this Public License, 147 | the Licensor hereby grants You a worldwide, royalty-free, 148 | non-sublicensable, non-exclusive, irrevocable license to 149 | exercise the Licensed Rights in the Licensed Material to: 150 | 151 | a. reproduce and Share the Licensed Material, in whole or 152 | in part, for NonCommercial purposes only; and 153 | 154 | b. produce, reproduce, and Share Adapted Material for 155 | NonCommercial purposes only. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. No downstream restrictions. You may not offer or impose 186 | any additional or different terms or conditions on, or 187 | apply any Effective Technological Measures to, the 188 | Licensed Material if doing so restricts exercise of the 189 | Licensed Rights by any recipient of the Licensed 190 | Material. 191 | 192 | 6. No endorsement. Nothing in this Public License constitutes or 193 | may be construed as permission to assert or imply that You 194 | are, or that Your use of the Licensed Material is, connected 195 | with, or sponsored, endorsed, or granted official status by, 196 | the Licensor or others designated to receive attribution as 197 | provided in Section 3(a)(1)(A)(i). 198 | 199 | b. Other rights. 200 | 201 | 1. Moral rights, such as the right of integrity, are not 202 | licensed under this Public License, nor are publicity, 203 | privacy, and/or other similar personality rights; however, to 204 | the extent possible, the Licensor waives and/or agrees not to 205 | assert any such rights held by the Licensor to the limited 206 | extent necessary to allow You to exercise the Licensed 207 | Rights, but not otherwise. 208 | 209 | 2. Patent and trademark rights are not licensed under this 210 | Public License. 211 | 212 | 3. To the extent possible, the Licensor waives any right to 213 | collect royalties from You for the exercise of the Licensed 214 | Rights, whether directly or through a collecting society 215 | under any voluntary or waivable statutory or compulsory 216 | licensing scheme. In all other cases the Licensor expressly 217 | reserves any right to collect such royalties, including when 218 | the Licensed Material is used other than for NonCommercial 219 | purposes. 220 | 221 | 222 | Section 3 -- License Conditions. 223 | 224 | Your exercise of the Licensed Rights is expressly made subject to the 225 | following conditions. 226 | 227 | a. Attribution. 228 | 229 | 1. If You Share the Licensed Material (including in modified 230 | form), You must: 231 | 232 | a. retain the following if it is supplied by the Licensor 233 | with the Licensed Material: 234 | 235 | i. identification of the creator(s) of the Licensed 236 | Material and any others designated to receive 237 | attribution, in any reasonable manner requested by 238 | the Licensor (including by pseudonym if 239 | designated); 240 | 241 | ii. a copyright notice; 242 | 243 | iii. a notice that refers to this Public License; 244 | 245 | iv. a notice that refers to the disclaimer of 246 | warranties; 247 | 248 | v. a URI or hyperlink to the Licensed Material to the 249 | extent reasonably practicable; 250 | 251 | b. indicate if You modified the Licensed Material and 252 | retain an indication of any previous modifications; and 253 | 254 | c. indicate the Licensed Material is licensed under this 255 | Public License, and include the text of, or the URI or 256 | hyperlink to, this Public License. 257 | 258 | 2. You may satisfy the conditions in Section 3(a)(1) in any 259 | reasonable manner based on the medium, means, and context in 260 | which You Share the Licensed Material. For example, it may be 261 | reasonable to satisfy the conditions by providing a URI or 262 | hyperlink to a resource that includes the required 263 | information. 264 | 265 | 3. If requested by the Licensor, You must remove any of the 266 | information required by Section 3(a)(1)(A) to the extent 267 | reasonably practicable. 268 | 269 | 4. If You Share Adapted Material You produce, the Adapter's 270 | License You apply must not prevent recipients of the Adapted 271 | Material from complying with this Public License. 272 | 273 | 274 | Section 4 -- Sui Generis Database Rights. 275 | 276 | Where the Licensed Rights include Sui Generis Database Rights that 277 | apply to Your use of the Licensed Material: 278 | 279 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 280 | to extract, reuse, reproduce, and Share all or a substantial 281 | portion of the contents of the database for NonCommercial purposes 282 | only; 283 | 284 | b. if You include all or a substantial portion of the database 285 | contents in a database in which You have Sui Generis Database 286 | Rights, then the database in which You have Sui Generis Database 287 | Rights (but not its individual contents) is Adapted Material; and 288 | 289 | c. You must comply with the conditions in Section 3(a) if You Share 290 | all or a substantial portion of the contents of the database. 291 | 292 | For the avoidance of doubt, this Section 4 supplements and does not 293 | replace Your obligations under this Public License where the Licensed 294 | Rights include other Copyright and Similar Rights. 295 | 296 | 297 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 298 | 299 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 300 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 301 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 302 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 303 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 304 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 305 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 306 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 307 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 308 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 309 | 310 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 311 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 312 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 313 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 314 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 315 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 316 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 317 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 318 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 319 | 320 | c. The disclaimer of warranties and limitation of liability provided 321 | above shall be interpreted in a manner that, to the extent 322 | possible, most closely approximates an absolute disclaimer and 323 | waiver of all liability. 324 | 325 | 326 | Section 6 -- Term and Termination. 327 | 328 | a. This Public License applies for the term of the Copyright and 329 | Similar Rights licensed here. However, if You fail to comply with 330 | this Public License, then Your rights under this Public License 331 | terminate automatically. 332 | 333 | b. Where Your right to use the Licensed Material has terminated under 334 | Section 6(a), it reinstates: 335 | 336 | 1. automatically as of the date the violation is cured, provided 337 | it is cured within 30 days of Your discovery of the 338 | violation; or 339 | 340 | 2. upon express reinstatement by the Licensor. 341 | 342 | For the avoidance of doubt, this Section 6(b) does not affect any 343 | right the Licensor may have to seek remedies for Your violations 344 | of this Public License. 345 | 346 | c. For the avoidance of doubt, the Licensor may also offer the 347 | Licensed Material under separate terms or conditions or stop 348 | distributing the Licensed Material at any time; however, doing so 349 | will not terminate this Public License. 350 | 351 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 352 | License. 353 | 354 | 355 | Section 7 -- Other Terms and Conditions. 356 | 357 | a. The Licensor shall not be bound by any additional or different 358 | terms or conditions communicated by You unless expressly agreed. 359 | 360 | b. Any arrangements, understandings, or agreements regarding the 361 | Licensed Material not stated herein are separate from and 362 | independent of the terms and conditions of this Public License. 363 | 364 | 365 | Section 8 -- Interpretation. 366 | 367 | a. For the avoidance of doubt, this Public License does not, and 368 | shall not be interpreted to, reduce, limit, restrict, or impose 369 | conditions on any use of the Licensed Material that could lawfully 370 | be made without permission under this Public License. 371 | 372 | b. To the extent possible, if any provision of this Public License is 373 | deemed unenforceable, it shall be automatically reformed to the 374 | minimum extent necessary to make it enforceable. If the provision 375 | cannot be reformed, it shall be severed from this Public License 376 | without affecting the enforceability of the remaining terms and 377 | conditions. 378 | 379 | c. No term or condition of this Public License will be waived and no 380 | failure to comply consented to unless expressly agreed to by the 381 | Licensor. 382 | 383 | d. Nothing in this Public License constitutes or may be interpreted 384 | as a limitation upon, or waiver of, any privileges and immunities 385 | that apply to the Licensor or You, including from the legal 386 | processes of any jurisdiction or authority. 387 | 388 | ======================================================================= 389 | 390 | Creative Commons is not a party to its public 391 | licenses. Notwithstanding, Creative Commons may elect to apply one of 392 | its public licenses to material it publishes and in those instances 393 | will be considered the “Licensor.” The text of the Creative Commons 394 | public licenses is dedicated to the public domain under the CC0 Public 395 | Domain Dedication. Except for the limited purpose of indicating that 396 | material is shared under a Creative Commons public license or as 397 | otherwise permitted by the Creative Commons policies published at 398 | creativecommons.org/policies, Creative Commons does not authorize the 399 | use of the trademark "Creative Commons" or any other trademark or logo 400 | of Creative Commons without its prior written consent including, 401 | without limitation, in connection with any unauthorized modifications 402 | to any of its public licenses or any other arrangements, 403 | understandings, or agreements concerning use of licensed material. For 404 | the avoidance of doubt, this paragraph does not form part of the 405 | public licenses. 406 | 407 | Creative Commons may be contacted at creativecommons.org. 408 | 409 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DefectSAM 2 | Segment Anything in Defect Detection, this is the official repository for DefectSAM. 3 | 4 | ![img](./imgs/DefectSAM-model.png) 5 | 6 | 7 | 8 | ## Installation 9 | 1. Install [Pytorch 2.0](https://pytorch.org/get-started/locally/), and torchvision. 10 | 2. Install Segment Anything: 11 | 12 | ``` 13 | pip install git+https://github.com/facebookresearch/segment-anything.git 14 | ``` 15 | 16 | or clone the repository locally and install with 17 | 18 | ``` 19 | git clone git@github.com:facebookresearch/segment-anything.git 20 | cd segment-anything; pip install -e . 21 | ``` 22 | 23 | 24 | ## Get Started 25 | Download the [model checkpoint](https://drive.google.com/file/d/1VX8O7R7UCUg8In9SShLxK1lVRi97luEf/view?usp=sharing) and place it at e.g., `weights/defect_vit_b` 26 | 27 | ## Dataset 28 | We released more thermal data and artificial annotations in the Releases of this repository. 29 | 30 | Contents of the released thermal defect detection database: 31 | 32 | public 33 | 34 | ├── plane_0: One version of the thermal defect detection dataset that was publicly released. Each sample is uniquely identified by a name and is stored in mat format. 35 | 36 | ├── plane_1: One of the latest iterations of the thermal defect detection dataset is housed in this section. All samples in this release are categorized as flat-type specimens, each bearing a distinct name. 37 | 38 | └── labels: Within this folder reside the labels corresponding to the samples found in the "plane" or "plane_0_public_history" directories. The labels are of two types: segmentation ground truth files, denoted by the .png extension, and box labels, indicated by the .json extension. These labels are associated with the sample names. For instance, for a sample named "0_20200615_1.mat" in the "plane" directory, its label can be found in either "labels/0_20200615_1.png" or "labels/0_20200615_1.json". 39 | 40 | 41 | The generation of JSON labels is facilitated through the utilization of the Labelme tool. In laboratory experiments where equipment remains stationary, each mat file containing a series of frames is considered to represent a single ground truth. Annotating these files involves the collaboration of three experienced human annotators, who annotate the original thermal image sequences or images processed using PCA independently. Initial processing of the mat files through PCA enhances the depth of defect information. Subsequently, Labelme is employed to label the PCA-processed images, resulting in the creation of JSON files. The segmentation ground truth files are binary-valued. 42 | 43 | 44 | ### License 45 | Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) 46 | 47 | 48 | ## Acknowledgements 49 | - We highly appreciate all the challenge organizers and dataset owners for providing the public dataset to the community. 50 | - We thank Meta AI for making the source code of [segment anything](https://github.com/facebookresearch/segment-anything) publicly available. 51 | - We also thank Alexandre Bonnet for sharing this great [blog](https://encord.com/blog/learn-how-to-fine-tune-the-segment-anything-model-sam/) 52 | - We highly thank Jun Ma, etc., for making the source code of MedSAM [paper](https://arxiv.org/abs/2304.12306), [code](https://github.com/bowang-lab/MedSAM) 53 | 54 | ## Reference 55 | ``` 56 | @misc{hu2023segment, 57 | title={Segment Anything in Defect Detection}, 58 | author={Bozhen Hu and Bin Gao and Cheng Tan and Tongle Wu and Stan Z. Li}, 59 | year={2023}, 60 | eprint={2311.10245}, 61 | archivePrefix={arXiv}, 62 | primaryClass={cs.CV} 63 | } 64 | ``` 65 | -------------------------------------------------------------------------------- /ckpt_convert.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import torch 3 | 4 | # %% convert medsam model checkpoint to sam checkpoint format for convenient inference 5 | sam_ckpt_path = "weights/sam_vit_b_01ec64.pth" 6 | medsam_ckpt_path = "weights/medsam_model_best.pth" 7 | save_path = "weights/defect_vit_b.pth" 8 | multi_gpu_ckpt = False # set as True if the model is trained with multi-gpu 9 | 10 | sam_ckpt = torch.load(sam_ckpt_path) 11 | medsam_ckpt = torch.load(medsam_ckpt_path) 12 | sam_keys = sam_ckpt.keys() 13 | for key in sam_keys: 14 | if not multi_gpu_ckpt: 15 | sam_ckpt[key] = medsam_ckpt["model"][key] 16 | else: 17 | sam_ckpt[key] = medsam_ckpt["model"]["module." + key] 18 | 19 | torch.save(sam_ckpt, save_path) 20 | -------------------------------------------------------------------------------- /defect_inference.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | test the image encoder and mask decoder 4 | freeze prompt image encoder 5 | """ 6 | import numpy as np 7 | import matplotlib.pyplot as plt 8 | import os 9 | import scipy.io as sio 10 | os.environ["CUDA_VISIBLE_DEVICES"] = "1" 11 | import sys 12 | 13 | from tqdm import tqdm 14 | from skimage import transform 15 | import torch 16 | import torch.nn as nn 17 | from torch.utils.data import Dataset, DataLoader 18 | import monai 19 | from segment_anything import sam_model_registry 20 | import torch.nn.functional as F 21 | import argparse 22 | import random 23 | from datetime import datetime 24 | import shutil 25 | import glob 26 | import cv2 27 | import json 28 | 29 | # set seeds 30 | seed = 42 31 | # np.random.seed(seed) 32 | torch.manual_seed(seed) 33 | # random.seed(seed) 34 | torch.cuda.empty_cache() 35 | 36 | # torch.distributed.init_process_group(backend="gloo") 37 | 38 | # os.environ["OMP_NUM_THREADS"] = "4" # export OMP_NUM_THREADS=4 39 | # os.environ["OPENBLAS_NUM_THREADS"] = "4" # export OPENBLAS_NUM_THREADS=4 40 | # os.environ["MKL_NUM_THREADS"] = "6" # export MKL_NUM_THREADS=6 41 | # os.environ["VECLIB_MAXIMUM_THREADS"] = "4" # export VECLIB_MAXIMUM_THREADS=4 42 | # os.environ["NUMEXPR_NUM_THREADS"] = "6" # export NUMEXPR_NUM_THREADS=6 43 | def calculate_iou(y_hat, y): 44 | intersection = np.logical_and(y_hat, y) 45 | union = np.logical_or(y_hat, y) 46 | iou = np.sum(intersection) / np.sum(union) 47 | return iou 48 | 49 | def show_mask(mask, ax, random_color=False): 50 | if random_color: 51 | color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0) 52 | else: 53 | color = np.array([251 / 255, 252 / 255, 30 / 255, 0.6]) 54 | h, w = mask.shape[-2:] 55 | mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1) 56 | ax.imshow(mask_image) 57 | 58 | 59 | def show_box(box, ax): 60 | x0, y0 = box[0], box[1] 61 | w, h = box[2] - box[0], box[3] - box[1] 62 | ax.add_patch( 63 | plt.Rectangle((x0, y0), w, h, edgecolor="green", facecolor=(0, 0, 0, 0), lw=2) 64 | ) 65 | 66 | @torch.no_grad() 67 | def defectsam_inference(medsam_model, img_embed, boxes, H, W): 68 | 69 | predicted_masks = np.zeros((img_embed.shape[0], boxes.shape[1], H, W)) 70 | for i in range(boxes.shape[1]): 71 | box = boxes[:, i, :] 72 | box_torch = torch.as_tensor(box, dtype=torch.float, device=img_embed.device) 73 | if len(box.shape) == 2: 74 | box_torch = box_torch[:, None, :] # (B, 1, 4) 75 | sparse_embeddings, dense_embeddings = medsam_model.prompt_encoder( 76 | points=None, 77 | boxes=box_torch, 78 | masks=None, 79 | ) 80 | low_res_logits, _ = medsam_model.mask_decoder( 81 | image_embeddings=img_embed, # (B, 256, 64, 64) 82 | image_pe=medsam_model.prompt_encoder.get_dense_pe(), # (1, 256, 64, 64) 83 | sparse_prompt_embeddings=sparse_embeddings, # (B, 2, 256) 84 | dense_prompt_embeddings=dense_embeddings, # (B, 256, 64, 64) 85 | multimask_output=False, 86 | ) 87 | 88 | low_res_pred = torch.sigmoid(low_res_logits) # (1, 1, 256, 256) 89 | 90 | low_res_pred = F.interpolate( 91 | low_res_pred, 92 | size=(H, W), 93 | mode="bilinear", 94 | align_corners=False, 95 | ) # (1, 1, gt.shape) 96 | low_res_pred = low_res_pred.squeeze().cpu().numpy() # (256, 256) 97 | medsam_seg = (low_res_pred > 0.5).astype(np.uint8) 98 | predicted_masks[:, i, :, :] = medsam_seg 99 | return predicted_masks 100 | 101 | class DefectSAM(nn.Module): 102 | def __init__( 103 | self, 104 | image_encoder, 105 | mask_decoder, 106 | prompt_encoder, 107 | ): 108 | super().__init__() 109 | self.image_encoder = image_encoder 110 | self.mask_decoder = mask_decoder 111 | self.prompt_encoder = prompt_encoder 112 | # freeze prompt encoder 113 | # for param in self.prompt_encoder.parameters(): 114 | # param.requires_grad = False 115 | 116 | def forward(self, image, boxes): 117 | image_embedding = self.image_encoder(image) # (B, 256, 64, 64) 118 | predicted_masks = torch.zeros((image.shape[0], boxes.shape[1], image.shape[2], image.shape[3]), device=image.device) 119 | # do not compute gradients for prompt encoder 120 | for i in range(boxes.shape[1]): 121 | box = boxes[:, i, :] 122 | with torch.no_grad(): 123 | box_torch = torch.as_tensor(box, dtype=torch.float32, device=image.device) 124 | if len(box_torch.shape) == 2: 125 | box_torch = box_torch[:, None, :] # (B, 1, 4) 126 | 127 | sparse_embeddings, dense_embeddings = self.prompt_encoder( 128 | points=None, 129 | boxes=box_torch, 130 | masks=None, 131 | ) 132 | 133 | low_res_masks, _ = self.mask_decoder( 134 | image_embeddings=image_embedding, # (B, 256, 64, 64) 135 | image_pe=self.prompt_encoder.get_dense_pe(), # (1, 256, 64, 64) 136 | sparse_prompt_embeddings=sparse_embeddings, # (B, 2, 256) 137 | dense_prompt_embeddings=dense_embeddings, # (B, 256, 64, 64) 138 | multimask_output=False, 139 | ) 140 | ori_res_masks = F.interpolate( 141 | low_res_masks, 142 | size=(image.shape[2], image.shape[3]), 143 | mode="bilinear", 144 | align_corners=False, 145 | ) 146 | predicted_masks[:, i, :, :] = ori_res_masks.squeeze(1) 147 | 148 | def inference(self, img_embed, boxes, H, W): 149 | predicted_masks = np.zeros((img_embed.shape[0], boxes.shape[1], H, W)) 150 | for i in range(boxes.shape[1]): 151 | box = boxes[:, i, :] 152 | box_torch = torch.as_tensor(box, dtype=torch.float, device=img_embed.device) 153 | if len(box.shape) == 2: 154 | box_torch = box_torch[:, None, :] # (B, 1, 4) 155 | sparse_embeddings, dense_embeddings = self.prompt_encoder( 156 | points=None, 157 | boxes=box_torch, 158 | masks=None, 159 | ) 160 | low_res_logits, _ = self.mask_decoder( 161 | image_embeddings=img_embed, # (B, 256, 64, 64) 162 | image_pe=self.prompt_encoder.get_dense_pe(), # (1, 256, 64, 64) 163 | sparse_prompt_embeddings=sparse_embeddings, # (B, 2, 256) 164 | dense_prompt_embeddings=dense_embeddings, # (B, 256, 64, 64) 165 | multimask_output=False, 166 | ) 167 | 168 | low_res_pred = torch.sigmoid(low_res_logits) # (1, 1, 256, 256) 169 | 170 | low_res_pred = F.interpolate( 171 | low_res_pred, 172 | size=(H, W), 173 | mode="bilinear", 174 | align_corners=False, 175 | ) # (1, 1, gt.shape) 176 | low_res_pred = low_res_pred.squeeze().cpu().numpy() # (256, 256) 177 | medsam_seg = (low_res_pred > 0.5).astype(np.uint8) 178 | predicted_masks[:, i, :, :] = medsam_seg 179 | return predicted_masks 180 | 181 | 182 | 183 | class DefectDataset(Dataset): 184 | def __init__(self, data_root='defect/test_set.txt', label_dir='defect/data/labels_coco/labels', 185 | height=1024, width=1024, heating_num=50, batchsize=8, bbox_shift=10): 186 | file = open(data_root, 'r') 187 | self.data_path = [line.strip() for line in file] 188 | file.close() 189 | 190 | self.label_dir = label_dir 191 | self.height = height 192 | self.width = width 193 | self.heating_num = heating_num 194 | self.batchsize = batchsize 195 | 196 | self.bbox_shift = bbox_shift 197 | print(f"number of samples: {len(self.data_path)}") 198 | 199 | def __len__(self): 200 | return len(self.data_path) 201 | 202 | def __getitem__(self, index): 203 | # load npy image (1024, 1024, 3), [0,1] 204 | file_path = self.data_path[index] 205 | basename = file_path.split('/')[-1].split('.')[0] 206 | label_path = os.path.join(self.label_dir,'{}_label.png'.format(basename)) 207 | 208 | label_img = cv2.imread(label_path, 0) 209 | scale_x = self.width / label_img.shape[1] 210 | scale_y = self.height / label_img.shape[0] 211 | label_img = cv2.resize(label_img, (self.width, self.height)) 212 | label_img[label_img < 120] = 120 213 | label_img[label_img != 120 ] = 0 #0,black,1 white 214 | label_img[label_img != 0] = 255 #label convert 215 | label_img = label_img / 255. 216 | 217 | data_struct = sio.loadmat(file_path) 218 | data = data_struct['data'] 219 | t_len = data.shape[2] 220 | sub = data[:, :, -1] 221 | data = data[:, :, self.heating_num:min(t_len, self.heating_num+160)] 222 | data = data - np.tile(sub[:, :, np.newaxis], (1, 1, data.shape[2])) 223 | 224 | random_indices = np.random.choice(data.shape[2], size=self.batchsize, replace=False) 225 | data = data[:, :, random_indices] 226 | data = cv2.resize(data, (self.width, self.height)) 227 | data = np.transpose(data, (2, 0, 1)) 228 | data = data / 255. 229 | 230 | labels = np.tile(label_img[np.newaxis, :, :], (data.shape[0], 1, 1)) 231 | data = np.tile(data[:, np.newaxis, :, :], (1, 3, 1, 1)) 232 | 233 | label_json = os.path.join(self.label_dir,'{}_label.json'.format(basename)) 234 | bboxes = [] 235 | with open(label_json, 'r') as fp: 236 | label_coord = json.load(fp) 237 | num_classes = len(label_coord['shapes']) 238 | masked_image = np.zeros((labels.shape[0], num_classes, labels.shape[1], labels.shape[2])) 239 | for i in range(num_classes): 240 | shapes = label_coord['shapes'][i] 241 | points = shapes['points'] 242 | x_min, y_min = points[0][0], points[0][1] 243 | x_max, y_max = points[1][0], points[1][1] 244 | x_min = int(x_min * scale_x) 245 | x_max = int(x_max * scale_x) 246 | y_min = int(y_min * scale_y) 247 | y_max = int(y_max * scale_y) 248 | x_min = max(0, x_min - random.randint(0, self.bbox_shift)) 249 | x_max = min(self.width, x_max + random.randint(0, self.bbox_shift)) 250 | y_min = max(0, y_min - random.randint(0, self.bbox_shift)) 251 | y_max = min(self.height, y_max + random.randint(0, self.bbox_shift)) 252 | bboxes.append([x_min, y_min, x_max, y_max]) 253 | masked_image[:, i, y_min:y_max, x_min:x_max] = labels[:, y_min:y_max, x_min:x_max] 254 | 255 | bboxes = np.array(bboxes) 256 | bboxes = np.tile(bboxes[np.newaxis, :, :], (data.shape[0], 1, 1)) 257 | 258 | return ( 259 | torch.tensor(masked_image).float(), 260 | torch.tensor(data).float(), 261 | torch.tensor(bboxes).float(), 262 | basename, 263 | ) 264 | 265 | parser = argparse.ArgumentParser() 266 | parser.add_argument( 267 | "-i", 268 | "--tr_npy_path", 269 | type=str, 270 | default="defect/data", 271 | help="path to training npy files; two subfolders: gts and imgs", 272 | ) 273 | parser.add_argument( 274 | "-o", 275 | "--seg_path", 276 | type=str, 277 | default="defect/output", 278 | help="path to the segmentation folder", 279 | ) 280 | parser.add_argument( 281 | "--box", 282 | type=list, 283 | default=[10,200,100,250], #[95, 255, 190, 350] 284 | help="bounding box of the segmentation target", 285 | ) 286 | parser.add_argument("--device", type=str, default="cuda:0", help="device") 287 | parser.add_argument( 288 | "-chk", 289 | "--checkpoint", 290 | type=str, 291 | default="weights/defect_vit_b.pth", 292 | help="path to the trained model", 293 | ) 294 | parser.add_argument("-num_workers", type=int, default=4) 295 | parser.add_argument("-model_type", type=str, default="vit_b") 296 | parser.add_argument("-work_dir", type=str, default="./work_dir") 297 | parser.add_argument("-width", type=int, default=1024) 298 | parser.add_argument("-height", type=int, default=1024) 299 | parser.add_argument("-heating_num", type=int, default=50) 300 | parser.add_argument("-sample_rate", type=int, default=4) 301 | 302 | args = parser.parse_args() 303 | 304 | 305 | device = torch.device(args.device) 306 | 307 | medsam_model = sam_model_registry[args.model_type](checkpoint=args.checkpoint) 308 | medsam_model = medsam_model.to(device) 309 | medsam_model.eval() 310 | 311 | 312 | test_dataset = DefectDataset(data_root='defect/test_set.txt', height=args.height, width=args.width, 313 | heating_num=args.heating_num, batchsize=args.sample_rate) 314 | 315 | print("Number of training samples: ", len(test_dataset)) 316 | 317 | test_dataloader = DataLoader( 318 | test_dataset, 319 | batch_size=1, 320 | shuffle=False, 321 | num_workers=args.num_workers, 322 | pin_memory=True, 323 | ) 324 | 325 | IOU_plane = [] 326 | IOU_R = [] 327 | R_type = ['036g', '029g', '035g', '012g'] 328 | for step, (labels, data, bboxes, names_temp) in enumerate(test_dataloader): 329 | data = torch.flatten(data, start_dim=0, end_dim=1) 330 | labels = torch.flatten(labels, start_dim=0, end_dim=1) 331 | bboxes = torch.flatten(bboxes, start_dim=0, end_dim=1) 332 | boxes_np = bboxes.detach().cpu().numpy() 333 | labels, data = labels.to(device), data.to(device) 334 | with torch.no_grad(): 335 | image_embedding = medsam_model.image_encoder(data) 336 | defectsam_seg = defectsam_inference(medsam_model, image_embedding, boxes_np, args.height, args.width) 337 | # print('medsam', medsam_seg.shape) 338 | # print('data', data.shape) 339 | # print('label', labels.shape) 340 | labels = labels.cpu().numpy() 341 | data = data.cpu().numpy() 342 | for i in range(data.shape[0]): 343 | label_img = labels[0] 344 | label_img = label_img.astype(bool) 345 | pre_img = defectsam_seg[i] 346 | pre_img = pre_img.astype(bool) 347 | y = label_img[0] 348 | y_hat = pre_img[0] 349 | for j in range(label_img.shape[0]): 350 | y = np.logical_or(y, label_img[j]) 351 | for j in range(pre_img.shape[0]): 352 | y_hat = np.logical_or(y_hat, pre_img[j]) 353 | IOU = calculate_iou(y_hat, y) 354 | if names_temp[0] in R_type: 355 | IOU_R.append(IOU) 356 | else: 357 | IOU_plane.append(IOU) 358 | print('avg plane IOU', sum(IOU_plane)/len(IOU_plane)) 359 | print('avg R IOU', sum(IOU_R)/len(IOU_R)) 360 | # for i in range(data.shape[0]): 361 | # fig = plt.figure(figsize=(10, 10)) 362 | # ax = fig.add_subplot(111) 363 | # img = data[i].cpu().numpy() 364 | # img = img.transpose(1, 2, 0) 365 | # # img = data_np[0].astype(float) 366 | # ax.imshow(img) 367 | 368 | # print(len(medsam_seg)) 369 | # for mask in medsam_seg[i]: 370 | # show_mask(mask, ax, random_color=False) 371 | 372 | # # for box in boxes_np[0]: 373 | # # show_box(box, ax) 374 | # ax.axis("off") 375 | 376 | # # plt.show() 377 | # plt.tight_layout() 378 | # plt.savefig('defect/output/MedSAM/{}_{}.png'.format(names_temp[0], i)) 379 | # plt.shxianow() 380 | # break -------------------------------------------------------------------------------- /defect_train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | train the image encoder and mask decoder 4 | freeze prompt image encoder 5 | """ 6 | import numpy as np 7 | import matplotlib.pyplot as plt 8 | import os 9 | import scipy.io as sio 10 | os.environ["CUDA_VISIBLE_DEVICES"] = "0" 11 | import sys 12 | 13 | from tqdm import tqdm 14 | from skimage import transform 15 | import torch 16 | import torch.nn as nn 17 | from torch.utils.data import Dataset, DataLoader 18 | import monai 19 | from segment_anything import sam_model_registry 20 | import torch.nn.functional as F 21 | import argparse 22 | import random 23 | from datetime import datetime 24 | import shutil 25 | import glob 26 | import cv2 27 | import json 28 | 29 | # set seeds 30 | seed = 42 31 | # np.random.seed(seed) 32 | torch.manual_seed(seed) 33 | # random.seed(seed) 34 | torch.cuda.empty_cache() 35 | 36 | # torch.distributed.init_process_group(backend="gloo") 37 | 38 | # os.environ["OMP_NUM_THREADS"] = "4" # export OMP_NUM_THREADS=4 39 | # os.environ["OPENBLAS_NUM_THREADS"] = "4" # export OPENBLAS_NUM_THREADS=4 40 | # os.environ["MKL_NUM_THREADS"] = "6" # export MKL_NUM_THREADS=6 41 | # os.environ["VECLIB_MAXIMUM_THREADS"] = "4" # export VECLIB_MAXIMUM_THREADS=4 42 | # os.environ["NUMEXPR_NUM_THREADS"] = "6" # export NUMEXPR_NUM_THREADS=6 43 | 44 | def show_mask(mask, ax, random_color=False): 45 | if random_color: 46 | color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0) 47 | else: 48 | color = np.array([251 / 255, 252 / 255, 30 / 255, 0.6]) 49 | h, w = mask.shape[-2:] 50 | mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1) 51 | ax.imshow(mask_image) 52 | 53 | 54 | def show_box(box, ax): 55 | x0, y0 = box[0], box[1] 56 | w, h = box[2] - box[0], box[3] - box[1] 57 | ax.add_patch( 58 | plt.Rectangle((x0, y0), w, h, edgecolor="blue", facecolor=(0, 0, 0, 0), lw=2) 59 | ) 60 | 61 | class DefectDataset(Dataset): 62 | def __init__(self, data_root='defect/test_set.txt', label_dir='defect/data/labels_coco/labels', 63 | height=1024, width=1024, heating_num=50, batchsize=8, bbox_shift=10): 64 | file = open(data_root, 'r') 65 | self.data_path = [line.strip() for line in file] 66 | file.close() 67 | 68 | self.label_dir = label_dir 69 | self.height = height 70 | self.width = width 71 | self.heating_num = heating_num 72 | self.batchsize = batchsize 73 | 74 | self.bbox_shift = bbox_shift 75 | print(f"number of samples: {len(self.data_path)}") 76 | 77 | def __len__(self): 78 | return len(self.data_path) 79 | 80 | def __getitem__(self, index): 81 | # load npy image (1024, 1024, 3), [0,1] 82 | file_path = self.data_path[index] 83 | basename = file_path.split('/')[-1].split('.')[0] 84 | label_path = os.path.join(self.label_dir,'{}_label.png'.format(basename)) 85 | 86 | label_img = cv2.imread(label_path, 0) 87 | scale_x = self.width / label_img.shape[1] 88 | scale_y = self.height / label_img.shape[0] 89 | label_img = cv2.resize(label_img, (self.width, self.height)) 90 | label_img[label_img < 120] = 120 91 | label_img[label_img != 120 ] = 0 #0,black,1 white 92 | label_img[label_img != 0] = 255 #label convert 93 | label_img = label_img / 255. 94 | 95 | data_struct = sio.loadmat(file_path) 96 | data = data_struct['data'] 97 | t_len = data.shape[2] 98 | sub = data[:, :, -1] 99 | data = data[:, :, self.heating_num:min(t_len, self.heating_num+160)] 100 | data = data - np.tile(sub[:, :, np.newaxis], (1, 1, data.shape[2])) 101 | 102 | random_indices = np.random.choice(data.shape[2], size=self.batchsize, replace=False) 103 | data = data[:, :, random_indices] 104 | data = cv2.resize(data, (self.width, self.height)) 105 | data = np.transpose(data, (2, 0, 1)) 106 | data = data / 255. 107 | 108 | labels = np.tile(label_img[np.newaxis, :, :], (data.shape[0], 1, 1)) 109 | data = np.tile(data[:, np.newaxis, :, :], (1, 3, 1, 1)) 110 | 111 | label_json = os.path.join(self.label_dir,'{}_label.json'.format(basename)) 112 | bboxes = [] 113 | with open(label_json, 'r') as fp: 114 | label_coord = json.load(fp) 115 | num_classes = len(label_coord['shapes']) 116 | masked_image = np.zeros((labels.shape[0], num_classes, labels.shape[1], labels.shape[2])) 117 | for i in range(num_classes): 118 | shapes = label_coord['shapes'][i] 119 | points = shapes['points'] 120 | x_min, y_min = points[0][0], points[0][1] 121 | x_max, y_max = points[1][0], points[1][1] 122 | x_min = int(x_min * scale_x) 123 | x_max = int(x_max * scale_x) 124 | y_min = int(y_min * scale_y) 125 | y_max = int(y_max * scale_y) 126 | x_min = max(0, x_min - random.randint(0, self.bbox_shift)) 127 | x_max = min(self.width, x_max + random.randint(0, self.bbox_shift)) 128 | y_min = max(0, y_min - random.randint(0, self.bbox_shift)) 129 | y_max = min(self.height, y_max + random.randint(0, self.bbox_shift)) 130 | bboxes.append([x_min, y_min, x_max, y_max]) 131 | masked_image[:, i, y_min:y_max, x_min:x_max] = labels[:, y_min:y_max, x_min:x_max] 132 | 133 | bboxes = np.array(bboxes) 134 | bboxes = np.tile(bboxes[np.newaxis, :, :], (data.shape[0], 1, 1)) 135 | 136 | return ( 137 | torch.tensor(masked_image).float(), 138 | torch.tensor(data).float(), 139 | torch.tensor(bboxes).float(), 140 | basename, 141 | ) 142 | 143 | parser = argparse.ArgumentParser() 144 | parser.add_argument( 145 | "-i", 146 | "--tr_npy_path", 147 | type=str, 148 | default="defect/data", 149 | help="path to training npy files; two subfolders: gts and imgs", 150 | ) 151 | parser.add_argument("-task_name", type=str, default="DefectSAM-ViT-B") 152 | parser.add_argument("-model_type", type=str, default="vit_b") 153 | parser.add_argument( 154 | "-checkpoint", type=str, default="weights/sam_vit_b_01ec64.pth") 155 | parser.add_argument( 156 | "--load_pretrain", type=bool, default=True, help="use wandb to monitor training") 157 | parser.add_argument("-pretrain_model_path", type=str, default="") 158 | parser.add_argument("-work_dir", type=str, default="./work_dir") 159 | parser.add_argument("-num_epochs", type=int, default=100) 160 | parser.add_argument("-batch_size", type=int, default=1) 161 | parser.add_argument("-num_workers", type=int, default=4) 162 | parser.add_argument("-width", type=int, default=1024) 163 | parser.add_argument("-height", type=int, default=1024) 164 | parser.add_argument("-heating_num", type=int, default=50) 165 | parser.add_argument("-sample_rate", type=int, default=4) 166 | 167 | parser.add_argument( 168 | "-weight_decay", type=float, default=0.01, help="weight decay (default: 0.01)") 169 | parser.add_argument( 170 | "-lr", type=float, default=0.0001, metavar="LR", help="learning rate (absolute lr)") 171 | parser.add_argument( 172 | "-use_wandb", type=bool, default=False, help="use wandb to monitor training" 173 | ) 174 | parser.add_argument("-use_amp", action="store_true", default=False, help="use amp") 175 | parser.add_argument( 176 | "--resume", type=str, default="", help="Resuming training from checkpoint" 177 | ) 178 | parser.add_argument("--device", type=str, default="cuda:0") 179 | 180 | args = parser.parse_args() 181 | 182 | if args.use_wandb: 183 | import wandb 184 | 185 | wandb.login() 186 | wandb.init( 187 | project=args.task_name, 188 | config={ 189 | "lr": args.lr, 190 | "batch_size": args.batch_size, 191 | "data_path": args.tr_npy_path, 192 | "model_type": args.model_type, 193 | },) 194 | 195 | run_id = datetime.now().strftime("%Y%m%d-%H%M") 196 | model_save_path = os.path.join(args.work_dir, args.task_name + "-" + run_id) 197 | device = torch.device(args.device) 198 | 199 | 200 | class DefectSAM(nn.Module): 201 | def __init__( 202 | self, 203 | image_encoder, 204 | mask_decoder, 205 | prompt_encoder, 206 | ): 207 | super().__init__() 208 | self.image_encoder = image_encoder 209 | self.mask_decoder = mask_decoder 210 | self.prompt_encoder = prompt_encoder 211 | # freeze prompt encoder 212 | for param in self.prompt_encoder.parameters(): 213 | param.requires_grad = False 214 | 215 | def forward(self, image, boxes): 216 | image_embedding = self.image_encoder(image) # (B, 256, 64, 64) 217 | predicted_masks = torch.zeros((image.shape[0], boxes.shape[1], image.shape[2], image.shape[3]), device=image.device) 218 | # do not compute gradients for prompt encoder 219 | for i in range(boxes.shape[1]): 220 | box = boxes[:, i, :] 221 | with torch.no_grad(): 222 | box_torch = torch.as_tensor(box, dtype=torch.float32, device=image.device) 223 | if len(box_torch.shape) == 2: 224 | box_torch = box_torch[:, None, :] # (B, 1, 4) 225 | 226 | sparse_embeddings, dense_embeddings = self.prompt_encoder( 227 | points=None, 228 | boxes=box_torch, 229 | masks=None, 230 | ) 231 | 232 | low_res_masks, _ = self.mask_decoder( 233 | image_embeddings=image_embedding, # (B, 256, 64, 64) 234 | image_pe=self.prompt_encoder.get_dense_pe(), # (1, 256, 64, 64) 235 | sparse_prompt_embeddings=sparse_embeddings, # (B, 2, 256) 236 | dense_prompt_embeddings=dense_embeddings, # (B, 256, 64, 64) 237 | multimask_output=False, 238 | ) 239 | ori_res_masks = F.interpolate( 240 | low_res_masks, 241 | size=(image.shape[2], image.shape[3]), 242 | mode="bilinear", 243 | align_corners=False, 244 | ) 245 | predicted_masks[:, i, :, :] = ori_res_masks.squeeze(1) 246 | 247 | def inference(self,): 248 | pass 249 | 250 | 251 | 252 | def main(): 253 | os.makedirs(model_save_path, exist_ok=True) 254 | shutil.copyfile( 255 | __file__, os.path.join(model_save_path, run_id + "_" + os.path.basename(__file__)) 256 | ) 257 | 258 | sam_model = sam_model_registry[args.model_type](checkpoint=args.checkpoint) 259 | Defect_model = DefectSAM( 260 | image_encoder=sam_model.image_encoder, 261 | mask_decoder=sam_model.mask_decoder, 262 | prompt_encoder=sam_model.prompt_encoder, 263 | ).to(device) 264 | Defect_model.train() 265 | 266 | print( 267 | "Number of total parameters: ", 268 | sum(p.numel() for p in Defect_model.parameters()), 269 | ) # 93735472 270 | print( 271 | "Number of trainable parameters: ", 272 | sum(p.numel() for p in Defect_model.parameters() if p.requires_grad), 273 | ) # 93729252 274 | 275 | img_mask_encdec_params = list(Defect_model.image_encoder.parameters()) + list( 276 | Defect_model.mask_decoder.parameters() 277 | ) 278 | optimizer = torch.optim.AdamW( 279 | img_mask_encdec_params, lr=args.lr, weight_decay=args.weight_decay 280 | ) 281 | print( 282 | "Number of image encoder and mask decoder parameters: ", 283 | sum(p.numel() for p in img_mask_encdec_params if p.requires_grad), 284 | ) # 93729252 285 | seg_loss = monai.losses.DiceLoss(sigmoid=True, squared_pred=True, reduction="mean") 286 | # cross entropy loss 287 | ce_loss = nn.BCEWithLogitsLoss(reduction="mean") 288 | 289 | num_epochs = args.num_epochs 290 | iter_num = 0 291 | train_losses = [] 292 | val_losses = [] 293 | best_loss = 1e10 294 | train_dataset = DefectDataset(data_root='defect/train_set.txt', height=args.height, width=args.width, 295 | heating_num=args.heating_num, batchsize=args.sample_rate) 296 | val_dataset = DefectDataset(data_root='defect/val_set.txt', height=args.height, width=args.width, 297 | heating_num=args.heating_num, batchsize=args.sample_rate) 298 | # test_dataset = DefectDataset(data_root='defect/test_set.txt', height=args.height, width=args.width, 299 | # heating_num=args.heating_num, batchsize=args.sample_rate) 300 | 301 | print("Number of training samples: ", len(train_dataset)) 302 | train_dataloader = DataLoader( 303 | train_dataset, 304 | batch_size=args.batch_size, 305 | shuffle=True, 306 | num_workers=args.num_workers, 307 | pin_memory=True, 308 | ) 309 | 310 | val_dataloader = DataLoader( 311 | val_dataset, 312 | batch_size=args.batch_size, 313 | shuffle=True, 314 | num_workers=args.num_workers, 315 | pin_memory=True, 316 | ) 317 | 318 | start_epoch = 0 319 | if args.resume is not None: 320 | if os.path.isfile(args.resume): 321 | ## Map model to be loaded to specified single GPU 322 | checkpoint = torch.load(args.resume, map_location=device) 323 | start_epoch = checkpoint["epoch"] + 1 324 | Defect_model.load_state_dict(checkpoint["model"]) 325 | optimizer.load_state_dict(checkpoint["optimizer"]) 326 | if args.use_amp: 327 | scaler = torch.cuda.amp.GradScaler() 328 | 329 | for epoch in range(start_epoch, num_epochs): 330 | train_epoch_loss = 0 331 | for step, (labels, data, bboxes, names_temp) in enumerate(train_dataloader): 332 | data = torch.flatten(data, start_dim=0, end_dim=1) 333 | labels = torch.flatten(labels, start_dim=0, end_dim=1) 334 | bboxes = torch.flatten(bboxes, start_dim=0, end_dim=1) 335 | optimizer.zero_grad() 336 | boxes_np = bboxes.detach().cpu().numpy() 337 | labels, data = labels.to(device), data.to(device) 338 | if args.use_amp: 339 | ## AMP 340 | with torch.autocast(device_type="cuda", dtype=torch.float16): 341 | medsam_pred = Defect_model(data, boxes_np) 342 | loss = seg_loss(medsam_pred, labels) + ce_loss( 343 | medsam_pred, labels.float() 344 | ) 345 | scaler.scale(loss).backward() 346 | scaler.step(optimizer) 347 | scaler.update() 348 | optimizer.zero_grad() 349 | else: 350 | medsam_pred = Defect_model(data, boxes_np) 351 | seg_loss_ = seg_loss(medsam_pred, labels) 352 | ce_loss_ = ce_loss(medsam_pred, labels.float()) 353 | loss = seg_loss_ + ce_loss_ 354 | loss.backward() 355 | optimizer.step() 356 | optimizer.zero_grad() 357 | 358 | print(f'Epoch: {epoch}, Step: {step}, seg_loss: {seg_loss_.item()}, ce_loss_: {ce_loss_.item()}') 359 | 360 | train_epoch_loss += loss.item() 361 | iter_num += 1 362 | 363 | train_epoch_loss /= step 364 | train_losses.append(train_epoch_loss) 365 | if args.use_wandb: 366 | wandb.log({"train_epoch_loss": train_epoch_loss}) 367 | print( 368 | f'Time: {datetime.now().strftime("%Y%m%d-%H%M")}, Epoch: {epoch}, Train_epoch_loss: {train_epoch_loss}' 369 | ) 370 | 371 | val_epoch_loss = 0 372 | for step, (labels, data, bboxes, names_temp) in enumerate(val_dataloader): 373 | data = torch.flatten(data, start_dim=0, end_dim=1) 374 | labels = torch.flatten(labels, start_dim=0, end_dim=1) 375 | bboxes = torch.flatten(bboxes, start_dim=0, end_dim=1) 376 | boxes_np = bboxes.detach().cpu().numpy() 377 | labels, data = labels.to(device), data.to(device) 378 | with torch.no_grad(): 379 | medsam_pred = Defect_model(data, boxes_np) 380 | seg_loss_ = seg_loss(medsam_pred, labels) 381 | ce_loss_ = ce_loss(medsam_pred, labels.float()) 382 | loss = seg_loss_ + ce_loss_ 383 | 384 | print(f'Epoch: {epoch}, Step: {step}, val_seg_loss: {seg_loss_.item()}, val_ce_loss_: {ce_loss_.item()}') 385 | 386 | val_epoch_loss += loss.item() 387 | iter_num += 1 388 | val_epoch_loss /= step 389 | val_losses.append(val_epoch_loss) 390 | if args.use_wandb: 391 | wandb.log({"val_epoch_loss": val_epoch_loss}) 392 | print( 393 | f'Time: {datetime.now().strftime("%Y%m%d-%H%M")}, Epoch: {epoch}, val_epoch_loss: {val_epoch_loss}' 394 | ) 395 | 396 | ## save the best model 397 | if val_epoch_loss < best_loss: 398 | best_loss = val_epoch_loss 399 | checkpoint = { 400 | "model": Defect_model.state_dict(), 401 | "optimizer": optimizer.state_dict(), 402 | "epoch": epoch, 403 | } 404 | torch.save(checkpoint, os.path.join(model_save_path, "defectsam_model_best.pth")) 405 | losses = {'train_losses': train_losses, 'val_losses': val_losses} 406 | with open(os.path.join(model_save_path, "losses.json"), 'w') as f: 407 | json.dump(losses, f) 408 | # %% plot loss 409 | # plt.plot(losses) 410 | # plt.title("Dice + Cross Entropy Loss") 411 | # plt.xlabel("Epoch") 412 | # plt.ylabel("Loss") 413 | # plt.savefig(join(model_save_path, args.task_name + "train_loss.png")) 414 | # plt.close() 415 | 416 | 417 | if __name__ == "__main__": 418 | main() 419 | -------------------------------------------------------------------------------- /imgs/DefectSAM-model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bozhenhhu/DefectSAM/003367486f29b96e0b6d51185515c2f31c0532cd/imgs/DefectSAM-model.png -------------------------------------------------------------------------------- /predictor.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from segment_anything import SamPredictor, sam_model_registry\n", 10 | "import numpy as np\n", 11 | "import torch\n", 12 | "import matplotlib.pyplot as plt\n", 13 | "import cv2\n", 14 | "import scipy.io as sio\n", 15 | "import os \n", 16 | "import random \n", 17 | "import json\n", 18 | "from torch.utils.data import Dataset, DataLoader\n", 19 | "\n", 20 | "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n", 21 | "def show_mask(mask, ax, random_color=False):\n", 22 | " if random_color:\n", 23 | " color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)\n", 24 | " else:\n", 25 | " color = np.array([30/255, 144/255, 255/255, 0.6])\n", 26 | " h, w = mask.shape[-2:]\n", 27 | " mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n", 28 | " ax.imshow(mask_image)\n", 29 | " \n", 30 | "def show_points(coords, labels, ax, marker_size=375):\n", 31 | " pos_points = coords[labels==1]\n", 32 | " neg_points = coords[labels==0]\n", 33 | " ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)\n", 34 | " ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25) \n", 35 | " \n", 36 | "def show_box(box, ax):\n", 37 | " x0, y0 = box[0], box[1]\n", 38 | " w, h = box[2] - box[0], box[3] - box[1]\n", 39 | " ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2)) " 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "metadata": {}, 46 | "outputs": [], 47 | "source": [ 48 | "class DefectDataset(Dataset):\n", 49 | " def __init__(self, data_root='defect/test_set.txt', label_dir='defect/data/labels_coco/labels',\n", 50 | " height=1024, width=1024, heating_num=50, batchsize=8, bbox_shift=10):\n", 51 | " file = open(data_root, 'r')\n", 52 | " self.data_path = [line.strip() for line in file]\n", 53 | " file.close()\n", 54 | "\n", 55 | " self.label_dir = label_dir\n", 56 | " self.height = height\n", 57 | " self.width = width\n", 58 | " self.heating_num = heating_num\n", 59 | " self.batchsize = batchsize\n", 60 | "\n", 61 | " self.bbox_shift = bbox_shift\n", 62 | " print(f\"number of samples: {len(self.data_path)}\")\n", 63 | "\n", 64 | " def __len__(self):\n", 65 | " return len(self.data_path)\n", 66 | "\n", 67 | " def __getitem__(self, index):\n", 68 | " # load npy image (1024, 1024, 3), [0,1]\n", 69 | " file_path = self.data_path[index]\n", 70 | " basename = file_path.split('/')[-1].split('.')[0]\n", 71 | " label_path = os.path.join(self.label_dir,'{}_label.png'.format(basename))\n", 72 | "\n", 73 | " label_img = cv2.imread(label_path, 0)\n", 74 | " scale_x = self.width / label_img.shape[1]\n", 75 | " scale_y = self.height / label_img.shape[0]\n", 76 | " label_img = cv2.resize(label_img, (self.width, self.height))\n", 77 | " label_img[label_img < 120] = 120\n", 78 | " label_img[label_img != 120 ] = 0 #0,black,1 white\n", 79 | " label_img[label_img != 0] = 255 #label convert\n", 80 | " label_img = label_img / 255.\n", 81 | "\n", 82 | " data_struct = sio.loadmat(file_path)\n", 83 | " data = data_struct['data']\n", 84 | " t_len = data.shape[2]\n", 85 | " sub = data[:, :, -1]\n", 86 | " data = data[:, :, self.heating_num:min(t_len, self.heating_num+160)]\n", 87 | " data = data - np.tile(sub[:, :, np.newaxis], (1, 1, data.shape[2]))\n", 88 | "\n", 89 | " random_indices = np.random.choice(data.shape[2], size=self.batchsize, replace=False)\n", 90 | " data = data[:, :, random_indices]\n", 91 | " data = cv2.resize(data, (self.width, self.height))\n", 92 | " data = np.transpose(data, (2, 0, 1))\n", 93 | " # data = data / 255.\n", 94 | "\n", 95 | " labels = np.tile(label_img[np.newaxis, :, :], (data.shape[0], 1, 1))\n", 96 | " data = np.tile(data[:, np.newaxis, :, :], (1, 3, 1, 1))\n", 97 | "\n", 98 | " label_json = os.path.join(self.label_dir,'{}_label.json'.format(basename))\n", 99 | " bboxes = []\n", 100 | " with open(label_json, 'r') as fp:\n", 101 | " label_coord = json.load(fp)\n", 102 | " num_classes = len(label_coord['shapes'])\n", 103 | " masked_image = np.zeros((labels.shape[0], num_classes, labels.shape[1], labels.shape[2]))\n", 104 | " for i in range(num_classes):\n", 105 | " shapes = label_coord['shapes'][i]\n", 106 | " points = shapes['points']\n", 107 | " x_min, y_min = points[0][0], points[0][1]\n", 108 | " x_max, y_max = points[1][0], points[1][1]\n", 109 | " x_min = int(x_min * scale_x)\n", 110 | " x_max = int(x_max * scale_x)\n", 111 | " y_min = int(y_min * scale_y)\n", 112 | " y_max = int(y_max * scale_y)\n", 113 | " x_min = max(0, x_min - random.randint(0, self.bbox_shift))\n", 114 | " x_max = min(self.width, x_max + random.randint(0, self.bbox_shift))\n", 115 | " y_min = max(0, y_min - random.randint(0, self.bbox_shift))\n", 116 | " y_max = min(self.height, y_max + random.randint(0, self.bbox_shift))\n", 117 | " bboxes.append([x_min, y_min, x_max, y_max])\n", 118 | " masked_image[:, i, y_min:y_max, x_min:x_max] = labels[:, y_min:y_max, x_min:x_max]\n", 119 | "\n", 120 | " bboxes = np.array(bboxes)\n", 121 | " bboxes = np.tile(bboxes[np.newaxis, :, :], (data.shape[0], 1, 1))\n", 122 | "\n", 123 | " return (\n", 124 | " torch.tensor(masked_image).float(),\n", 125 | " torch.tensor(data).float(),\n", 126 | " torch.tensor(bboxes).float(),\n", 127 | " basename,\n", 128 | " )" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "metadata": {}, 135 | "outputs": [], 136 | "source": [ 137 | "width = 1024\n", 138 | "height = 1024\n", 139 | "heating_num=50\n", 140 | "sample_rate=4\n", 141 | "batchsize = 1\n", 142 | "device = \"cuda\"\n", 143 | "sam_checkpoint = \"weights/sam_vit_b_01ec64.pth\"\n", 144 | "model_type = \"vit_b\"\n", 145 | "sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)\n", 146 | "sam.to(device=device)\n", 147 | "\n", 148 | "predictor = SamPredictor(sam)\n", 149 | "test_dataset = DefectDataset(data_root='defect/test_set.txt', height=height, width=width, \n", 150 | " heating_num=heating_num, batchsize=sample_rate)\n", 151 | "test_dataloader = DataLoader(\n", 152 | " test_dataset,\n", 153 | " batch_size=batchsize,\n", 154 | " shuffle=False,\n", 155 | " num_workers=4,\n", 156 | " pin_memory=True,\n", 157 | " )" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": null, 163 | "metadata": {}, 164 | "outputs": [], 165 | "source": [ 166 | "\n", 167 | "# for step, (labels, data, bboxes, names_temp) in enumerate(test_dataloader):\n", 168 | "# data = torch.flatten(data, start_dim=0, end_dim=1)\n", 169 | "# labels = torch.flatten(labels, start_dim=0, end_dim=1)\n", 170 | "# bboxes = torch.flatten(bboxes, start_dim=0, end_dim=1)\n", 171 | "# print(data.shape, labels.shape, bboxes.shape)\n", 172 | "\n", 173 | "# _, axs = plt.subplots(1, 2, figsize=(25, 25))\n", 174 | "# idx = random.randint(0, 4)\n", 175 | "# img = data[idx].cpu().permute(1, 2, 0).numpy()\n", 176 | "# axs[0].imshow(img/255.)\n", 177 | "# axs[0].axis(\"off\")\n", 178 | "# boxes = bboxes[idx].cpu().numpy()\n", 179 | "# for box in boxes:\n", 180 | "# show_box(box, axs[0])\n", 181 | "# # set title\n", 182 | "# axs[0].set_title(names_temp[0])\n", 183 | "\n", 184 | "# img = labels[idx].cpu().permute(1, 2, 0).numpy()\n", 185 | "# axs[1].imshow(img[:, :, 0])\n", 186 | "# for box in boxes:\n", 187 | "# show_box(box, axs[1])\n", 188 | "# axs[1].axis(\"off\")\n", 189 | "# # set title\n", 190 | "# axs[1].set_title(names_temp[0]+'label')\n", 191 | " \n", 192 | "# plt.tight_layout()\n", 193 | "# plt.show()\n", 194 | "# # plt.subplots_adjust(wspace=0.01, hspace=0)\n", 195 | "# # plt.savefig(\"./defect/data_sanitycheck_0.png\", bbox_inches=\"tight\", dpi=300)\n", 196 | "# # plt.close()\n", 197 | "# # show the example\n", 198 | "# print('ok')\n", 199 | "# break" 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": null, 205 | "metadata": {}, 206 | "outputs": [], 207 | "source": [ 208 | "\n", 209 | "# for step, (labels, data, bboxes, names_temp) in enumerate(test_dataloader):\n", 210 | "# data = torch.flatten(data, start_dim=0, end_dim=1)\n", 211 | "# labels = torch.flatten(labels, start_dim=0, end_dim=1)\n", 212 | "# bboxes = torch.flatten(bboxes, start_dim=0, end_dim=1)\n", 213 | "# print(data.shape, labels.shape, bboxes.shape)\n", 214 | "# # boxes_np = bboxes.detach().cpu().numpy()\n", 215 | "# labels, data = labels.to(device), data.to(device)\n", 216 | "# bboxes = bboxes.to(device)\n", 217 | "# # data = data.permute(0, 2, 3, 1)\n", 218 | "# print(data.shape)\n", 219 | "# batched_output = []\n", 220 | "# for i in range(data.shape[0]):\n", 221 | "# print(data[i].shape)\n", 222 | "# predictor.set_image(data[i])\n", 223 | "# transformed_boxes = predictor.transform.apply_boxes_torch(bboxes[i], data[i].shape[:2])\n", 224 | "# masks, _, _ = predictor.predict_torch(\n", 225 | "# point_coords=None,\n", 226 | "# point_labels=None,\n", 227 | "# boxes=transformed_boxes,\n", 228 | "# multimask_output=False,\n", 229 | "# )\n", 230 | "# batched_output.append(masks)\n", 231 | "\n", 232 | "# break\n" 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "execution_count": null, 238 | "metadata": {}, 239 | "outputs": [], 240 | "source": [ 241 | "#visualization\n", 242 | "\n", 243 | "from segment_anything.utils.transforms import ResizeLongestSide\n", 244 | "resize_transform = ResizeLongestSide(sam.image_encoder.img_size)\n", 245 | "\n", 246 | "def prepare_image(image, transform, device):\n", 247 | " image = transform.apply_image(image)\n", 248 | " image = torch.as_tensor(image, device=device.device)\n", 249 | " print('before permute', image.shape)\n", 250 | " return image.permute(2, 0, 1).contiguous()\n", 251 | "\n", 252 | "\n", 253 | "for step, (labels, data, bboxes, names_temp) in enumerate(test_dataloader):\n", 254 | " data = torch.flatten(data, start_dim=0, end_dim=1)\n", 255 | " labels = torch.flatten(labels, start_dim=0, end_dim=1)\n", 256 | " bboxes = torch.flatten(bboxes, start_dim=0, end_dim=1)\n", 257 | " print(data.shape, labels.shape, bboxes.shape)\n", 258 | " boxes_np = bboxes.detach().cpu().numpy()\n", 259 | " # labels, data = labels.to(device), data.to(device)\n", 260 | " bboxes = bboxes.to(device)\n", 261 | " data_np = data.permute(0, 2, 3, 1)\n", 262 | " data_np = data_np.cpu().numpy()\n", 263 | " data_np = data_np.astype(np.uint8)\n", 264 | " print(data.shape)\n", 265 | " \n", 266 | " batched_input = []\n", 267 | " for i in range(data.shape[0]):\n", 268 | " img_tmp = prepare_image(data_np[i], resize_transform, sam)\n", 269 | " print(img_tmp.shape)\n", 270 | " box_tmp = resize_transform.apply_boxes_torch(bboxes[i], data[i].shape[:2])\n", 271 | " print(box_tmp.shape)\n", 272 | " input = {'image': prepare_image(data_np[i], resize_transform, sam),\n", 273 | " 'boxes': resize_transform.apply_boxes_torch(bboxes[i], data_np[i].shape[:2]),\n", 274 | " 'original_size': data_np[i].shape[:2]}\n", 275 | " batched_input.append(input)\n", 276 | " batched_output = sam(batched_input, multimask_output=False)\n", 277 | " print('mask shape:', batched_output[0]['masks'].shape)\n", 278 | "\n", 279 | " fig = plt.figure(figsize=(10, 10))\n", 280 | " ax = fig.add_subplot(111)\n", 281 | " img = data[0].cpu().numpy()\n", 282 | " img = img.transpose(1, 2, 0)\n", 283 | " # img = data_np[0].astype(float)\n", 284 | " ax.imshow(img/255.)\n", 285 | "\n", 286 | " for mask in batched_output[0]['masks']:\n", 287 | " show_mask(mask.cpu().numpy(), ax, random_color=False)\n", 288 | " \n", 289 | " for box in boxes_np[0]:\n", 290 | " show_box(box, ax)\n", 291 | " ax.axis(\"off\")\n", 292 | "\n", 293 | " plt.tight_layout()\n", 294 | " # plt.shxianow()\n", 295 | " break\n" 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": null, 301 | "metadata": {}, 302 | "outputs": [], 303 | "source": [ 304 | "#calculate IOU\n", 305 | "\n", 306 | "from segment_anything.utils.transforms import ResizeLongestSide\n", 307 | "resize_transform = ResizeLongestSide(sam.image_encoder.img_size)\n", 308 | "\n", 309 | "def prepare_image(image, transform, device):\n", 310 | " image = transform.apply_image(image)\n", 311 | " image = torch.as_tensor(image, device=device.device)\n", 312 | " # print('before permute', image.shape)\n", 313 | " return image.permute(2, 0, 1).contiguous()\n", 314 | "\n", 315 | "\n", 316 | "def calculate_iou(y_hat, y):\n", 317 | " intersection = np.logical_and(y_hat, y)\n", 318 | " union = np.logical_or(y_hat, y)\n", 319 | " iou = np.sum(intersection) / np.sum(union)\n", 320 | " return iou\n", 321 | "\n", 322 | "IOU_plane = []\n", 323 | "IOU_R = []\n", 324 | "R_type = ['036g', '029g', '035g', '012g']\n", 325 | "for step, (labels, data, bboxes, names_temp) in enumerate(test_dataloader):\n", 326 | " data = torch.flatten(data, start_dim=0, end_dim=1)\n", 327 | " labels = torch.flatten(labels, start_dim=0, end_dim=1)\n", 328 | " bboxes = torch.flatten(bboxes, start_dim=0, end_dim=1)\n", 329 | " print(data.shape, labels.shape, bboxes.shape)\n", 330 | " boxes_np = bboxes.detach().cpu().numpy()\n", 331 | " # labels, data = labels.to(device), data.to(device)\n", 332 | " bboxes = bboxes.to(device)\n", 333 | " data_np = data.permute(0, 2, 3, 1)\n", 334 | " data_np = data_np.cpu().numpy()\n", 335 | " data_np = data_np.astype(np.uint8)\n", 336 | " # print(data.shape)\n", 337 | " \n", 338 | " batched_input = []\n", 339 | " for i in range(data.shape[0]):\n", 340 | " img_tmp = prepare_image(data_np[i], resize_transform, sam)\n", 341 | " print(img_tmp.shape)\n", 342 | " box_tmp = resize_transform.apply_boxes_torch(bboxes[i], data[i].shape[:2])\n", 343 | " print(box_tmp.shape)\n", 344 | " input = {'image': prepare_image(data_np[i], resize_transform, sam),\n", 345 | " 'boxes': resize_transform.apply_boxes_torch(bboxes[i], data_np[i].shape[:2]),\n", 346 | " 'original_size': data_np[i].shape[:2]}\n", 347 | " batched_input.append(input)\n", 348 | " batched_output = sam(batched_input, multimask_output=False)\n", 349 | " print('mask shape:', batched_output[0]['masks'].shape)\n", 350 | "\n", 351 | "\n", 352 | " labels = labels.cpu().numpy()\n", 353 | " for i in range(data.shape[0]):\n", 354 | " # img = data[i].cpu().numpy()\n", 355 | " # img = img.transpose(1, 2, 0)\n", 356 | " label_img = labels[0]\n", 357 | " label_img = label_img.astype(bool)\n", 358 | " pre_img = batched_output[i]['masks']\n", 359 | " pre_img = pre_img.squeeze(1)\n", 360 | " pre_img = pre_img.cpu().numpy()\n", 361 | " pre_img = pre_img.astype(bool)\n", 362 | " y = label_img[0]\n", 363 | " y_hat = pre_img[0]\n", 364 | " for j in range(label_img.shape[0]):\n", 365 | " y = np.logical_or(y, label_img[j])\n", 366 | " for j in range(pre_img.shape[0]):\n", 367 | " y_hat = np.logical_or(y_hat, pre_img[j])\n", 368 | " IOU = calculate_iou(y_hat, y)\n", 369 | " if names_temp[0] in R_type:\n", 370 | " IOU_R.append(IOU)\n", 371 | " else:\n", 372 | " IOU_plane.append(IOU)\n", 373 | "\n", 374 | "\n", 375 | "print('avg plane IOU', sum(IOU_plane)/len(IOU_plane))\n", 376 | "print('avg R IOU', sum(IOU_R)/len(IOU_R))\n" 377 | ] 378 | }, 379 | { 380 | "cell_type": "code", 381 | "execution_count": null, 382 | "metadata": {}, 383 | "outputs": [], 384 | "source": [ 385 | "#generate images\n", 386 | "from segment_anything.utils.transforms import ResizeLongestSide\n", 387 | "resize_transform = ResizeLongestSide(sam.image_encoder.img_size)\n", 388 | "\n", 389 | "def prepare_image(image, transform, device):\n", 390 | " image = transform.apply_image(image)\n", 391 | " image = torch.as_tensor(image, device=device.device)\n", 392 | " print('before permute', image.shape)\n", 393 | " return image.permute(2, 0, 1).contiguous()\n", 394 | "\n", 395 | "\n", 396 | "for step, (labels, data, bboxes, names_temp) in enumerate(test_dataloader):\n", 397 | " data = torch.flatten(data, start_dim=0, end_dim=1)\n", 398 | " labels = torch.flatten(labels, start_dim=0, end_dim=1)\n", 399 | " bboxes = torch.flatten(bboxes, start_dim=0, end_dim=1)\n", 400 | " print(data.shape, labels.shape, bboxes.shape)\n", 401 | " boxes_np = bboxes.detach().cpu().numpy()\n", 402 | " # labels, data = labels.to(device), data.to(device)\n", 403 | " bboxes = bboxes.to(device)\n", 404 | " data_np = data.permute(0, 2, 3, 1)\n", 405 | " data_np = data_np.cpu().numpy()\n", 406 | " data_np = data_np.astype(np.uint8)\n", 407 | " print(data.shape)\n", 408 | " \n", 409 | " batched_input = []\n", 410 | " for i in range(data.shape[0]):\n", 411 | " img_tmp = prepare_image(data_np[i], resize_transform, sam)\n", 412 | " print(img_tmp.shape)\n", 413 | " box_tmp = resize_transform.apply_boxes_torch(bboxes[i], data[i].shape[:2])\n", 414 | " print(box_tmp.shape)\n", 415 | " input = {'image': prepare_image(data_np[i], resize_transform, sam),\n", 416 | " 'boxes': resize_transform.apply_boxes_torch(bboxes[i], data_np[i].shape[:2]),\n", 417 | " 'original_size': data_np[i].shape[:2]}\n", 418 | " batched_input.append(input)\n", 419 | " batched_output = sam(batched_input, multimask_output=False)\n", 420 | " print('mask shape:', batched_output[0]['masks'].shape)\n", 421 | "\n", 422 | " for i in range(data.shape[0]):\n", 423 | " fig = plt.figure(figsize=(10, 10))\n", 424 | " ax = fig.add_subplot(111)\n", 425 | " img = data[i].cpu().numpy()\n", 426 | " img = img.transpose(1, 2, 0)\n", 427 | " # img = data_np[0].astype(float)\n", 428 | " ax.imshow(img/255.)\n", 429 | "\n", 430 | " # for mask in batched_output[i]['masks']:\n", 431 | " # show_mask(mask.cpu().numpy(), ax, random_color=False)\n", 432 | " \n", 433 | " # for box in boxes_np[i]:\n", 434 | " # show_box(box, ax)\n", 435 | " ax.axis(\"off\")\n", 436 | "\n", 437 | " plt.tight_layout()\n", 438 | " plt.savefig('defect/output/original/{}_{}.png'.format(names_temp[0], i))\n", 439 | " # plt.shxianow()\n", 440 | " \n" 441 | ] 442 | }, 443 | { 444 | "cell_type": "code", 445 | "execution_count": null, 446 | "metadata": {}, 447 | "outputs": [], 448 | "source": [ 449 | "for step, (labels, data, bboxes, names_temp) in enumerate(test_dataloader):\n", 450 | " data = torch.flatten(data, start_dim=0, end_dim=1)\n", 451 | " labels = torch.flatten(labels, start_dim=0, end_dim=1)\n", 452 | " bboxes = torch.flatten(bboxes, start_dim=0, end_dim=1)\n", 453 | " print(data.shape, labels.shape, bboxes.shape)\n", 454 | " data_np = data.permute(0, 2, 3, 1)\n", 455 | " data_np = data_np.cpu().numpy()\n", 456 | " data_np = data_np.astype(np.uint8)\n", 457 | " print(data.shape)" 458 | ] 459 | } 460 | ], 461 | "metadata": { 462 | "kernelspec": { 463 | "display_name": "medsam", 464 | "language": "python", 465 | "name": "python3" 466 | }, 467 | "language_info": { 468 | "codemirror_mode": { 469 | "name": "ipython", 470 | "version": 3 471 | }, 472 | "file_extension": ".py", 473 | "mimetype": "text/x-python", 474 | "name": "python", 475 | "nbconvert_exporter": "python", 476 | "pygments_lexer": "ipython3", 477 | "version": "3.10.13" 478 | } 479 | }, 480 | "nbformat": 4, 481 | "nbformat_minor": 2 482 | } 483 | -------------------------------------------------------------------------------- /test_set.txt: -------------------------------------------------------------------------------- 1 | defect/data/mat/plane/20200813_0005g.mat 2 | defect/data/mat/plane/20200923_0006g.mat 3 | defect/data/mat/plane/20200723_0037g.mat 4 | defect/data/mat/plane/20200813_0001g.mat 5 | defect/data/mat/plane/20200618_0117g.mat 6 | defect/data/mat/plane/20200723_0040g.mat 7 | defect/data/mat/plane/20200618_0115g.mat 8 | defect/data/mat/plane/20200723_0049g.mat 9 | defect/data/mat/plane/20200812_0012g.mat 10 | defect/data/mat/plane/166g.mat 11 | defect/data/mat/r_zone/036g.mat 12 | defect/data/mat/r_zone/029g.mat 13 | defect/data/mat/r_zone/035g.mat 14 | defect/data/mat/r_zone/012g.mat 15 | defect/data/mat/temperature/J18.mat 16 | defect/data/mat/temperature/NT.mat 17 | defect/data/mat/temperature/N3.mat 18 | defect/data/mat/temperature/N2.mat 19 | -------------------------------------------------------------------------------- /train_set.txt: -------------------------------------------------------------------------------- 1 | defect/data/mat/plane/20200923_0015g.mat 2 | defect/data/mat/plane/20200618_0113g.mat 3 | defect/data/mat/plane/20200618_0123g.mat 4 | defect/data/mat/plane/002g.mat 5 | defect/data/mat/plane/0_20200615_4.mat 6 | defect/data/mat/plane/20200812_0010g.mat 7 | defect/data/mat/plane/0602(3).mat 8 | defect/data/mat/plane/0602(4).mat 9 | defect/data/mat/plane/20200723_0050g.mat 10 | defect/data/mat/plane/0602(5).mat 11 | defect/data/mat/plane/20200618_0114g.mat 12 | defect/data/mat/plane/20200618_0111g.mat 13 | defect/data/mat/plane/20200618_0110g.mat 14 | defect/data/mat/plane/20200618_0128g.mat 15 | defect/data/mat/plane/20200812_0002g.mat 16 | defect/data/mat/plane/20200923_0016g.mat 17 | defect/data/mat/plane/20200618_0122g.mat 18 | defect/data/mat/plane/20200812_0006g.mat 19 | defect/data/mat/plane/2_200615_1.mat 20 | defect/data/mat/plane/20200923_0021g.mat 21 | defect/data/mat/plane/20200618_0121g.mat 22 | defect/data/mat/plane/20200723_0015g.mat 23 | defect/data/mat/plane/20200618_0118g.mat 24 | defect/data/mat/plane/20200618_0109g.mat 25 | defect/data/mat/plane/20200923_0007g.mat 26 | defect/data/mat/plane/20200812_0013g.mat 27 | defect/data/mat/plane/3_200615.mat 28 | defect/data/mat/plane/0_20200615_1.mat 29 | defect/data/mat/plane/20200923_0011g.mat 30 | defect/data/mat/plane/20200923_0003g.mat 31 | defect/data/mat/plane/20200923_0019g.mat 32 | defect/data/mat/plane/20200923_0005g.mat 33 | defect/data/mat/plane/0_20200615_2.mat 34 | defect/data/mat/plane/20200923_0020g.mat 35 | defect/data/mat/plane/20200618_0124g.mat 36 | defect/data/mat/plane/20200618_0119g.mat 37 | defect/data/mat/plane/20200923_0012g.mat 38 | defect/data/mat/plane/20200812_0003g.mat 39 | defect/data/mat/plane/0602(2).mat 40 | defect/data/mat/plane/20200618_0127g.mat 41 | defect/data/mat/plane/0_20200615_3.mat 42 | defect/data/mat/plane/046g.mat 43 | defect/data/mat/plane/20200722_0035g.mat 44 | defect/data/mat/plane/20200923_0008g.mat 45 | defect/data/mat/plane/20200923_0009g.mat 46 | defect/data/mat/plane/20200812_0011g.mat 47 | defect/data/mat/plane/20200618_0116g.mat 48 | defect/data/mat/plane/20200923_0004g.mat 49 | defect/data/mat/plane/20200923_0017g.mat 50 | defect/data/mat/plane/20200618_0129g.mat 51 | defect/data/mat/plane/20200812_0001g.mat 52 | defect/data/mat/plane/005g.mat 53 | defect/data/mat/plane/20200723_0038g.mat 54 | defect/data/mat/plane/20200618_0125g.mat 55 | defect/data/mat/plane/20200723_0016g.mat 56 | defect/data/mat/plane/20200923_0013g.mat 57 | defect/data/mat/plane/20200618_0120g.mat 58 | defect/data/mat/plane/20200923_0018g.mat 59 | defect/data/mat/plane/20200618_0112g.mat 60 | defect/data/mat/plane/20200812_0005g.mat 61 | defect/data/mat/plane/20200812_0007g.mat 62 | defect/data/mat/plane/20200618_0126g.mat 63 | defect/data/mat/plane/051g.mat 64 | defect/data/mat/plane/20200923_0002g.mat 65 | defect/data/mat/plane/182g.mat 66 | defect/data/mat/plane/20200923_0014g.mat 67 | defect/data/mat/plane/20200722_0031g.mat 68 | defect/data/mat/plane/2_200615_2.mat 69 | defect/data/mat/plane/20200923_0010g.mat 70 | defect/data/mat/r_zone/028g.mat 71 | defect/data/mat/r_zone/025g.mat 72 | defect/data/mat/r_zone/024g.mat 73 | defect/data/mat/r_zone/1_20200615_2.mat 74 | defect/data/mat/r_zone/172g.mat 75 | defect/data/mat/r_zone/042g.mat 76 | defect/data/mat/r_zone/039g.mat 77 | defect/data/mat/r_zone/094g.mat 78 | defect/data/mat/r_zone/023g.mat 79 | defect/data/mat/r_zone/040g.mat 80 | defect/data/mat/r_zone/019g.mat 81 | defect/data/mat/r_zone/178g.mat 82 | defect/data/mat/r_zone/1_20200615_1.mat 83 | defect/data/mat/r_zone/017g.mat 84 | defect/data/mat/r_zone/020g.mat 85 | defect/data/mat/r_zone/1_20200615_3.mat 86 | defect/data/mat/r_zone/009g.mat 87 | defect/data/mat/r_zone/018g.mat 88 | defect/data/mat/r_zone/008g.mat 89 | defect/data/mat/r_zone/031g.mat 90 | defect/data/mat/r_zone/038g.mat 91 | defect/data/mat/r_zone/037g.mat 92 | defect/data/mat/r_zone/027g.mat 93 | defect/data/mat/r_zone/026g.mat 94 | defect/data/mat/r_zone/006g.mat 95 | defect/data/mat/r_zone/022g.mat 96 | defect/data/mat/r_zone/171g.mat 97 | defect/data/mat/temperature/N4.mat 98 | defect/data/mat/temperature/1110t.mat 99 | defect/data/mat/temperature/201t.mat 100 | defect/data/mat/temperature/1132t.mat 101 | defect/data/mat/temperature/1055t.mat 102 | defect/data/mat/temperature/0923t.mat 103 | defect/data/mat/temperature/196t.mat 104 | defect/data/mat/temperature/200t.mat 105 | defect/data/mat/temperature/198t.mat 106 | defect/data/mat/temperature/1632t.mat 107 | defect/data/mat/temperature/F11.mat 108 | defect/data/mat/temperature/1700t.mat 109 | defect/data/mat/temperature/1526t.mat 110 | defect/data/mat/temperature/NF.mat 111 | defect/data/mat/temperature/1637t.mat 112 | defect/data/mat/temperature/195t.mat 113 | defect/data/mat/temperature/1112t.mat 114 | defect/data/mat/temperature/1050t.mat 115 | defect/data/mat/temperature/1058t.mat 116 | defect/data/mat/temperature/D1.mat 117 | defect/data/mat/temperature/F17.mat 118 | defect/data/mat/temperature/1103t.mat 119 | defect/data/mat/temperature/1634t.mat 120 | defect/data/mat/temperature/199t.mat 121 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | 2 | import scipy.io as sio 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | import matplotlib 6 | # matplotlib.use('Agg') 7 | 8 | def plot_3Ddata(data): 9 | #plot one mat data depended on values on time and locations 10 | from mpl_toolkits.mplot3d import Axes3D 11 | fig = plt.figure() 12 | ax = Axes3D(fig) 13 | X = [X for X in range(data.shape[0])] 14 | Y = [Y for Y in range(data.shape[1])] 15 | X, Y = np.meshgrid(X, Y) 16 | 17 | Z = data[X, Y, :] 18 | ax.plot_surface(X, Y, Z,cmap = 'rainbow') 19 | plt.axis('off') 20 | plt.savefig('defect/output/N1_3D.png') 21 | 22 | 23 | def plot_curve(mat_path): 24 | ''' 25 | :param mat_path: path to read a mat file 26 | :return: draw Temperature Change Curve for some points that you listed in this function 27 | ''' 28 | data_struct = sio.loadmat(mat_path) #if 195t.mat 29 | data = data_struct['data'] 30 | x = [x for x in range(data.shape[2])] 31 | y1 = data[197, 151, x] 32 | y2 = data[209, 149, x] 33 | y3 = data[212, 151, x] 34 | y4 = data[251, 149, x] 35 | y5 = data[251, 180, x] 36 | plt.figure() 37 | plt.plot(x, y1, color='dodgerblue', label='Line1') 38 | plt.plot(x, y2, color='orangered', label='Line2') 39 | plt.plot(x, y3, color='orange', label='Line3') 40 | plt.plot(x, y4, color='mediumorchid', label='Line4') 41 | plt.plot(x, y5, color='limegreen', label='Line5') 42 | 43 | plt.ylim((24, 36)) 44 | plt.xlim((0, 200)) 45 | y_ticks = np.linspace(24, 36, num=6) 46 | x_ticks = np.linspace(0, 200, num=5) 47 | plt.yticks(y_ticks) 48 | plt.xticks(x_ticks) 49 | plt.legend() 50 | plt.xlabel('Frame') 51 | plt.ylabel('Centigrade Temperature(℃)') 52 | plt.title('Temperature Change Curve') 53 | plt.show() 54 | plt.savefig('./Line.png') 55 | return 56 | 57 | def plot_curve(mat_path): 58 | ''' 59 | :param mat_path: path to read a mat file 60 | :return: draw Temperature Change Curve for some points that you listed in this function 61 | ''' 62 | data_struct = sio.loadmat(mat_path) #if 195t.mat 63 | data = data_struct['data'] 64 | x = [x for x in range(data.shape[2])] 65 | y1 = data[140, 51, x] / 10 66 | # y2 = data[209, 149, x] 67 | # y3 = data[212, 151, x] 68 | # y4 = data[251, 149, x] 69 | y5 = data[145, 57, x] / 10 70 | plt.figure() 71 | plt.plot(x, y1, color='dodgerblue', label='defect edge point') 72 | plt.plot(x, y5, color='purple', label='thermal diffusion point') 73 | 74 | # plt.plot(x, y1, color='dodgerblue', label='Line1') 75 | # plt.plot(x, y2, color='orangered', label='Line2') 76 | # plt.plot(x, y3, color='orange', label='Line3') 77 | # plt.plot(x, y4, color='mediumorchid', label='Line4') 78 | # plt.plot(x, y5, color='limegreen', label='Line5') 79 | 80 | # plt.ylim((24, 36)) 81 | plt.xlim((0, 180)) 82 | # y_ticks = np.linspace(24, 36, num=6) 83 | # x_ticks = np.linspace(0, 200, num=5) 84 | # plt.yticks(y_ticks) 85 | # plt.xticks(x_ticks) 86 | plt.legend() 87 | plt.xlabel('Frame') 88 | plt.ylabel('Centigrade Temperature(℃)') 89 | # plt.title('Temperature Change Curve') 90 | # plt.show() 91 | plt.savefig('defect/output/Line_2.png') 92 | return 93 | 94 | 95 | # plot_curve('defect/data/mat/temperature/N1.mat') 96 | file_path = 'defect/data/mat/temperature/N1.mat' 97 | plot_curve(file_path) 98 | # data_struct = sio.loadmat(file_path) 99 | # data = data_struct['data'] 100 | # t_len = data.shape[2] 101 | # print(t_len) 102 | # plt.imshow(data[:, :, 70], cmap='gray') 103 | # plt.show() 104 | # for i in range(t_len): 105 | # img = data[:, :, i] 106 | # plt.imshow(img, cmap='gray') 107 | # plt.axis('off') 108 | # plt.savefig('defect/output/N1/N1_{}.png'.format(i)) 109 | 110 | -------------------------------------------------------------------------------- /val_set.txt: -------------------------------------------------------------------------------- 1 | defect/data/mat/plane/20200723_0014g.mat 2 | defect/data/mat/plane/001g.mat 3 | defect/data/mat/plane/0602(1).mat 4 | defect/data/mat/plane/20200812_0004g.mat 5 | defect/data/mat/plane/20200813_0002g.mat 6 | defect/data/mat/plane/003g.mat 7 | defect/data/mat/plane/20200812_0009g.mat 8 | defect/data/mat/plane/20200923_0001g.mat 9 | defect/data/mat/r_zone/1_20200615_4.mat 10 | defect/data/mat/r_zone/041g.mat 11 | defect/data/mat/r_zone/007g.mat 12 | defect/data/mat/temperature/0921t.mat 13 | defect/data/mat/temperature/N1.mat 14 | defect/data/mat/temperature/N7.mat 15 | --------------------------------------------------------------------------------