Repository: mazurowski-lab/segment-anything-medical-evaluation Branch: main Commit: 2775b73f3165 Files: 13 Total size: 78.2 KB Directory structure: gitextract_s8s34ac6/ ├── .gitignore ├── CITATION.md ├── LICENSE ├── README.md ├── experimental_results_tables/ │ ├── Fig2-Performance of SAM for 5 modes of Use.csv │ ├── fig34-Table_for_focalclick_point_number_changes.csv │ ├── fig34-Table_for_ritm_point_number_changes.csv │ ├── fig34-Table_for_sam_oracle_point_number_changes.csv │ ├── fig34-Table_for_sam_point_number_changes.csv │ ├── fig34-Table_for_simpleclick_point_number_changes.csv │ └── fig4-Table_average_overalldatasets_point_numer_changes.csv ├── prompt_gen_and_exec_v1.py └── prompt_gen_and_exec_v2_allmode.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.pth *.py.swp run_record.py scores*/* .ipynb*/* log.txt results/* segment-anything/* segment_anything/* ritm_interactive_segmentation/* weights/* ================================================ FILE: CITATION.md ================================================ ```bib @article{mazurowski2023segment, title={Segment anything model for medical image analysis: an experimental study}, author={Mazurowski, Maciej A and Dong, Haoyu and Gu, Hanxue and Yang, Jichen and Konz, Nicholas and Zhang, Yixin}, journal={Medical Image Analysis}, volume={89}, pages={102918}, year={2023}, publisher={Elsevier} } ``` ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Segment Anything Model for Medical Image Analysis: an Experimental Study [![arXiv Paper](https://img.shields.io/badge/arXiv-2304.10517-orange.svg?style=flat)](https://arxiv.org/abs/2304.10517) #### By [Maciej Mazurowski](https://sites.duke.edu/mazurowski/), Haoyu Dong, Hanxue Gu, Jichen Yang, [Nicholas Konz](https://nickk124.github.io/) and Yixin Zhang. This is the official repository for our paper: [Segment Anything Model for Medical Image Analysis: an Experimental Study](https://www.sciencedirect.com/science/article/pii/S1361841523001780), recently published in Medical Image Analysis, where we evaluated Meta AI's Segment Anything Model (SAM) on many medical imaging datasets. ## Installation The code requires installing SAM's repository [Segment Anything (SAM)](https://github.com/facebookresearch/segment-anything.git). The model and dependencies can be found at SAM's repository, or you can install them with ``` git clone https://github.com/facebookresearch/segment-anything.git cd segment-anything; pip install -e . ``` Optionally, we have included code to evaluate [Reviving Iterative Training with Mask Guidance for Interactive Segmentation (RITM)](https://arxiv.org/abs/2102.06583) on the datasets. All you need to do to use our code for this is to clone their repository locally: ``` git clone https://github.com/yzluka/ritm_interactive_segmentation ``` ## Getting start First, download SAM's model checkpoint ``` wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth ``` If you want to run SAM (and competing methods) with iterative prompts, run the code with: ``` python3 prompt_gen_and_exec_v1.py --num-prompt XXX --model sam/ritm ``` where it will ask you to enter the dataset you wish to evaluate on. Optionally, to run RITM, you need to download its weights via: ``` wget https://github.com/saic-vul/ritm_interactive_segmentation/releases/download/v1.0/coco_lvis_h32_itermask.pth ``` If you want to run SAM with the 5 mode proposed in the paper, run the code with: ``` python3 prompt_gen_and_exec_v2_allmode.py ``` The 5 mode strategy includes (also shown in Figure 1, [![arXiv Paper](https://img.shields.io/badge/arXiv-2304.10517-orange.svg?style=flat)](https://arxiv.org/abs/2304.10517)): - 1 point at the center of the **largest** component - 1 point at the center of **each** component (put at most 3 points) - 1 box sharply around the **largest** component - 1 box sharply around **each** component (put at most 3 boxes) - 1 box covers **all** object ## Obtaining datasets from our paper TODO ## Adding custom datasets To evaluate your own dataset, you need to format the dataset as: ``` XXX: images: abc.png def.png ... masks: abc.png def.png ... ``` where images and masks should have the same name. ## News - 1 We have released our experimental results with detailed numerical numbers that were used to make figures in our paper; these tables are under the subfolder /experimental_results_tables. ## Citation If you find our work to be useful for your research, please cite our paper: ``` @article{mazurowski2023segment, title={Segment anything model for medical image analysis: an experimental study}, author={Mazurowski, Maciej A and Dong, Haoyu and Gu, Hanxue and Yang, Jichen and Konz, Nicholas and Zhang, Yixin}, journal={Medical Image Analysis}, volume={89}, pages={102918}, year={2023}, publisher={Elsevier} } ``` ================================================ FILE: experimental_results_tables/Fig2-Performance of SAM for 5 modes of Use.csv ================================================ ,Dataset_names,Mode 1: 1 point at largest object region,Mode 1 (oracle): 1 point at largest object region,Mode 2: 1 point at each object region,Mode 2 (oracle): 1 point at each object region,Mode 3: 1 box at largest object region,Mode 3 (oracle): 1 box at largest object region,Mode 4: 1 box at each object region,Mode 4 (oracle): 1 box at each object region,Mode 5: 1 box cover all objects,Mode 5 (oracle): 1 box cover all objects 0,CT-Organ: Lung,0.5040375609102761,0.7649961536318798,0.8399531292817298,0.8544587010504898,0.5619888040977155,0.5751254678667818,0.9118037681853222,0.9287611757965885,0.8442930189948117,0.9014606792388544 1,MRI-Spine: SP,0.7073228746669389,0.7096432977416823,0.7070476025992274,0.7095302007531917,0.9043487094339112,0.9119653011188062,0.9043487094339112,0.9119653011188062,0.9043487094339112,0.9119653011188062 2,CT-Spleen,0.8691847407254183,0.8772478846904421,0.8689422709715835,0.8768474552752175,0.8888784234966336,0.8960502031503226,0.8903440667420405,0.8977486661086032,0.888157727658361,0.896161751204274 3,Xray-Chest,0.488912549431233,0.7042973771124544,0.8255508338566884,0.8304664474345188,0.4845595757679478,0.5063367845139323,0.8808300821393182,0.9088518824912722,0.8380273852364888,0.8731804644274592 4,Xray-Hip: Ilium,0.8649546268769193,0.8775119614476239,0.8649960616662165,0.8776958070689208,0.8671305346236142,0.9498623353564899,0.8671305346236142,0.9498623353564899,0.8671305346236142,0.9498623353564899 5,CT-Liver,0.7168836341782948,0.7247227437045324,0.6897820158324605,0.6957833671590816,0.8339470767285759,0.8497763577430864,0.8454871317234407,0.8613084541832972,0.8244972081253991,0.841507070072933 6,CT-Organ: Kidney,0.48812141016765004,0.5137771486899364,0.5293984833999216,0.5306062550294209,0.528200113701847,0.53434510978159,0.8309711867869959,0.8391476064107741,0.45035835954319947,0.5159415625931333 7,CT-Organ: Bladder,0.5916728074734098,0.5916739116938898,0.5726033235071356,0.5726221823458707,0.7796024605322711,0.8196618408524342,0.7868766417826404,0.8290201142372928,0.7608618606538163,0.7958953774032693 8,Xray-Hip: Femur,0.6737930817054792,0.6845047915027754,0.6740167144857426,0.6847395375238928,0.7867385105826606,0.8058534761556695,0.7867375836188909,0.8058525491918997,0.7867528936815141,0.805867859254523 9,MRI-Heart,0.573143704527502,0.583662130445331,0.5775095522204375,0.5881684497095361,0.734538458869586,0.7669220221895826,0.7856222042741158,0.8176279421491547,0.6293998738464587,0.7048879357807536 10,CT-Organ: Liver,0.6572655994639135,0.657509567934053,0.6356032466211343,0.6358335035559992,0.7789995383252979,0.8760939976763359,0.7854910304887937,0.8823629020543077,0.7778099650265168,0.8718598005716134 11,US-Kidney,0.5531198274177759,0.6843526106476006,0.5569639972326419,0.6782384069681024,0.7717521567805573,0.8660795122175549,0.7722598559812998,0.8665291114759625,0.771622575672267,0.8660049668283785 12,CT-Colon,0.5241501535721865,0.5307969474576953,0.5250511629078818,0.5313687214826,0.6987196146385244,0.7210953366255343,0.7180784774651142,0.7408698698258476,0.6941207593677051,0.7208699936931542 13,CT-Organ: Bone,0.3870924726703019,0.537948309577858,0.5617453967171664,0.6075720277255027,0.5041121728098235,0.5591699598152509,0.7179510572142475,0.7861382489199804,0.4318603175075531,0.555966121641184 14,CT-Pancreas,0.5010115151433743,0.532924268069487,0.4980692434242409,0.5275509005159461,0.6761699849486295,0.7309784379842976,0.6952301940549994,0.7507288043045295,0.656463026747013,0.7209926850758989 15,MRI-Prostate,0.4716223475002687,0.5064347886055016,0.47104135778245915,0.5058923133864082,0.6843254450929145,0.7592649707750968,0.6848254784853673,0.7597124063727306,0.6834499338952817,0.7585286565598245 16,US-Breast,0.4712195546907309,0.6188008177558781,0.4735816855561947,0.6155673166376364,0.6410504608959803,0.7790617068901438,0.6410492376798388,0.7790555125298435,0.641132505088589,0.7790603773140136 17,MRI-Breast: Breast,0.34783472864351483,0.49746769921502504,0.35509528978447896,0.5012692482207185,0.5899735090916093,0.8347561389801192,0.6060022011834233,0.8527033667723514,0.5937453747396176,0.8437996657670627 18,PET-Wholebody,0.3426932634019096,0.3520103866842598,0.326432439783384,0.3328435709649819,0.5173322095044326,0.6173761929957494,0.562570259343904,0.6693695039761657,0.4643212895824232,0.5706536068818072 19,CT-Hepaticvessel,0.24518548187187356,0.24979626329976973,0.15671143905373192,0.1588021329729012,0.41687928725650014,0.46549963889514995,0.5419016843275795,0.5905769848091643,0.22333774646603485,0.25288755765451426 20,MRI-Brain: GD,0.3644789966578506,0.3729348517929812,0.3510795231936171,0.35839340193525926,0.4884324398981961,0.5417414636069973,0.5092892536422939,0.5646283585515393,0.47862140678629467,0.5270173818782171 21,MRI-Breast: FGT,0.2891343803228075,0.2985958075634497,0.22236704406413602,0.22236704406413602,0.34043336460000645,0.3467864983150635,0.49118344693603677,0.4944861199774202,0.2275343719139432,0.2550043716169522 22,US-Variantumor,0.3398076921862697,0.4573707014742938,0.34383180057461576,0.459333444052403,0.4633740285070635,0.7190842974900171,0.46523688156504733,0.7211977909933263,0.4639737355438073,0.7202034744723546 23,MRI-Brain: Core,0.2586909570158529,0.26170807541206154,0.23217271635685718,0.23415282948636373,0.416183998958719,0.45198666074925037,0.45756469370085256,0.5012820015283274,0.3333978894984103,0.35959147741753417 24,MRI-Brain: Edema,0.26076432589689647,0.26263997215298457,0.23422116339198454,0.23653493691978156,0.41239031745961985,0.46911298689380737,0.4501623828483823,0.5098458542001842,0.3605293097304758,0.41228754855160304 25,MRI-Spine: GM,0.11364871552061874,0.11364871552061874,0.11363235284637922,0.11363235284637922,0.2783918412038833,0.2877485790893153,0.2814359955162776,0.2910305845120911,0.2782344908831689,0.2874760097423331 26,US-Nerve,0.12620618960020696,0.14699303717568177,0.12688055807197968,0.1475196349207403,0.23287614303247803,0.543738210855488,0.23287614303247803,0.543738210855488,0.23287614303247803,0.543738210855488 27,US-Muscle,0.17728576808683244,0.3060046121522509,0.17914924775826055,0.30700876202985417,0.213416606828824,0.7724017740374894,0.2134182856841066,0.7724058881872616,0.21340544435737385,0.772385439486003 ================================================ FILE: experimental_results_tables/fig34-Table_for_focalclick_point_number_changes.csv ================================================ Num of points,MRI-Spine: GM,MRI-Spine: SC,MRI-Heart,MRI-Prostate,MRI-Brain: Core,MRI-Brain: Edema,MRI-Brain: GD,MRI-Breast: Breast,MRI-Breast: FGT,Xray-Chest,Xray-Hip: Ilium,Xray-Hip: Femur,US-Breast,US-Kidney,US-Nerve,US-Muscle,US-Variantumor,CT-Liver,CT-Organ: Liver,CT-Organ: Bladder,CT-Organ: Lung,CT-Organ: Kidney,CT-Organ: Bone,CT-Spleen,CT-Colon,CT-Pancreas,CT-Hepatovessel,PET-Wholebody 1,0.004025254,0.027928349,0.113857237,0.175645957,0.03986095,0.075069539,0.070572936,0.457802043,0.1895125,0.427554391,0.708503111,0.475881822,0.54081021,0.504198998,0.294929264,0.253375321,0.293808738,0.123678439,0.133033298,0.144042378,0.295752141,0.054716302,0.164837266,0.501527525,0.107550383,0.035529687,0.044232954,0.014385373 2,0.037371442,0.235181014,0.321559345,0.381946207,0.13743478,0.193391269,0.180658076,0.63880211,0.251257308,0.593945688,0.644230198,0.517541668,0.666885296,0.650718912,0.51178986,0.462183475,0.538999815,0.406077525,0.446821573,0.420565875,0.482557875,0.315196521,0.390300968,0.676238626,0.252521424,0.209702186,0.096300469,0.062876195 3,0.052412104,0.309360884,0.441770545,0.565831141,0.170330246,0.307568209,0.259887872,0.757668926,0.312243651,0.734368014,0.646724595,0.474139465,0.741157111,0.730287091,0.613760204,0.521225309,0.688531831,0.623366324,0.580700973,0.498732137,0.537030405,0.453235187,0.45147101,0.751979752,0.328490041,0.312865563,0.162824101,0.105695172 4,0.069027901,0.364489127,0.509469233,0.666893419,0.178108232,0.349356889,0.281664208,0.82831261,0.343710686,0.826458024,0.647969761,0.477270964,0.785818353,0.79611497,0.687293409,0.588059884,0.758672241,0.722269748,0.618459182,0.512337014,0.610735233,0.594804091,0.508565103,0.785288622,0.381492659,0.378995336,0.211513325,0.134701685 5,0.095872792,0.420259525,0.555479043,0.724153243,0.180289088,0.367112475,0.286844621,0.852578554,0.356086718,0.861720631,0.652154379,0.465022331,0.814209694,0.827644195,0.738322571,0.679083091,0.811598345,0.777060986,0.647416519,0.522419772,0.61735451,0.633075598,0.541030351,0.809464194,0.423001174,0.433595818,0.242501905,0.164536063 6,0.093518396,0.484263019,0.587125317,0.756102812,0.181137974,0.378856699,0.289923621,0.87569604,0.36313737,0.882275747,0.652971097,0.465608305,0.841888733,0.84342565,0.772921105,0.741472471,0.842666603,0.811999407,0.665484014,0.530768205,0.640768748,0.667851201,0.571398107,0.826310776,0.459383865,0.483031031,0.263238971,0.197997842 7,0.081247272,0.537294983,0.607956103,0.783828811,0.181238216,0.388258647,0.290885048,0.889782916,0.374244758,0.897437485,0.652454306,0.46276503,0.856383756,0.852037007,0.797975349,0.78428192,0.865014988,0.833933397,0.673719344,0.537998042,0.646140145,0.688874425,0.590814707,0.838715872,0.488143128,0.527070534,0.275937206,0.217199647 8,0.074974276,0.580202232,0.625476621,0.805202033,0.181652181,0.39319481,0.290999649,0.897631706,0.380314859,0.905907584,0.648484516,0.461930857,0.869769538,0.860097299,0.817469358,0.812780729,0.882941019,0.849989042,0.681943505,0.540466828,0.646468513,0.698536529,0.607636286,0.847639387,0.50355775,0.562378446,0.284445333,0.234339204 9,0.064372595,0.617293354,0.636814772,0.81873772,0.182106247,0.396528486,0.291566884,0.905754443,0.386745736,0.910290517,0.650224492,0.461491777,0.878295597,0.86621057,0.831896302,0.835481466,0.894598737,0.860873497,0.684290566,0.544097253,0.649310387,0.705362618,0.618825187,0.857405388,0.525595827,0.592320924,0.292000151,0.237753194 ================================================ FILE: experimental_results_tables/fig34-Table_for_ritm_point_number_changes.csv ================================================ Num of points,MRI-Spine: GM,MRI-Spine: SC,MRI-Heart,MRI-Prostate,MRI-Brain: Core,MRI-Brain: Edema,MRI-Brain: GD,MRI-Breast: Breast,MRI-Breast: FGT,Xray-Chest,Xray-Hip: Ilium,Xray-Hip: Femur,US-Breast,US-Kidney,US-Nerve,US-Muscle,US-Variantumor,CT-Liver,CT-Organ: Liver,CT-Organ: Bladder,CT-Organ: Lung,CT-Organ: Kidney,CT-Organ: Bone,CT-Spleen,CT-Colon,CT-Pancreas,CT-Hepatovessel,PET-Wholebody 1,0.009776697,0.064966565,0.031878882,0.056176431,0.025811666,0.136587317,0.178802495,0.401831015,0.127263521,0.017399807,0.473251112,0.247120046,0.227658544,0.186122093,0.029403263,0.210569491,0.203615625,0.086053854,0.115138964,0.337620822,0.194030643,0.084108101,0.147452457,0.036503824,0.022889909,0.016603625,0.01956532,0.014308346 2,0.068667712,0.347604107,0.249125446,0.1944822,0.210006062,0.282736389,0.264742438,0.546480434,0.207528461,0.189691616,0.646843857,0.24760928,0.533022288,0.241617361,0.162263621,0.300972757,0.485504215,0.382499465,0.456108544,0.514644855,0.323987645,0.222086953,0.271730279,0.476155671,0.241041065,0.148854411,0.09798397,0.182438889 3,0.154209721,0.746773816,0.55001828,0.340019777,0.236681708,0.361771356,0.309778051,0.699137796,0.251447991,0.477084273,0.688482455,0.247425019,0.663302256,0.44918303,0.27393084,0.39539574,0.600270934,0.618278285,0.543890146,0.577171719,0.42489841,0.311404133,0.369327315,0.806914013,0.489541566,0.462619064,0.279317908,0.378661778 4,0.21684836,0.892405101,0.676870639,0.501080067,0.242542209,0.394699765,0.319229324,0.804759199,0.28326333,0.699922214,0.69362893,0.247221362,0.750896218,0.713147694,0.359931088,0.445786427,0.704843719,0.738720174,0.592463057,0.598386179,0.480453971,0.372974286,0.445158454,0.887687304,0.60397035,0.613247552,0.368131341,0.469181529 5,0.265030949,0.924699564,0.744049431,0.629485554,0.242154976,0.412765858,0.321642999,0.865720902,0.337969453,0.809688804,0.695911906,0.247417335,0.810460731,0.811335838,0.428248214,0.643546062,0.776301034,0.809028787,0.623963797,0.610775455,0.49233884,0.435245423,0.49780431,0.909903533,0.691907605,0.704259619,0.427880846,0.523284619 6,0.293561637,0.936065097,0.781527363,0.730566168,0.241348761,0.425597662,0.322459763,0.898664187,0.396409222,0.864812026,0.696607856,0.247236398,0.8438083,0.862407998,0.535131673,0.707554486,0.827314184,0.857053478,0.642652954,0.619250626,0.498056709,0.475407592,0.521437292,0.923824123,0.753749049,0.768801437,0.470085891,0.553297118 7,0.339553131,0.941408456,0.809197888,0.798286357,0.239756967,0.432402415,0.322503837,0.91438182,0.419718229,0.891209937,0.69633196,0.247038081,0.872005705,0.900013577,0.635584238,0.754948718,0.866732198,0.887371351,0.650995682,0.625320391,0.505517236,0.500040239,0.531951126,0.932297287,0.788843536,0.809973718,0.502399452,0.56522908 8,0.397066238,0.94591996,0.82966044,0.839945735,0.239260708,0.437825163,0.321764581,0.927722872,0.43637957,0.905989902,0.696155826,0.246879107,0.893606449,0.92246739,0.72420605,0.786267115,0.89277063,0.907604086,0.658782923,0.629542152,0.508517805,0.515757562,0.539467557,0.938039262,0.817118128,0.838108995,0.52857919,0.581858984 9,0.412193052,0.949736334,0.845647817,0.868920434,0.238503004,0.441827948,0.32143899,0.93506419,0.456128524,0.917510153,0.695700578,0.246786427,0.908231648,0.932989257,0.77823478,0.813730829,0.909237121,0.920241409,0.663375988,0.63332767,0.510802672,0.528933515,0.545852604,0.941726217,0.83594024,0.857004672,0.546440041,0.594484696 ================================================ FILE: experimental_results_tables/fig34-Table_for_sam_oracle_point_number_changes.csv ================================================ Num of points,MRI-Spine: GM,MRI-Spine: SC,MRI-Heart,MRI-Prostate,MRI-Brain: Core,MRI-Brain: Edema,MRI-Brain: GD,MRI-Breast: Breast,MRI-Breast: FGT,Xray-Chest,Xray-Hip: Ilium,Xray-Hip: Femur,US-Breast,US-Kidney,US-Nerve,US-Muscle,US-Variantumor,CT-Liver,CT-Organ: Liver,CT-Organ: Bladder,CT-Organ: Lung,CT-Organ: Kidney,CT-Organ: Bone,CT-Spleen,CT-Colon,CT-Pancreas,CT-Hepatovessel,PET-Wholebody 1,0.113382997,0.709539584,0.584178611,0.505804327,0.262528162,0.263294527,0.372029612,0.345463166,0.281663085,0.703325319,0.877513169,0.684958183,0.619357476,0.683999403,0.146854203,0.306368149,0.457226535,0.724377986,0.657583236,0.591689781,0.756044629,0.500723179,0.537987563,0.877240458,0.530114986,0.532048976,0.247168962,0.35194111 2,0.119773235,0.744939523,0.623545727,0.572477487,0.260994068,0.285302196,0.381234603,0.6758047,0.282176727,0.757258261,0.866834801,0.693362246,0.662810424,0.724950099,0.21833731,0.299017412,0.505241469,0.763792433,0.747898034,0.651779335,0.777408925,0.541486882,0.647947162,0.884336822,0.576671729,0.584240611,0.261465026,0.373038835 3,0.131098987,0.77523773,0.661308732,0.628740032,0.259306542,0.307602154,0.385021197,0.739919723,0.346261046,0.805092075,0.842825267,0.685079064,0.688989909,0.737467933,0.316962782,0.336051904,0.547289692,0.805481587,0.784161253,0.693749368,0.78040897,0.580062795,0.639216857,0.889431374,0.615054616,0.632621648,0.269766316,0.397435305 4,0.144442728,0.807678556,0.692461091,0.667809023,0.261313032,0.32947915,0.389469012,0.768061551,0.392392058,0.829856068,0.822066657,0.687697527,0.701730236,0.744358425,0.385976748,0.374349785,0.583980264,0.824626046,0.806545088,0.711553102,0.793423502,0.564309555,0.648418237,0.890618712,0.639570084,0.671549271,0.299500696,0.426413642 5,0.161924661,0.845353502,0.712152915,0.699246907,0.265616183,0.341519375,0.391408173,0.777935351,0.407752693,0.83866496,0.811284519,0.677701683,0.724727862,0.75665265,0.437000192,0.403446497,0.62484449,0.830443839,0.812466614,0.724030866,0.82727534,0.551586181,0.653927076,0.890058509,0.658637482,0.698534343,0.324923983,0.455377389 6,0.167757436,0.864340548,0.723892649,0.71829192,0.269502834,0.344262467,0.392093148,0.793504565,0.422228556,0.854127414,0.804561141,0.675640243,0.724652364,0.769091511,0.47065314,0.416911855,0.652996022,0.839153688,0.816542629,0.728040748,0.837140309,0.551943499,0.660250726,0.893487344,0.672777098,0.716694442,0.343314906,0.473515701 7,0.173125413,0.874823174,0.732049981,0.736758716,0.272990221,0.344493113,0.390468607,0.803812689,0.436776109,0.854147837,0.792230632,0.67081475,0.735734646,0.775930539,0.493510469,0.422737161,0.673982636,0.845186259,0.814895267,0.731619981,0.836369617,0.542190014,0.664648044,0.896358762,0.683805082,0.731251292,0.355798264,0.489787023 8,0.183577247,0.88637115,0.741975592,0.746546349,0.275315608,0.342568224,0.387580426,0.803870108,0.458241272,0.854426157,0.778807153,0.661918896,0.7418308,0.783291581,0.5123567,0.421774649,0.687583437,0.851054856,0.812642294,0.732826391,0.835499331,0.544930103,0.667525656,0.897994785,0.697964294,0.740121265,0.364902054,0.502679934 9,0.190396554,0.897643678,0.753222393,0.755160615,0.276963077,0.340643781,0.383814678,0.787328514,0.460068245,0.854899836,0.769445566,0.655260741,0.745393265,0.784851411,0.526184921,0.416789598,0.698905152,0.85512019,0.812771086,0.732771328,0.833912249,0.549772844,0.669674454,0.900418815,0.701900522,0.74757714,0.3734387,0.511993308 ================================================ FILE: experimental_results_tables/fig34-Table_for_sam_point_number_changes.csv ================================================ Num of points,MRI-Spine: GM,MRI-Spine: SC,MRI-Heart,MRI-Prostate,MRI-Brain: Core,MRI-Brain: Edema,MRI-Brain: GD,MRI-Breast: Breast,MRI-Breast: FGT,Xray-Chest,Xray-Hip: Ilium,Xray-Hip: Femur,US-Breast,US-Kidney,US-Nerve,US-Muscle,US-Variantumor,CT-Liver,CT-Organ: Liver,CT-Organ: Bladder,CT-Organ: Lung,CT-Organ: Kidney,CT-Organ: Bone,CT-Spleen,CT-Colon,CT-Pancreas,CT-Hepatovessel,PET-Wholebody 1,0.113413977,0.707215114,0.573544732,0.471484832,0.259309921,0.261415985,0.363609559,0.345463166,0.281663085,0.488023392,0.864998503,0.674170642,0.469474787,0.554015436,0.12686366,0.178319396,0.339103869,0.716429507,0.657342781,0.591651548,0.489052597,0.475591875,0.387103928,0.869169392,0.52332346,0.500065368,0.242615495,0.342118366 2,0.119720765,0.741655333,0.613681693,0.554351424,0.259478487,0.26830508,0.370015985,0.6758047,0.282176727,0.815230861,0.866504315,0.682316191,0.556444339,0.655622439,0.194500321,0.226703197,0.457742115,0.75970764,0.748821195,0.651586276,0.836874513,0.53963711,0.590489785,0.874130197,0.568189091,0.571431809,0.259368123,0.367411142 3,0.130625675,0.775255575,0.641411695,0.612059803,0.25741975,0.276364913,0.369346785,0.739919723,0.346261046,0.842280125,0.82674459,0.657379542,0.600844455,0.679694542,0.297765281,0.262841288,0.509721222,0.794624795,0.779262286,0.676877934,0.844412218,0.577549233,0.637491155,0.865739229,0.595874492,0.618693877,0.267563546,0.388570816 4,0.140929047,0.808272794,0.66301319,0.654204918,0.258600237,0.281275707,0.362243969,0.768061551,0.392392058,0.843979369,0.823342113,0.671320349,0.621606089,0.677511842,0.364005482,0.322279245,0.557451932,0.809056451,0.795562604,0.703767267,0.810856815,0.559227768,0.661925752,0.840927741,0.612444449,0.65265008,0.296264734,0.41660268 5,0.157720416,0.843728096,0.646885278,0.686865409,0.261668629,0.28317044,0.356432685,0.777935351,0.407752693,0.849559747,0.806677077,0.694991678,0.616813718,0.661007505,0.407601655,0.408274878,0.600053731,0.819339927,0.804950482,0.712652346,0.799093396,0.539457276,0.665058131,0.84107665,0.625167238,0.676747083,0.321142828,0.441237441 6,0.165206027,0.858033034,0.663534131,0.700802231,0.264560409,0.280564741,0.348235591,0.793504565,0.422228556,0.846243434,0.791316816,0.685539102,0.614913468,0.636224163,0.438131547,0.469440695,0.613285541,0.824457076,0.808271998,0.716800062,0.803959442,0.532942121,0.671274585,0.857472527,0.63745082,0.691322993,0.339571283,0.462745665 7,0.170710257,0.877168916,0.672949965,0.718864864,0.266768938,0.27679308,0.339407058,0.803812689,0.436776109,0.838384875,0.765968568,0.672491214,0.607713174,0.628649917,0.455333945,0.50208456,0.629049662,0.833091981,0.807588849,0.719530307,0.794449968,0.51318959,0.674749771,0.86698824,0.653521569,0.707366518,0.35531408,0.476078195 8,0.179191533,0.88327955,0.703467031,0.72961057,0.267926433,0.271807464,0.332516189,0.803870108,0.458241272,0.830292781,0.748915342,0.645784546,0.600356357,0.615247279,0.470843702,0.501249768,0.640108247,0.84212085,0.802128089,0.722922894,0.781299554,0.497305569,0.675521227,0.875795185,0.669449242,0.716551435,0.366660119,0.489572866 9,0.184767742,0.895182706,0.717627308,0.735748131,0.268970293,0.268623994,0.326253536,0.787328514,0.460068245,0.82685649,0.74433395,0.63887511,0.5971176,0.60587999,0.482580404,0.478826268,0.640657611,0.848753094,0.803524566,0.718247447,0.754021906,0.496107277,0.677250297,0.884291823,0.670955895,0.725567878,0.375163374,0.501396368 ================================================ FILE: experimental_results_tables/fig34-Table_for_simpleclick_point_number_changes.csv ================================================ Num of points,MRI-Spine: GM,MRI-Spine: SC,MRI-Heart,MRI-Prostate,MRI-Brain: Core,MRI-Brain: Edema,MRI-Brain: GD,MRI-Breast: Breast,MRI-Breast: FGT,Xray-Chest,Xray-Hip: Ilium,Xray-Hip: Femur,US-Breast,US-Kidney,US-Nerve,US-Muscle,US-Variantumor,CT-Liver,CT-Organ: Liver,CT-Organ: Bladder,CT-Organ: Lung,CT-Organ: Kidney,CT-Organ: Bone,CT-Spleen,CT-Colon,CT-Pancreas,CT-Hepatovessel,PET-Wholebody 1,0.036917364,0.24013777,0.32813968,0.156812103,0.070737675,0.073833558,0.074938771,0.384828897,0.120320148,0.301886825,0.338930018,0.139755433,0.411324625,0.18485997,0.033587518,0.208382876,0.195995699,0.100781133,0.076410721,0.029517988,0.433976494,0.236869678,0.295704409,0.160617213,0.24045458,0.306115354,0.083992175,0.083024798 2,0.074315899,0.438909908,0.509669764,0.345343094,0.176221411,0.233113111,0.245429407,0.560587466,0.17447836,0.759687667,0.558547507,0.150257849,0.5822415,0.376086352,0.167600733,0.212095385,0.448687145,0.439668434,0.327814714,0.187063209,0.557230434,0.273434594,0.460289411,0.372857387,0.370298809,0.445682783,0.145724064,0.161255947 3,0.111411227,0.601302105,0.623511013,0.515320271,0.204729417,0.353292809,0.32309356,0.690514998,0.251615944,0.80702532,0.610816165,0.159405573,0.706460364,0.54632359,0.336670784,0.386810195,0.642558025,0.633103056,0.448854849,0.390500837,0.682851036,0.527287338,0.540123064,0.641800154,0.497363944,0.576087301,0.236427216,0.254708616 4,0.145873285,0.704035775,0.67408799,0.627307873,0.212863807,0.39269438,0.340823454,0.783280141,0.318457856,0.870576472,0.608568184,0.163149144,0.778123062,0.696258158,0.506423285,0.46089373,0.75090271,0.728375573,0.496894148,0.464911241,0.729745385,0.650564222,0.576397223,0.78523993,0.574217989,0.653446876,0.299489016,0.319963864 5,0.178057912,0.769424843,0.705193028,0.70631438,0.215447934,0.414631131,0.346224984,0.849528716,0.356345058,0.898726587,0.608904009,0.1635142,0.82435243,0.794294994,0.633361621,0.55701521,0.824221983,0.788878818,0.533639099,0.50066737,0.752613232,0.707905958,0.599769217,0.847601037,0.629973033,0.703643714,0.34292095,0.383902662 6,0.203528154,0.811252956,0.734680222,0.758216841,0.216681591,0.42858391,0.348861456,0.880011884,0.39786577,0.916010945,0.610065063,0.163581144,0.86052427,0.844360641,0.703675,0.638759001,0.860300985,0.829969299,0.561197229,0.514743443,0.756157771,0.735048871,0.619552816,0.881396382,0.672322956,0.742477014,0.376187727,0.44142806 7,0.225104011,0.838638255,0.755109759,0.796218067,0.217525453,0.439049634,0.351082259,0.901187755,0.423384017,0.924646584,0.610104041,0.163646219,0.879463806,0.871914095,0.752700252,0.699594984,0.886310947,0.856232022,0.575102865,0.523347094,0.755540253,0.751679337,0.636610438,0.895181059,0.706988799,0.770656071,0.401466605,0.483005371 8,0.249185049,0.862994056,0.773623544,0.820442908,0.217706336,0.44749058,0.352220971,0.915576452,0.434242601,0.929429077,0.610209747,0.163664286,0.892879742,0.892682051,0.788452519,0.748429821,0.902504666,0.875388962,0.584143075,0.528106312,0.758542131,0.766925149,0.653760277,0.90289883,0.727813526,0.791685955,0.420597816,0.519655867 9,0.262713832,0.880448639,0.787876751,0.842244168,0.217946907,0.454003211,0.352453584,0.92839559,0.447385722,0.935918749,0.611428802,0.163666056,0.904899678,0.905523481,0.816563445,0.785038715,0.914627466,0.88973461,0.590006894,0.532383632,0.755828556,0.777167205,0.664510904,0.912021661,0.74913438,0.809574149,0.438426564,0.552590644 ================================================ FILE: experimental_results_tables/fig4-Table_average_overalldatasets_point_numer_changes.csv ================================================ Num of points,SAM,SAM (oracle),RITM,SimpleClick,FocalClick 1,0.459519799,0.508014549,0.132232515,0.191030481,0.224022227 2,0.539567888,0.553004503,0.303443928,0.348378298,0.382966275 3,0.566878414,0.581487316,0.453819192,0.474998885,0.469059209 4,0.584634865,0.602130352,0.539908923,0.546913028,0.52206614 5,0.596895064,0.618017651,0.59617223,0.594181218,0.553567435 6,0.604929737,0.628477461,0.63195318,0.625265764,0.577543683 7,0.609457031,0.634867725,0.656464736,0.646124645,0.593629751 8,0.611501257,0.63986344,0.675259442,0.661830439,0.605229646 9,0.611249208,0.642368666,0.687500386,0.6743755,0.614151596 ================================================ FILE: prompt_gen_and_exec_v1.py ================================================ from segment_anything import SamPredictor, sam_model_registry from PIL import Image, ImageDraw, ImageOps from shapely.geometry import LineString, MultiLineString, Polygon, Point, GeometryCollection from skimage.morphology import medial_axis from scipy.optimize import minimize_scalar from scipy.ndimage import binary_dilation from skimage.measure import label from sklearn.cluster import KMeans import argparse import os import cv2 import json import imutils import random import matplotlib.pyplot as plt import numpy as np # Fix randomness in prompt selection np.random.seed(1) import sys sys.path.append('FocalClick') #sys.path.append('ritm_interactive_segmentation') #sys.path.append('CFR-ICL-Interactive-Segmentation') from isegm.inference.clicker import Click from isegm.inference import utils as is_utils from isegm.inference.predictors import get_predictor as is_get_predictor from isegm.inference.evaluation import evaluate_sample_onepass as is_evaluate_sample_onepass #This is a helper function that should not be called directly def _find_closest(centroid, pos_points): dist_squared = np.sum((pos_points - centroid)**2, axis=1) point_idx = np.argmin(dist_squared) return pos_points[point_idx] def IOU(pm, gt): a = np.sum(np.bitwise_and(pm, gt)) b = np.sum(pm) + np.sum(gt) - a #+ 1e-8 if b == 0: return -1 else: return a / b def IOUMulti(y_pred, y): score = 0 numLabels = np.max(y) if np.max(y) == 1: score = IOU(y_pred, y) return score else: count = 1 for index in range(1,numLabels+1): curr_score = IOU(y_pred[y==index], y[y==index]) print(index, curr_score) if curr_score != -1: score += curr_score count += 1 return score / (count - 1) # taking average #################################################### # input: raw_msk # A mask should containing no 'void' class. # Binary mask should have value {0,1} but not {0,255} # output: # A list of region profiles; Each profile takes the form # {'loc':[x0,y0,x1,y1], 'cls': cls} # 'loc' is a list with 4 elements ; 'cls' is object class as integer #################################################### def MaskToBoxes(mask): label_msk, region_ids = label(mask, connectivity=2, return_num=True) bbox_profiles = [] for region_id in range(1, region_ids+1): #find coordinates of points in the region row,col = np.argwhere(label_msk == region_id).T #find class of the region cls = mask[row[0],col[0]] # find the four corner coordinates y0,x0 = row.min(),col.min() y1,x1 = row.max(),col.max() bbox_profiles.append({'loc':[x0,y0,x1,y1], 'cls':cls}) return bbox_profiles #################################################### # input: raw_msk # A mask should containing no 'void' class. # Binary mask should have value {0,1} but not {0,255} # input: N # The number of points to apply on each object/connected region # output: # A list of region profiles. Each region profile takes the form # {'loc':np.array([[x0,y0],[x1,y1],[x_N,y_N]]), 'cls': cls} # 'loc' is 2D array with shape (N, 2); 'cls' is object class as integer #################################################### def Mask2Points(raw_msk, N=1): label_msk, region_ids = label(raw_msk, connectivity=2,return_num = True) point_profiles = [] for region_id in range(1, region_ids+1): #find coordinates of points in the region pos_points = np.argwhere(label_msk == region_id) # clean some region that is abnormally small r = len(pos_points) / len(raw_msk.flatten()) if r < 1e-4: continue print('mask ratio', r) #if len(pos_points) < len(raw_msk.flatten())*0.001: # continue #get the skeleton binary_msk = np.where(label_msk == region_id,1,0) skeleton_msk = medial_axis(binary_msk).astype(np.uint8) skeleton_points = np.argwhere(skeleton_msk>0) # Cluster and assign the object skeleton into N sections #kmean = KMeans(n_clusters=N,n_init=3, algorithm='lloyd' if N == 1 else 'elkan').fit(skeleton_points) kmean = KMeans(n_clusters=N,n_init=3, algorithm='auto').fit(skeleton_points) cluster_assigned = np.zeros(len(skeleton_points)) if N == 1 else kmean.predict(skeleton_points) centroids = kmean.cluster_centers_ # pick a skeleton point closest to the centroid from each cluster selected_points = np.zeros((N,2)) for cluster_id, centroid in zip(range(N),centroids): points_in_cluster = skeleton_points[cluster_assigned==cluster_id] selected_points[cluster_id] = _find_closest(centroid,points_in_cluster) #find class of the region cls = raw_msk[pos_points[0,0],pos_points[0,1]] point_profiles.append({'loc':np.concatenate((selected_points[:,1:],selected_points[:,0:1]),axis=1), 'cls':cls}) #TODO: double check if > 1 regions found break return point_profiles if __name__ == '__main__': parser = argparse.ArgumentParser(description="SAG segmentor for medical images") parser.add_argument("--num-prompt", default=1, type=int, help="number of prompts to include, negative number means using box as prompts") parser.add_argument("--class-type", default="b", type=str, help="binary or multi class, choose b or m") parser.add_argument("--model-path", default="./", type=str, help="the path of the model saved") parser.add_argument("--init-path", default="./", type=str, help="the path of the dataset") parser.add_argument("--model", default="sam", type=str, help="the model to use as predictor") parser.add_argument("--oracle", default=False, type=bool, help="whether eval in the oracle mode, where best prediction is selected based on GT") parser.add_argument("--result-image",default="./results",type=str, help="the path to save segmented results") parser.add_argument("--result-score",default="./scores",type=str, help="the path to save result metrics") args = parser.parse_args() # Set up model if args.model == 'sam': sam = sam_model_registry["default"](checkpoint=os.path.join(args.model_path, "sam_vit_h_4b8939.pth")) sam.to('cuda') predictor = SamPredictor(sam) # NOTE: manual change sys path when importing library elif args.model == 'ritm': model = is_utils.load_is_model(os.path.join(args.model_path, "coco_lvis_h32_itermask.pth"), "cuda") predictor = is_get_predictor(model, "NoBRS", "cuda") elif args.model == 'sc': model = is_utils.load_is_model(os.path.join(args.model_path, "cocolvis_icl_vit_huge.pth"), "cuda", eval_ritm=False) zoom_in_params = { 'skip_clicks': -1, 'target_size': (448, 448) } predictor_params = { 'cascade_step': 4 + 1, 'cascade_adaptive': True, 'cascade_clicks': 1 } predictor = is_get_predictor(model, "NoBRS", "cuda", prob_thresh=0.49, \ predictor_params=predictor_params, zoom_in_params=zoom_in_params) elif args.model == 'fc': model = is_utils.load_is_model(os.path.join(args.model_path, "segformerB3_S2_comb.pth"), "cuda") predictor = is_get_predictor(model, "NoBRS", "cuda", prob_thresh=0.49) print('Dataset you can choose among: chest, gmsc_sp, gmsc_gm, breast_b, breast_f, heart, usbreast, liver, prostate, nodule, brats, all') # Set up dataset dataset = input("Type of input: ") if dataset == 'all': dataset_list = ['busi', 'breast_b', 'breast_d', 'chest', 'gmsc_sp', 'gmsc_gm', 'heart', 'liver', 'petwhole', 'prostate', 'brats_3m', 'xrayhip', \ 'ctliver', 'ctorgan', 'ctcolon', 'cthepaticvessel', 'ctpancreas', 'ctspleen', 'usmuscle', 'usnerve', 'usovariantumor'] else: dataset_list = [dataset] for dataset in dataset_list: print('curr dataset', dataset) num_class = 1 if 'gmsc' in dataset: input_img_dir = os.path.join(args.init_path, 'sa_gmsc/images') input_seg_dir = os.path.join(args.init_path, 'sa_gmsc/masks') elif 'breast' in dataset: input_img_dir = os.path.join(args.init_path, "sa_dbc-2D/imgs") if dataset == 'breast_b': input_seg_dir = os.path.join(args.init_path, "sa_dbc-2D/masks_breast") else: input_seg_dir = os.path.join(args.init_path, "sa_dbc-2D/masks_dense-tissue") else: input_img_dir = os.path.join(args.init_path, 'sa_%s/images' % dataset) input_seg_dir = os.path.join(args.init_path, 'sa_%s/masks' % dataset) if dataset == 'brats_3m': num_class = 3 if dataset == 'xrayhip': num_class = 2 if dataset == 'ctorgan': num_class = 5 # target is a variable only used by GMSC if dataset == 'gmsc_sp': target = 'sp' if dataset == 'gmsc_gm': target = 'gm' print(input_img_dir) print(input_seg_dir) if args.num_prompt<0: save_path = os.path.join('results',dataset,'box') elif args.oracle: save_path = os.path.join('results',dataset,'oracle') else: save_path = os.path.join('results',dataset,'point') # Running dc_log, names = [], [] mask_list = os.listdir(input_seg_dir) print('# of dataset', len(mask_list)) # VIS: now VIS function is separted into another file. Only provide mask if needed vis = False # Change to [name1, name2, ...] if only need to run on a few samples im_list = None#['CHNCXR_0061_0_mask.png'] for im_idx, im_name in enumerate(mask_list): # Skip non-selected images if specified print(im_name) if im_list is not None: if im_name not in im_list: continue # GMSC: All masks in the same dir, separated by names if 'gmsc' in dataset: if target not in im_name: continue if 'DS_Store' in im_name: continue # Read image and mask try: input_mask = cv2.imread(os.path.join(input_seg_dir, im_name), 0) except: print('Cannot read mask', im_name) continue if np.max(input_mask) == 0: print('Empty mask') print('*****') continue # In multi-class setting, we assume classes are labeled 0,1,2,3... # BraTS has label 1,2,4 if 'brats' in dataset: input_mask[input_mask == 4] = 3 # In binary-class setting, some masks are encoded as 0, 255 if np.max(input_mask) == 255: input_mask = np.uint8(input_mask / input_mask.max()) # Chest and GMSC: name inconsistentcy if 'chest' in dataset: im_name = im_name.replace('_mask', '') if 'gmsc' in dataset: im_name = im_name.replace('mask', 'image').replace(target+'-', '') try: input_image = Image.open(os.path.join(input_img_dir, im_name)).convert("RGB") except: print('Cannot read image', im_name) continue input_array = np.array(input_image) input_array = np.uint8(input_array / np.max(input_array) * 255) print('Number of labels', np.max(input_mask)) print('Image maximum', np.max(input_array)) # if we want to do multi-class classification # else, we combine all the masks as the same class #if args.class_type == 'm': if num_class > 1: #mask_one_hot = (np.arange(1, input_mask.max()+1) == input_mask[...,None]).astype(int) mask_one_hot = (np.arange(1, num_class+1) == input_mask[...,None]).astype(int) else: mask_one_hot = np.array(input_mask > 0,dtype=int) if len(mask_one_hot.shape) < 3: mask_one_hot = mask_one_hot[:,:,np.newaxis] # height*depth*1, to consistent with multi-class setting # Start prediction for each class if args.model == 'sam': predictor.set_image(input_array) elif args.model == 'ritm': predictor.set_input_image(input_array) # Mask has to be float pre_mask = np.zeros_like(mask_one_hot, dtype=float) dc_class_tmp = [] for cls in range(num_class): dc_prompt_tmp = [] print('Predicting class %s' % cls) # segment current class as binary segmentation try: mask_cls = np.uint8(mask_one_hot[:,:,cls]) except: print('Mask do not contain this class, skipped') if num_class == 1: dc_class_tmp.append(np.nan) else: dc_class_tmp.append([np.nan] * args.num_prompt) continue if np.sum(mask_cls) == 0: print('Empty single cls, skipped') #dc_class_tmp.append(np.nan) if num_class == 1: dc_class_tmp.append(np.nan) else: dc_class_tmp.append([np.nan] * args.num_prompt) continue # ------ Generate prompt by SAM's eval protocol -------# preds_mask_full, prompts_full,gt_mask_full,input_full = [], [],[],[] # Calculates the distance to the closest zero pixel for each pixel of the source image. # Ref from RITM: https://github.com/SamsungLabs/ritm_interactive_segmentation/blob/aa3bb52a77129e477599b5edfd041535bc67b259/isegm/data/points_sampler.py padded_mask = np.pad(mask_cls, ((1, 1), (1, 1)), 'constant') dist_img = cv2.distanceTransform(padded_mask, distanceType=cv2.DIST_L2, maskSize=5).astype(np.float32)[1:-1, 1:-1] # NOTE: numpy and opencv have inverse definition of row and column # NOTE: SAM and opencv have the same definition cY, cX = np.where(dist_img==dist_img.max()) # NOTE: random seems to change DC by +/-1e-4 # Random sample one point with largest distance random_idx = np.random.randint(0, len(cX)) cX, cY = int(cX[random_idx]), int(cY[random_idx]) # First point: farthest from the object boundary pc = [(cX,cY)] pl = [1] if args.model == 'sam': preds, _, _ = predictor.predict(point_coords=np.array(pc), point_labels=np.array(pl), return_logits=True) elif args.model == 'ritm': # RITM returns mask, mask_prob, iou click_list = [Click(is_positive=True, coords=(cY, cX), indx = 0)] _, preds = is_evaluate_sample_onepass(predictor, click_list) # RITM uses 0.49 as threshold. Substract it to let 0 be the threshold preds = preds - 0.49 preds = preds[None,:,:].repeat(3,0) elif args.model == 'sc' or args.model == 'fc': # SimpleClick click_list = [Click(is_positive=True, coords=(cY, cX), indx = 0)] _, preds_prob, _ = is_evaluate_sample_onepass(input_array, mask_cls, predictor, click_list, \ pred_thr=0.49, iterative=False) preds = preds_prob - 0.49 preds = preds[None,:,:].repeat(3,0) #elif args.model == 'fc': # click_list = [Click(is_positive=True, coords=(cY, cX), indx = 0)] # _, preds_prob, _ = is_evaluate_sample_onepass(input_array, mask_cls, predictor, click_list, \ # pred_thr=0.49, iterative=False) # preds = preds_prob - 0.49 # if logit < 0, it is more like a background preds[preds < 0] = 0 preds = preds.transpose((1,2,0)) if args.oracle: max_slice, max_dc = -1, 0 for mask_slice in range(preds.shape[-1]): preds_mask_single = np.array(preds[:,:,mask_slice]>0,dtype=int) dc = IOUMulti(preds_mask_single, mask_cls) if dc > max_dc: max_dc = dc max_slice = mask_slice print(mask_slice, dc) preds_mask_single = np.array(preds[:,:,max_slice]>0,dtype=int) else: preds_mask_single = np.array(preds[:,:,0]>0,dtype=int) dc = IOUMulti(preds_mask_single, mask_cls) dc_prompt_tmp.append(dc) preds_mask_full.append(np.expand_dims(preds, 0)) gt_mask_full.append(np.expand_dims(mask_cls, 0)) input_full.append(input_array) prompts_full.append((cX,cY,1)) # Subsequent point: farthest from the boundary of the error region for idx_p in range(args.num_prompt - 1): error_mask = np.uint8(np.bitwise_xor(mask_cls, preds_mask_single)) padded_mask = np.pad(error_mask, ((1, 1), (1, 1)), 'constant') dist_img = cv2.distanceTransform(padded_mask, distanceType=cv2.DIST_L2, maskSize=5).astype(np.float32)[1:-1, 1:-1] cY, cX = np.where(dist_img==dist_img.max()) random_idx = np.random.randint(0, len(cX)) cX, cY = int(cX[random_idx]), int(cY[random_idx]) pc.append((cX, cY)) if np.sum(input_mask[cY][cX]) == 0: pl.append(0) prompts_full.append((cX,cY,0)) else: pl.append(1) prompts_full.append((cX,cY,1)) if args.model == 'sam': preds, _, _ = predictor.predict(point_coords=np.array(pc), point_labels=np.array(pl), return_logits=True) elif args.model == 'ritm': curr_click = Click(is_positive=pl[-1], coords=(cY, cX), indx = idx_p+1) click_list.append(curr_click) _, preds = is_evaluate_sample_onepass(predictor, click_list) preds = preds - 0.49 preds = preds[None,:,:].repeat(3,0) elif args.model == 'sc' or args.model == 'fc': curr_click = Click(is_positive=pl[-1], coords=(cY, cX), indx = idx_p+1) click_list.append(curr_click) # SimpleClick _, preds_prob, _ = is_evaluate_sample_onepass(input_array, mask_cls, predictor, click_list, \ pred_thr=0.49, iterative=False) preds = preds_prob - 0.49 preds = preds[None,:,:].repeat(3,0) # if logit < 0, it is more like a background preds[preds < 0] = 0 preds = preds.transpose((1,2,0)) if args.oracle: max_slice, max_dc = -1, 0 for mask_slice in range(preds.shape[-1]): preds_mask_single = np.array(preds[:,:,mask_slice]>0,dtype=int) dc = IOUMulti(preds_mask_single, mask_cls) if dc > max_dc: max_dc = dc max_slice = mask_slice preds_mask_single = np.array(preds[:,:,max_slice]>0,dtype=int) else: preds_mask_single = np.array(preds[:,:,0]>0,dtype=int) dc = IOUMulti(preds_mask_single, mask_cls) dc_prompt_tmp.append(dc) preds_mask_full.append(np.expand_dims(preds, 0)) gt_mask_full.append(np.expand_dims(mask_cls, 0)) input_full.append(input_array) print('Final prompts', pc, pl) # assgin final mask for this class to it print('Predicted DC', dc) dc_class_tmp.append(dc_prompt_tmp) pre_mask[:,:,cls] = preds[:,:,0] dc_log.append(dc_class_tmp) names.append(im_name) print('****') # VIS mode only saves mask and prompt information if vis: # Final shape: N*H*W*3 # N = number of predictions. 1 if box prompt, otherwise number of prompts # H,W = size of mask # 3 = number of outputs per prediction. SAM returns 3 outpus per prompt. # If no oracle mode, select 0 # If oracle mode, select maximum slice. # You can do that later, or use variable "max_slice" preds_mask_full = np.concatenate(preds_mask_full) gt_mask_full = np.concatenate(gt_mask_full) input_full = np.concatenate(input_full) # If box: N*4, N=number of boxes, 4=box coordinate in XYXY format # If prompts:N*3, N=number of prmts, 3=cX, cY, pos/neg prompts_full = np.array(prompts_full) print(preds_mask_full.shape) # TODO: replace with desired storage place if not os.path.exists(save_path): os.mkdir(save_path) np.save(save_path+'/%s_pred.npy' % im_name[:-4], preds_mask_full) np.save(save_path+'/%s_prompt.npy' % im_name[:-4], prompts_full) np.save(save_path+'/%s_gt.npy' % im_name[:-4], gt_mask_full) np.save(save_path+'/%s_input.npy' % im_name[:-4], input_full) if not vis: dc_log = np.array(dc_log) print(dc_log.shape) print(np.nanmean(dc_log, axis=0)) print(np.nanmean(dc_log)) version = 'sam_prompt' #version = 'sam_oracle' #version = 'sam_box' if args.model == 'sc': version = 'simpleclick' if args.model == 'fc': version = 'focalclick' if args.model == 'ritm': version = 'ritm' json.dump(names, open('scores/v1_rerun/%s_binary_names_%s.json' % (version, dataset), 'w+')) np.save('scores/v1_rerun/%s_binary_score_%s.npy' % (version, dataset), dc_log) ================================================ FILE: prompt_gen_and_exec_v2_allmode.py ================================================ from segment_anything import SamPredictor, sam_model_registry from PIL import Image, ImageDraw, ImageOps from shapely.geometry import LineString, MultiLineString, Polygon, Point, GeometryCollection from skimage.morphology import medial_axis from scipy.optimize import minimize_scalar from scipy.ndimage import binary_dilation from skimage.measure import label from sklearn.cluster import KMeans import argparse import os import cv2 import json import imutils import random import matplotlib.pyplot as plt import numpy as np # Fix randomness in prompt selection np.random.seed(1) #This is a helper function that should not be called directly def _find_closest(centroid, pos_points): dist_squared = np.sum((pos_points - centroid)**2, axis=1) point_idx = np.argmin(dist_squared) return pos_points[point_idx] def IOU(pm, gt): a = np.sum(np.bitwise_and(pm, gt)) b = np.sum(pm) + np.sum(gt) - a #+ 1e-8 if b == 0: return -1 else: return a / b def IOUMulti(y_pred, y): score = 0 numLabels = np.max(y) if np.max(y) == 1: score = IOU(y_pred, y) return score else: count = 1 for index in range(1,numLabels+1): curr_score = IOU(y_pred[y==index], y[y==index]) print(index, curr_score) if curr_score != -1: score += curr_score count += 1 return score / (count - 1) # taking average #################################################### # input: raw_msk # A mask should containing no 'void' class. # Binary mask should have value {0,1} but not {0,255} # output: # A list of region profiles; Each profile takes the form # {'loc':[x0,y0,x1,y1], 'cls': cls} # 'loc' is a list with 4 elements ; 'cls' is object class as integer #################################################### def MaskToBoxSimple(mask): mask = mask.squeeze() #find coordinates of points in the region row, col = np.argwhere(mask).T # find the four corner coordinates y0,x0 = row.min(),col.min() y1,x1 = row.max(),col.max() return [x0,y0,x1,y1] if __name__ == '__main__': parser = argparse.ArgumentParser(description="SAG segmentor for medical images") parser.add_argument("--num-prompt", default=1, type=int, help="number of prompts to include, negative number means using box as prompts") parser.add_argument("--class-type", default="b", type=str, help="binary or multi class, choose b or m") parser.add_argument("--model-path", default="./", type=str, help="the path of the model saved") parser.add_argument("--init-path", default="./", type=str, help="the path of the dataset") parser.add_argument("--model", default="sam", type=str, help="the model to use as predictor") parser.add_argument("--oracle", default=False, type=bool, help="whether eval in the oracle mode, where best prediction is selected based on GT") parser.add_argument("--result-image",default="./results",type=str, help="the path to save segmented results") parser.add_argument("--result-score",default="./scores",type=str, help="the path to save result metrics") args = parser.parse_args() # Set up model sam = sam_model_registry["default"](checkpoint=os.path.join(args.model_path, "sam_vit_h_4b8939.pth")) sam.to('cuda') predictor = SamPredictor(sam) # Set up dataset dataset = input("Type of input: ") if dataset == 'all': # all dataset_list = ['busi', 'breast_b', 'breast_d', 'chest', 'gmsc_sp', 'gmsc_gm', 'heart', 'liver', 'petwhole', 'prostate', 'brats_3m', 'xrayhip', \ 'ctliver', 'ctorgan', 'ctcolon', 'cthepaticvessel', 'ctpancreas', 'ctspleen', 'usmuscle', 'usnerve', 'usovariantumor'] else: dataset_list = [dataset] for dataset in dataset_list: num_class = 1 if 'gmsc' in dataset: input_img_dir = os.path.join(args.init_path, 'sa_gmsc/images') input_seg_dir = os.path.join(args.init_path, 'sa_gmsc/masks') elif 'breast' in dataset: input_img_dir = "../sa_dbc-2D/imgs" if dataset == 'breast_b': input_seg_dir = "../sa_dbc-2D/masks_breast" else: input_seg_dir = "../sa_dbc-2D/masks_dense-tissue" else: input_img_dir = os.path.join(args.init_path, 'sa_%s/images' % dataset) input_seg_dir = os.path.join(args.init_path, 'sa_%s/masks' % dataset) # Handle dataset with multi-class if dataset == 'brats_3m': num_class = 3 if dataset == 'xrayhip': num_class = 2 if dataset == 'ctorgan': num_class = 5 # target is a variable only used by GMSC if dataset == 'gmsc_sp': target = 'sp' if dataset == 'gmsc_gm': target = 'gm' print(input_img_dir) print(input_seg_dir) # Running dc_log, names = [], [] mask_list = os.listdir(input_seg_dir) print('# of dataset', len(mask_list)) # VIS: now VIS function is separted into another file. Only provide mask if neede vis = False # Change to [name1, name2, ...] if only need to run on a few samples im_list = None#['CHNCXR_0061_0_mask.png'] for im_idx, im_name in enumerate(mask_list): # Skip non-selected images if specified print(im_name) if im_list is not None: if im_name not in im_list: continue # GMSC: All masks in the same dir, separated by names if 'gmsc' in dataset: if target not in im_name: continue if 'DS_Store' in im_name: continue # Read image and mask try: input_mask = cv2.imread(os.path.join(input_seg_dir, im_name), 0) except: print('Cannot read mask', im_name) continue if np.max(input_mask) == 0: print('Empty mask') print('*****') continue # In multi-class setting, we assume classes are labeled 0,1,2,3... # BraTS has label 1,2,4 if 'brats' in dataset: input_mask[input_mask == 4] = 3 # In binary-class setting, some masks are encoded as 0, 255 if np.max(input_mask) == 255: input_mask = np.uint8(input_mask / input_mask.max()) # Chest and GMSC: name inconsistentcy if 'chest' in dataset: im_name = im_name.replace('_mask', '') if 'gmsc' in dataset: im_name = im_name.replace('mask', 'image').replace(target+'-', '') try: input_image = Image.open(os.path.join(input_img_dir, im_name)).convert("RGB") except: print('Cannot read image', im_name) continue input_array = np.array(input_image) input_array = np.uint8(input_array / np.max(input_array) * 255) print('Number of labels', np.max(input_mask)) print('Image maximum', np.max(input_array)) # if we want to do multi-class classification # else, we combine all the masks as the same class #if args.class_type == 'm': if num_class > 1: #mask_one_hot = (np.arange(1, input_mask.max()+1) == input_mask[...,None]).astype(int) mask_one_hot = (np.arange(1, num_class+1) == input_mask[...,None]).astype(int) else: mask_one_hot = np.array(input_mask > 0,dtype=int) if len(mask_one_hot.shape) < 3: mask_one_hot = mask_one_hot[:,:,np.newaxis] # height*depth*1, to consistent with multi-class setting # Start prediction for each class predictor.set_image(input_array) # Mask has to be float dc_class_tmp = [] for cls in range(num_class): dc_prompt_tmp = [] # Cls = 2 means to predict mask with label 3 # But BraTS use 1,2,4 to label differet classes #if cls == 2 and 'brats' in dataset: # cls += 1 print('Predicting class %s' % cls) # segment current class as binary segmentation try: mask_cls = np.uint8(mask_one_hot[:,:,cls]) except: print('Mask do not contain this class, skipped') if num_class == 1: dc_class_tmp.append(np.nan) else: # Fixed with 5 modes for now dc_class_tmp.append([np.nan] * 5) continue if np.sum(mask_cls) == 0: print('Empty single cls, skipped') #dc_class_tmp.append(np.nan) if num_class == 1: dc_class_tmp.append(np.nan) else: dc_class_tmp.append([np.nan] * 5) continue # ------ Generate prompt by our definition -------- # preds_mask_full, prompts_full = [], [] # Find all disconnected regions label_msk, region_ids = label(mask_cls, connectivity=2, return_num=True) print('num of regions found', region_ids) ratio_list, regionid_list = [], [] for region_id in range(1, region_ids+1): #find coordinates of points in the region binary_msk = np.where(label_msk==region_id, 1, 0) # clean some region that is abnormally small r = np.sum(binary_msk) / np.sum(mask_cls) print('curr mask over all mask ratio', r) ratio_list.append(r) regionid_list.append(region_id) ratio_list, regionid_list = zip(*sorted(zip(ratio_list, regionid_list))) regionid_list = regionid_list[::-1] # 5 modes for now for mode in range(5): # Mode 0: middle point of LARGEST mask if mode == 0: binary_msk = np.where(label_msk==regionid_list[0], 1, 0) # Calculates the distance to the closest zero pixel for each pixel of the source image. # Ref from RITM: https://github.com/SamsungLabs/ritm_interactive_segmentation/blob/aa3bb52a77129e477599b5edfd041535bc67b259/isegm/data/points_sampler.py # NOTE: numpy and opencv have inverse definition of row and column # NOTE: SAM and opencv have the same definition padded_mask = np.uint8(np.pad(binary_msk, ((1, 1), (1, 1)), 'constant')) dist_img = cv2.distanceTransform(padded_mask, distanceType=cv2.DIST_L2, maskSize=5).astype(np.float32)[1:-1, 1:-1] cY, cX = np.where(dist_img==dist_img.max()) random_idx = np.random.randint(0, len(cX)) cX, cY = int(cX[random_idx]), int(cY[random_idx]) prompt = [(cX,cY,1)] # Mode 1: middle point of top-3 LARGEST mask if mode == 1: prompt = [] for mask_idx in range(3): if mask_idx < len(regionid_list): binary_msk = np.where(label_msk==regionid_list[mask_idx], 1, 0) padded_mask = np.uint8(np.pad(binary_msk, ((1, 1), (1, 1)), 'constant')) dist_img = cv2.distanceTransform(padded_mask, distanceType=cv2.DIST_L2, maskSize=5).astype(np.float32)[1:-1, 1:-1] cY, cX = np.where(dist_img==dist_img.max()) random_idx = np.random.randint(0, len(cX)) cX, cY = int(cX[random_idx]), int(cY[random_idx]) prompt.append((cX,cY,1)) # Mode 2: box of LARGEST mask if mode == 2: binary_msk = np.where(label_msk==regionid_list[0], 1, 0) box = MaskToBoxSimple(binary_msk) prompt = box # Mode 3: box of top-3 LARGEST mask if mode == 3: prompt = [] for mask_idx in range(3): if mask_idx < len(regionid_list): binary_msk = np.where(label_msk==regionid_list[mask_idx], 1, 0) box = MaskToBoxSimple(binary_msk) prompt.append(box) # Mode 4: box of ENTIRE mask if mode == 4: box = MaskToBoxSimple(mask_cls) prompt = box # Get output based on prompt type prompt = np.array(prompt) print('mode %s: prompt: %s' % (mode, prompt)) if prompt.shape[-1] == 3: pc = prompt[:,:2] pl = prompt[:, -1] preds, _, _ = predictor.predict(point_coords=pc, point_labels=pl) elif prompt.shape[-1] == 4: if len(prompt.shape) == 1: preds, _, _ = predictor.predict(box=prompt) else: preds = None for box in prompt: preds_single, _, _ = predictor.predict(box=box) if preds is None: preds = preds_single else: preds += preds_single preds = preds.transpose((1,2,0)) if args.oracle: max_slice, max_dc = -1, 0 for mask_slice in range(preds.shape[-1]): preds_mask_single = np.array(preds[:,:,mask_slice]>0,dtype=int) dc = IOUMulti(preds_mask_single, mask_cls) if dc > max_dc: max_dc = dc max_slice = mask_slice print(mask_slice, dc) preds_mask_single = np.array(preds[:,:,max_slice]>0,dtype=int) else: preds_mask_single = np.array(preds[:,:,0]>0,dtype=int) dc = IOUMulti(preds_mask_single, mask_cls) dc_prompt_tmp.append(dc) print('IoU:', dc) # Track prediction, only used when vis if vis: preds_mask_full.append(np.expand_dims(preds, 0)) prompts_full.append(prompt) # assgin final mask for this class to it dc_class_tmp.append(dc_prompt_tmp) dc_log.append(dc_class_tmp) names.append(im_name) print('****') # VIS mode only saves mask and prompt information if vis: # Final shape: N*H*W*3 # N = number of predictions. 1 if box prompt, otherwise number of prompts # H,W = size of mask # 3 = number of outputs per prediction. SAM returns 3 outpus per prompt. # If no oracle mode, select 0 # If oracle mode, select maximum slice. # You can do that later, or use variable "max_slice" preds_mask_full = np.concatenate(preds_mask_full) # If box: N*4, N=number of boxes, 4=box coordinate in XYXY format # If prompts:N*3, N=number of prmts, 3=cX, cY, pos/neg prompts_full = np.array(prompts_full) print(preds_mask_full.shape) # TODO: replace with desired storage place np.save('tmp/%s_pred.npy' % im_name[:-4], preds_mask_full) np.save('tmp/%s_prompt.npy' % im_name[:-4], prompts_full) if not vis: # BRATS labelled class as 1,2,4 dc_log = np.array(dc_log) print(dc_log.shape) print(np.nanmean(dc_log, axis=0)) print(np.nanmean(dc_log)) version = 'sam_diffmode' if args.oracle: version += '_oracle' json.dump(names, open('scores/v2/%s_binary_names_%s.json' % (version, dataset), 'w+')) np.save('scores/v2/%s_binary_score_%s.npy' % (version, dataset), dc_log)