[
  {
    "path": ".gitignore",
    "content": "*.pth\n*.py.swp\nrun_record.py\nscores*/*\n.ipynb*/*\nlog.txt\nresults/*\nsegment-anything/*\nsegment_anything/*\nritm_interactive_segmentation/*\nweights/*\n"
  },
  {
    "path": "CITATION.md",
    "content": "```bib\n@article{mazurowski2023segment,\n  title={Segment anything model for medical image analysis: an experimental study},\n  author={Mazurowski, Maciej A and Dong, Haoyu and Gu, Hanxue and Yang, Jichen and Konz, Nicholas and Zhang, Yixin},\n  journal={Medical Image Analysis},\n  volume={89},\n  pages={102918},\n  year={2023},\n  publisher={Elsevier}\n}\n```\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Segment Anything Model for Medical Image Analysis: an Experimental Study\n\n[![arXiv Paper](https://img.shields.io/badge/arXiv-2304.10517-orange.svg?style=flat)](https://arxiv.org/abs/2304.10517)\n\n#### By [Maciej Mazurowski](https://sites.duke.edu/mazurowski/), Haoyu Dong, Hanxue Gu, Jichen Yang, [Nicholas Konz](https://nickk124.github.io/) and Yixin Zhang.\n\nThis 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. \n\n## Installation\n\nThe 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\n\n```\ngit clone https://github.com/facebookresearch/segment-anything.git\ncd segment-anything; pip install -e .\n```\n\nOptionally, 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:\n\n```\ngit clone https://github.com/yzluka/ritm_interactive_segmentation\n```\n\n## Getting start\nFirst, download SAM's model checkpoint \n```\nwget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth\n```\n\nIf you want to run SAM (and competing methods) with iterative prompts, run the code with:\n```\npython3 prompt_gen_and_exec_v1.py --num-prompt XXX --model sam/ritm\n```\nwhere it will ask you to enter the dataset you wish to evaluate on.\n\nOptionally, to run RITM, you need to download its weights via:\n```\nwget https://github.com/saic-vul/ritm_interactive_segmentation/releases/download/v1.0/coco_lvis_h32_itermask.pth\n```\n\n\nIf you want to run SAM with the 5 mode proposed in the paper, run the code with:\n```\npython3 prompt_gen_and_exec_v2_allmode.py \n```\nThe 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)):\n- 1 point at the center of the **largest** component\n- 1 point at the center of **each** component (put at most 3 points)\n- 1 box sharply around the **largest** component\n- 1 box sharply around **each** component (put at most 3 boxes)\n- 1 box covers **all** object\n\n## Obtaining datasets from our paper\n\nTODO\n\n## Adding custom datasets\nTo evaluate your own dataset, you need to format the dataset as: \n```\n  XXX:\n     images:\n        abc.png\n        def.png\n        ...\n     masks:\n        abc.png\n        def.png\n        ...\n```\nwhere images and masks should have the same name.\n\n## News\n- 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.\n\n## Citation\nIf you find our work to be useful for your research, please cite our paper:\n```\n@article{mazurowski2023segment,\n  title={Segment anything model for medical image analysis: an experimental study},\n  author={Mazurowski, Maciej A and Dong, Haoyu and Gu, Hanxue and Yang, Jichen and Konz, Nicholas and Zhang, Yixin},\n  journal={Medical Image Analysis},\n  volume={89},\n  pages={102918},\n  year={2023},\n  publisher={Elsevier}\n}\n```\n"
  },
  {
    "path": "experimental_results_tables/Fig2-Performance of SAM for 5 modes of Use.csv",
    "content": ",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\n0,CT-Organ: Lung,0.5040375609102761,0.7649961536318798,0.8399531292817298,0.8544587010504898,0.5619888040977155,0.5751254678667818,0.9118037681853222,0.9287611757965885,0.8442930189948117,0.9014606792388544\n1,MRI-Spine: SP,0.7073228746669389,0.7096432977416823,0.7070476025992274,0.7095302007531917,0.9043487094339112,0.9119653011188062,0.9043487094339112,0.9119653011188062,0.9043487094339112,0.9119653011188062\n2,CT-Spleen,0.8691847407254183,0.8772478846904421,0.8689422709715835,0.8768474552752175,0.8888784234966336,0.8960502031503226,0.8903440667420405,0.8977486661086032,0.888157727658361,0.896161751204274\n3,Xray-Chest,0.488912549431233,0.7042973771124544,0.8255508338566884,0.8304664474345188,0.4845595757679478,0.5063367845139323,0.8808300821393182,0.9088518824912722,0.8380273852364888,0.8731804644274592\n4,Xray-Hip: Ilium,0.8649546268769193,0.8775119614476239,0.8649960616662165,0.8776958070689208,0.8671305346236142,0.9498623353564899,0.8671305346236142,0.9498623353564899,0.8671305346236142,0.9498623353564899\n5,CT-Liver,0.7168836341782948,0.7247227437045324,0.6897820158324605,0.6957833671590816,0.8339470767285759,0.8497763577430864,0.8454871317234407,0.8613084541832972,0.8244972081253991,0.841507070072933\n6,CT-Organ: Kidney,0.48812141016765004,0.5137771486899364,0.5293984833999216,0.5306062550294209,0.528200113701847,0.53434510978159,0.8309711867869959,0.8391476064107741,0.45035835954319947,0.5159415625931333\n7,CT-Organ: Bladder,0.5916728074734098,0.5916739116938898,0.5726033235071356,0.5726221823458707,0.7796024605322711,0.8196618408524342,0.7868766417826404,0.8290201142372928,0.7608618606538163,0.7958953774032693\n8,Xray-Hip: Femur,0.6737930817054792,0.6845047915027754,0.6740167144857426,0.6847395375238928,0.7867385105826606,0.8058534761556695,0.7867375836188909,0.8058525491918997,0.7867528936815141,0.805867859254523\n9,MRI-Heart,0.573143704527502,0.583662130445331,0.5775095522204375,0.5881684497095361,0.734538458869586,0.7669220221895826,0.7856222042741158,0.8176279421491547,0.6293998738464587,0.7048879357807536\n10,CT-Organ: Liver,0.6572655994639135,0.657509567934053,0.6356032466211343,0.6358335035559992,0.7789995383252979,0.8760939976763359,0.7854910304887937,0.8823629020543077,0.7778099650265168,0.8718598005716134\n11,US-Kidney,0.5531198274177759,0.6843526106476006,0.5569639972326419,0.6782384069681024,0.7717521567805573,0.8660795122175549,0.7722598559812998,0.8665291114759625,0.771622575672267,0.8660049668283785\n12,CT-Colon,0.5241501535721865,0.5307969474576953,0.5250511629078818,0.5313687214826,0.6987196146385244,0.7210953366255343,0.7180784774651142,0.7408698698258476,0.6941207593677051,0.7208699936931542\n13,CT-Organ: Bone,0.3870924726703019,0.537948309577858,0.5617453967171664,0.6075720277255027,0.5041121728098235,0.5591699598152509,0.7179510572142475,0.7861382489199804,0.4318603175075531,0.555966121641184\n14,CT-Pancreas,0.5010115151433743,0.532924268069487,0.4980692434242409,0.5275509005159461,0.6761699849486295,0.7309784379842976,0.6952301940549994,0.7507288043045295,0.656463026747013,0.7209926850758989\n15,MRI-Prostate,0.4716223475002687,0.5064347886055016,0.47104135778245915,0.5058923133864082,0.6843254450929145,0.7592649707750968,0.6848254784853673,0.7597124063727306,0.6834499338952817,0.7585286565598245\n16,US-Breast,0.4712195546907309,0.6188008177558781,0.4735816855561947,0.6155673166376364,0.6410504608959803,0.7790617068901438,0.6410492376798388,0.7790555125298435,0.641132505088589,0.7790603773140136\n17,MRI-Breast: Breast,0.34783472864351483,0.49746769921502504,0.35509528978447896,0.5012692482207185,0.5899735090916093,0.8347561389801192,0.6060022011834233,0.8527033667723514,0.5937453747396176,0.8437996657670627\n18,PET-Wholebody,0.3426932634019096,0.3520103866842598,0.326432439783384,0.3328435709649819,0.5173322095044326,0.6173761929957494,0.562570259343904,0.6693695039761657,0.4643212895824232,0.5706536068818072\n19,CT-Hepaticvessel,0.24518548187187356,0.24979626329976973,0.15671143905373192,0.1588021329729012,0.41687928725650014,0.46549963889514995,0.5419016843275795,0.5905769848091643,0.22333774646603485,0.25288755765451426\n20,MRI-Brain: GD,0.3644789966578506,0.3729348517929812,0.3510795231936171,0.35839340193525926,0.4884324398981961,0.5417414636069973,0.5092892536422939,0.5646283585515393,0.47862140678629467,0.5270173818782171\n21,MRI-Breast: FGT,0.2891343803228075,0.2985958075634497,0.22236704406413602,0.22236704406413602,0.34043336460000645,0.3467864983150635,0.49118344693603677,0.4944861199774202,0.2275343719139432,0.2550043716169522\n22,US-Variantumor,0.3398076921862697,0.4573707014742938,0.34383180057461576,0.459333444052403,0.4633740285070635,0.7190842974900171,0.46523688156504733,0.7211977909933263,0.4639737355438073,0.7202034744723546\n23,MRI-Brain: Core,0.2586909570158529,0.26170807541206154,0.23217271635685718,0.23415282948636373,0.416183998958719,0.45198666074925037,0.45756469370085256,0.5012820015283274,0.3333978894984103,0.35959147741753417\n24,MRI-Brain: Edema,0.26076432589689647,0.26263997215298457,0.23422116339198454,0.23653493691978156,0.41239031745961985,0.46911298689380737,0.4501623828483823,0.5098458542001842,0.3605293097304758,0.41228754855160304\n25,MRI-Spine: GM,0.11364871552061874,0.11364871552061874,0.11363235284637922,0.11363235284637922,0.2783918412038833,0.2877485790893153,0.2814359955162776,0.2910305845120911,0.2782344908831689,0.2874760097423331\n26,US-Nerve,0.12620618960020696,0.14699303717568177,0.12688055807197968,0.1475196349207403,0.23287614303247803,0.543738210855488,0.23287614303247803,0.543738210855488,0.23287614303247803,0.543738210855488\n27,US-Muscle,0.17728576808683244,0.3060046121522509,0.17914924775826055,0.30700876202985417,0.213416606828824,0.7724017740374894,0.2134182856841066,0.7724058881872616,0.21340544435737385,0.772385439486003\n"
  },
  {
    "path": "experimental_results_tables/fig34-Table_for_focalclick_point_number_changes.csv",
    "content": "﻿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\r\n1,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\r\n2,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\r\n3,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\r\n4,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\r\n5,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\r\n6,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\r\n7,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\r\n8,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\r\n9,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"
  },
  {
    "path": "experimental_results_tables/fig34-Table_for_ritm_point_number_changes.csv",
    "content": "﻿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\r\n1,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\r\n2,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\r\n3,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\r\n4,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\r\n5,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\r\n6,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\r\n7,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\r\n8,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\r\n9,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"
  },
  {
    "path": "experimental_results_tables/fig34-Table_for_sam_oracle_point_number_changes.csv",
    "content": "﻿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\r\n1,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\r\n2,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\r\n3,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\r\n4,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\r\n5,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\r\n6,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\r\n7,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\r\n8,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\r\n9,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"
  },
  {
    "path": "experimental_results_tables/fig34-Table_for_sam_point_number_changes.csv",
    "content": "﻿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\r\n1,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\r\n2,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\r\n3,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\r\n4,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\r\n5,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\r\n6,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\r\n7,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\r\n8,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\r\n9,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"
  },
  {
    "path": "experimental_results_tables/fig34-Table_for_simpleclick_point_number_changes.csv",
    "content": "﻿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\r\n1,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\r\n2,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\r\n3,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\r\n4,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\r\n5,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\r\n6,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\r\n7,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\r\n8,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\r\n9,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"
  },
  {
    "path": "experimental_results_tables/fig4-Table_average_overalldatasets_point_numer_changes.csv",
    "content": "Num of points,SAM,SAM (oracle),RITM,SimpleClick,FocalClick\r\n1,0.459519799,0.508014549,0.132232515,0.191030481,0.224022227\r\n2,0.539567888,0.553004503,0.303443928,0.348378298,0.382966275\r\n3,0.566878414,0.581487316,0.453819192,0.474998885,0.469059209\r\n4,0.584634865,0.602130352,0.539908923,0.546913028,0.52206614\r\n5,0.596895064,0.618017651,0.59617223,0.594181218,0.553567435\r\n6,0.604929737,0.628477461,0.63195318,0.625265764,0.577543683\r\n7,0.609457031,0.634867725,0.656464736,0.646124645,0.593629751\r\n8,0.611501257,0.63986344,0.675259442,0.661830439,0.605229646\r\n9,0.611249208,0.642368666,0.687500386,0.6743755,0.614151596"
  },
  {
    "path": "prompt_gen_and_exec_v1.py",
    "content": "from segment_anything import SamPredictor, sam_model_registry\nfrom PIL import Image, ImageDraw, ImageOps\nfrom shapely.geometry import LineString, MultiLineString, Polygon, Point, GeometryCollection\nfrom skimage.morphology import medial_axis\nfrom scipy.optimize import minimize_scalar\nfrom scipy.ndimage import binary_dilation\nfrom skimage.measure import label\nfrom sklearn.cluster import KMeans\n\nimport argparse\nimport os\nimport cv2\nimport json\nimport imutils\nimport random\nimport matplotlib.pyplot as plt\nimport numpy as np\n# Fix randomness in prompt selection\nnp.random.seed(1)\n\nimport sys\nsys.path.append('FocalClick')\n#sys.path.append('ritm_interactive_segmentation')\n#sys.path.append('CFR-ICL-Interactive-Segmentation')\nfrom isegm.inference.clicker import Click\nfrom isegm.inference import utils as is_utils\nfrom isegm.inference.predictors import get_predictor as is_get_predictor  \nfrom isegm.inference.evaluation import evaluate_sample_onepass as is_evaluate_sample_onepass\n\n#This is a helper function that should not be called directly\ndef _find_closest(centroid, pos_points):\n    dist_squared = np.sum((pos_points - centroid)**2, axis=1)\n    point_idx = np.argmin(dist_squared)\n    return pos_points[point_idx]\n\ndef IOU(pm, gt):\n    a = np.sum(np.bitwise_and(pm, gt))\n    b = np.sum(pm) + np.sum(gt) - a #+ 1e-8 \n    if b == 0:\n        return -1\n    else:\n        return a / b\n\ndef IOUMulti(y_pred, y):\n    score = 0\n    numLabels = np.max(y)\n    if np.max(y) == 1:\n        score = IOU(y_pred, y)\n        return score\n    else:\n        count = 1\n        for index in range(1,numLabels+1):\n            curr_score = IOU(y_pred[y==index], y[y==index])\n            print(index, curr_score)\n            if curr_score != -1:\n                score += curr_score\n                count += 1\n        return score / (count - 1) # taking average\n\n####################################################\n# input: raw_msk\n#   A mask should containing no 'void' class. \n#   Binary mask should have value {0,1} but not {0,255}\n# output:\n#   A list of region profiles; Each profile takes the form\n#   {'loc':[x0,y0,x1,y1], 'cls': cls}\n#   'loc' is a list with 4 elements ; 'cls' is object class as integer \n####################################################\ndef MaskToBoxes(mask):\n    label_msk, region_ids = label(mask, connectivity=2, return_num=True)\n    \n    bbox_profiles = []\n    for region_id  in range(1, region_ids+1):\n        #find coordinates of points in the region\n        row,col = np.argwhere(label_msk == region_id).T\n        #find class of the region\n        cls = mask[row[0],col[0]]\n        # find the four corner coordinates\n        y0,x0 = row.min(),col.min()\n        y1,x1 = row.max(),col.max()\n\n        bbox_profiles.append({'loc':[x0,y0,x1,y1], 'cls':cls})\n        \n    return bbox_profiles\n\n####################################################\n# input: raw_msk\n#   A mask should containing no 'void' class. \n#   Binary mask should have value {0,1} but not {0,255}\n# input: N\n#   The number of points to apply on each object/connected region\n# output:\n#   A list of region profiles. Each region profile takes the form\n#   {'loc':np.array([[x0,y0],[x1,y1],[x_N,y_N]]), 'cls': cls}\n#   'loc' is 2D array with shape (N, 2); 'cls' is object class as integer \n####################################################\ndef Mask2Points(raw_msk, N=1):\n    label_msk, region_ids = label(raw_msk, connectivity=2,return_num = True)\n    point_profiles = []\n\n    for region_id  in range(1, region_ids+1):\n        #find coordinates of points in the region\n        pos_points = np.argwhere(label_msk == region_id)\n        \n        # clean some region that is abnormally small\n        r = len(pos_points) / len(raw_msk.flatten())\n        if r < 1e-4:\n            continue\n        print('mask ratio', r)\n        #if len(pos_points) < len(raw_msk.flatten())*0.001:\n        #    continue\n            \n        #get the skeleton\n        binary_msk = np.where(label_msk == region_id,1,0)\n        skeleton_msk = medial_axis(binary_msk).astype(np.uint8)\n        skeleton_points = np.argwhere(skeleton_msk>0)\n\n        # Cluster and assign the object skeleton into N sections\n        #kmean = KMeans(n_clusters=N,n_init=3, algorithm='lloyd' if N == 1 else 'elkan').fit(skeleton_points)\n        kmean = KMeans(n_clusters=N,n_init=3, algorithm='auto').fit(skeleton_points)\n        cluster_assigned = np.zeros(len(skeleton_points)) if N == 1 else kmean.predict(skeleton_points)\n        centroids = kmean.cluster_centers_\n        \n        # pick a skeleton point closest to the centroid from each cluster\n        selected_points = np.zeros((N,2)) \n        for cluster_id, centroid in zip(range(N),centroids):\n            points_in_cluster = skeleton_points[cluster_assigned==cluster_id] \n            selected_points[cluster_id] = _find_closest(centroid,points_in_cluster)\n            \n        #find class of the region\n        cls = raw_msk[pos_points[0,0],pos_points[0,1]]\n        \n        point_profiles.append({'loc':np.concatenate((selected_points[:,1:],selected_points[:,0:1]),axis=1), 'cls':cls})\n        \n        #TODO: double check if > 1 regions found\n        break\n        \n    return point_profiles\n\nif __name__ == '__main__': \n    parser = argparse.ArgumentParser(description=\"SAG segmentor for medical images\")\n    parser.add_argument(\"--num-prompt\", default=1, type=int, help=\"number of prompts to include, negative number means using box as prompts\")\n    parser.add_argument(\"--class-type\", default=\"b\", type=str, help=\"binary or multi class, choose b or m\")\n    parser.add_argument(\"--model-path\", default=\"./\", type=str, help=\"the path of the model saved\")\n    parser.add_argument(\"--init-path\", default=\"./\", type=str, help=\"the path of the dataset\")\n    parser.add_argument(\"--model\", default=\"sam\", type=str, help=\"the model to use as predictor\")\n    parser.add_argument(\"--oracle\", default=False, type=bool, help=\"whether eval in the oracle mode, where best prediction is selected based on GT\")\n    parser.add_argument(\"--result-image\",default=\"./results\",type=str, help=\"the path to save segmented results\")\n    parser.add_argument(\"--result-score\",default=\"./scores\",type=str, help=\"the path to save result metrics\")\n    args = parser.parse_args()\n    \n    # Set up model\n    if args.model == 'sam':\n        sam = sam_model_registry[\"default\"](checkpoint=os.path.join(args.model_path, \"sam_vit_h_4b8939.pth\"))\n        sam.to('cuda')\n        predictor = SamPredictor(sam)\n    # NOTE: manual change sys path when importing library\n    elif args.model == 'ritm':\n        model = is_utils.load_is_model(os.path.join(args.model_path, \"coco_lvis_h32_itermask.pth\"), \"cuda\")\n        predictor = is_get_predictor(model, \"NoBRS\", \"cuda\")\n    elif args.model == 'sc': \n        model = is_utils.load_is_model(os.path.join(args.model_path, \"cocolvis_icl_vit_huge.pth\"), \"cuda\", eval_ritm=False)\n\n        zoom_in_params = {\n                        'skip_clicks': -1,\n                        'target_size': (448, 448)\n        }\n\n        predictor_params = {\n                        'cascade_step': 4 + 1,\n                        'cascade_adaptive': True,\n                        'cascade_clicks': 1\n        }\n        predictor = is_get_predictor(model, \"NoBRS\", \"cuda\", prob_thresh=0.49, \\\n                                     predictor_params=predictor_params, zoom_in_params=zoom_in_params)\n    elif args.model == 'fc':\n        model = is_utils.load_is_model(os.path.join(args.model_path, \"segformerB3_S2_comb.pth\"), \"cuda\")\n        predictor = is_get_predictor(model, \"NoBRS\", \"cuda\", prob_thresh=0.49)\n\n    print('Dataset you can choose among: chest, gmsc_sp, gmsc_gm, breast_b, breast_f, heart, usbreast, liver, prostate, nodule, brats, all')\n    # Set up dataset\n    dataset = input(\"Type of input: \")\n    if dataset == 'all':\n        dataset_list = ['busi', 'breast_b', 'breast_d', 'chest', 'gmsc_sp', 'gmsc_gm', 'heart', 'liver', 'petwhole', 'prostate', 'brats_3m', 'xrayhip', \\ \n                        'ctliver', 'ctorgan', 'ctcolon', 'cthepaticvessel', 'ctpancreas', 'ctspleen', 'usmuscle', 'usnerve', 'usovariantumor']\n    else:\n        dataset_list = [dataset]\n\n    for dataset in dataset_list:\n        print('curr dataset', dataset)\n        num_class = 1\n        if 'gmsc' in dataset:\n            input_img_dir = os.path.join(args.init_path, 'sa_gmsc/images') \n            input_seg_dir = os.path.join(args.init_path, 'sa_gmsc/masks')\n        elif 'breast' in dataset:\n            input_img_dir = os.path.join(args.init_path, \"sa_dbc-2D/imgs\")\n            if dataset == 'breast_b':\n                input_seg_dir = os.path.join(args.init_path, \"sa_dbc-2D/masks_breast\")\n            else:\n                input_seg_dir = os.path.join(args.init_path, \"sa_dbc-2D/masks_dense-tissue\")\n        else:\n            input_img_dir = os.path.join(args.init_path, 'sa_%s/images' % dataset)\n            input_seg_dir = os.path.join(args.init_path, 'sa_%s/masks' % dataset)\n\n        if dataset == 'brats_3m':\n            num_class = 3\n        if dataset == 'xrayhip':\n            num_class = 2\n        if dataset == 'ctorgan':\n            num_class = 5 \n\n        # target is a variable only used by GMSC\n        if dataset == 'gmsc_sp':\n            target = 'sp'\n        if dataset == 'gmsc_gm':\n            target = 'gm'\n\n        print(input_img_dir)\n        print(input_seg_dir)\n        \n        \n        if args.num_prompt<0:\n            save_path = os.path.join('results',dataset,'box')\n        elif args.oracle:\n            save_path = os.path.join('results',dataset,'oracle')\n        else:\n            save_path = os.path.join('results',dataset,'point')\n\n        # Running\n        dc_log, names = [], []\n        mask_list = os.listdir(input_seg_dir)\n        print('# of dataset', len(mask_list))\n        \n        # VIS: now VIS function is separted into another file. Only provide mask if needed\n        vis = False\n        # Change to [name1, name2, ...] if only need to run on a few samples\n        im_list = None#['CHNCXR_0061_0_mask.png'] \n\n        for im_idx, im_name in enumerate(mask_list):\n            # Skip non-selected images if specified\n            print(im_name)\n            if im_list is not None:\n                if im_name not in im_list:\n                    continue\n\n            # GMSC: All masks in the same dir, separated by names\n            if 'gmsc' in dataset:\n                if target not in im_name:\n                    continue\n\n            if 'DS_Store' in im_name:\n                continue\n\n            # Read image and mask\n            try:\n                input_mask = cv2.imread(os.path.join(input_seg_dir, im_name), 0)  \n            except:\n                print('Cannot read mask', im_name)\n                continue\n            \n            if np.max(input_mask) == 0:\n                print('Empty mask')\n                print('*****')\n                continue\n            \n            # In multi-class setting, we assume classes are labeled 0,1,2,3...\n            # BraTS has label 1,2,4\n            if 'brats' in dataset:\n                input_mask[input_mask == 4] = 3\n            \n            # In binary-class setting, some masks are encoded as 0, 255\n            if np.max(input_mask) == 255:\n                input_mask = np.uint8(input_mask / input_mask.max())\n\n            # Chest and GMSC: name inconsistentcy\n            if 'chest' in dataset:\n                im_name = im_name.replace('_mask', '')\n            if 'gmsc' in dataset:\n                im_name = im_name.replace('mask', 'image').replace(target+'-', '')\n            try:\n                input_image = Image.open(os.path.join(input_img_dir, im_name)).convert(\"RGB\")\n            except:\n                print('Cannot read image', im_name)\n                continue\n\n            input_array = np.array(input_image)\n            input_array = np.uint8(input_array / np.max(input_array) * 255)\n            print('Number of labels', np.max(input_mask))\n            print('Image maximum', np.max(input_array))\n            \n            # if we want to do multi-class classification\n            # else, we combine all the masks as the same class\n            #if args.class_type == 'm':\n            if num_class > 1:\n                #mask_one_hot = (np.arange(1, input_mask.max()+1) == input_mask[...,None]).astype(int) \n                mask_one_hot = (np.arange(1, num_class+1) == input_mask[...,None]).astype(int) \n            else: \n                mask_one_hot = np.array(input_mask > 0,dtype=int)\n            \n            if len(mask_one_hot.shape) < 3:\n                mask_one_hot = mask_one_hot[:,:,np.newaxis] # height*depth*1, to consistent with multi-class setting\n            \n            # Start prediction for each class\n            if args.model == 'sam':\n                predictor.set_image(input_array)\n            elif args.model == 'ritm':\n                predictor.set_input_image(input_array)\n            \n            # Mask has to be float\n            pre_mask = np.zeros_like(mask_one_hot, dtype=float)\n            dc_class_tmp = []\n            for cls in range(num_class):\n                dc_prompt_tmp = []\n                print('Predicting class %s' % cls)\n                # segment current class as binary segmentation\n                try:\n                    mask_cls = np.uint8(mask_one_hot[:,:,cls])\n                except:\n                    print('Mask do not contain this class, skipped')\n                    if num_class == 1:\n                        dc_class_tmp.append(np.nan)\n                    else:\n                        dc_class_tmp.append([np.nan] * args.num_prompt)\n                    continue\n\n                if np.sum(mask_cls) == 0:\n                    print('Empty single cls, skipped')\n                    #dc_class_tmp.append(np.nan)\n                    if num_class == 1:\n                        dc_class_tmp.append(np.nan)\n                    else:\n                        dc_class_tmp.append([np.nan] * args.num_prompt)\n                    continue\n                \n                # ------ Generate prompt by SAM's eval protocol -------#\n                preds_mask_full, prompts_full,gt_mask_full,input_full = [], [],[],[]\n\n                # Calculates the distance to the closest zero pixel for each pixel of the source image.\n                # Ref from RITM: https://github.com/SamsungLabs/ritm_interactive_segmentation/blob/aa3bb52a77129e477599b5edfd041535bc67b259/isegm/data/points_sampler.py\n                padded_mask = np.pad(mask_cls, ((1, 1), (1, 1)), 'constant')\n                dist_img = cv2.distanceTransform(padded_mask, distanceType=cv2.DIST_L2, maskSize=5).astype(np.float32)[1:-1, 1:-1]\n                # NOTE: numpy and opencv have inverse definition of row and column\n                # NOTE: SAM and opencv have the same definition\n                cY, cX = np.where(dist_img==dist_img.max())\n                # NOTE: random seems to change DC by +/-1e-4\n                # Random sample one point with largest distance\n                random_idx = np.random.randint(0, len(cX))\n                cX, cY = int(cX[random_idx]), int(cY[random_idx])\n                    \n                # First point: farthest from the object boundary\n                pc = [(cX,cY)]\n                pl = [1]\n\n                if args.model == 'sam':\n                    preds, _, _ = predictor.predict(point_coords=np.array(pc), point_labels=np.array(pl), return_logits=True)\n                elif args.model == 'ritm':\n                    # RITM returns mask, mask_prob, iou\n                    click_list = [Click(is_positive=True, coords=(cY, cX), indx = 0)]\n                    _, preds = is_evaluate_sample_onepass(predictor, click_list)\n                    # RITM uses 0.49 as threshold. Substract it to let 0 be the threshold\n                    preds = preds - 0.49\n                    preds = preds[None,:,:].repeat(3,0)\n                elif args.model == 'sc' or args.model == 'fc':\n                    # SimpleClick\n                    click_list = [Click(is_positive=True, coords=(cY, cX), indx = 0)]\n                    _, preds_prob, _ = is_evaluate_sample_onepass(input_array, mask_cls, predictor, click_list, \\\n                                                                  pred_thr=0.49, iterative=False)\n                    preds = preds_prob - 0.49\n                    preds = preds[None,:,:].repeat(3,0)\n                #elif args.model == 'fc':\n                #    click_list = [Click(is_positive=True, coords=(cY, cX), indx = 0)]\n                #    _, preds_prob, _ = is_evaluate_sample_onepass(input_array, mask_cls, predictor, click_list, \\\n                #                                                  pred_thr=0.49, iterative=False)\n                #    preds = preds_prob - 0.49\n\n                # if logit < 0, it is more like a background\n                preds[preds < 0] = 0 \n                preds = preds.transpose((1,2,0))\n\n                if args.oracle:\n                    max_slice, max_dc = -1, 0\n                    for mask_slice in range(preds.shape[-1]):\n                        preds_mask_single = np.array(preds[:,:,mask_slice]>0,dtype=int)\n                        dc = IOUMulti(preds_mask_single, mask_cls)\n                        if dc > max_dc:\n                            max_dc = dc\n                            max_slice = mask_slice\n                        print(mask_slice, dc)\n                    preds_mask_single = np.array(preds[:,:,max_slice]>0,dtype=int)\n                else:\n                    preds_mask_single = np.array(preds[:,:,0]>0,dtype=int)\n\n                dc = IOUMulti(preds_mask_single, mask_cls)\n                dc_prompt_tmp.append(dc)\n                preds_mask_full.append(np.expand_dims(preds, 0))\n                gt_mask_full.append(np.expand_dims(mask_cls, 0))\n                input_full.append(input_array)\n                prompts_full.append((cX,cY,1))\n \n                # Subsequent point: farthest from the boundary of the error region\n                for idx_p in range(args.num_prompt - 1):\n                    error_mask = np.uint8(np.bitwise_xor(mask_cls, preds_mask_single))\n                    padded_mask = np.pad(error_mask, ((1, 1), (1, 1)), 'constant')\n                    dist_img = cv2.distanceTransform(padded_mask, distanceType=cv2.DIST_L2, maskSize=5).astype(np.float32)[1:-1, 1:-1]\n                    cY, cX = np.where(dist_img==dist_img.max())\n                    random_idx = np.random.randint(0, len(cX))\n                    cX, cY = int(cX[random_idx]), int(cY[random_idx])\n                    pc.append((cX, cY))\n                    if np.sum(input_mask[cY][cX]) == 0:\n                        pl.append(0)\n                        prompts_full.append((cX,cY,0))\n                    else:\n                        pl.append(1)\n                        prompts_full.append((cX,cY,1))\n                    \n                    if args.model == 'sam':\n                        preds, _, _ = predictor.predict(point_coords=np.array(pc), point_labels=np.array(pl), return_logits=True)\n                    elif args.model == 'ritm':\n                        curr_click = Click(is_positive=pl[-1], coords=(cY, cX), indx = idx_p+1)\n                        click_list.append(curr_click)\n                        _, preds = is_evaluate_sample_onepass(predictor, click_list)\n                        preds = preds - 0.49\n                        preds = preds[None,:,:].repeat(3,0)\n                    elif args.model == 'sc' or args.model == 'fc':\n                        curr_click = Click(is_positive=pl[-1], coords=(cY, cX), indx = idx_p+1)\n                        click_list.append(curr_click)\n                        # SimpleClick\n                        _, preds_prob, _ = is_evaluate_sample_onepass(input_array, mask_cls, predictor, click_list, \\\n                                                                      pred_thr=0.49, iterative=False)\n                        preds = preds_prob - 0.49\n                        preds = preds[None,:,:].repeat(3,0)\n\n                    # if logit < 0, it is more like a background\n                    preds[preds < 0] = 0 \n                    preds = preds.transpose((1,2,0))\n\n                    if args.oracle:\n                        max_slice, max_dc = -1, 0\n                        for mask_slice in range(preds.shape[-1]):\n                            preds_mask_single = np.array(preds[:,:,mask_slice]>0,dtype=int)\n                            dc = IOUMulti(preds_mask_single, mask_cls)\n                            if dc > max_dc:\n                                max_dc = dc\n                                max_slice = mask_slice\n                        preds_mask_single = np.array(preds[:,:,max_slice]>0,dtype=int)\n                    else:\n                        preds_mask_single = np.array(preds[:,:,0]>0,dtype=int)\n                    \n                    dc = IOUMulti(preds_mask_single, mask_cls)\n                    dc_prompt_tmp.append(dc)\n\n                    preds_mask_full.append(np.expand_dims(preds, 0))\n                    gt_mask_full.append(np.expand_dims(mask_cls, 0))\n                    input_full.append(input_array)\n                print('Final prompts', pc, pl)\n\n                # assgin final mask for this class to it\n                print('Predicted DC', dc)\n                dc_class_tmp.append(dc_prompt_tmp)\n                pre_mask[:,:,cls] = preds[:,:,0]\n\n            dc_log.append(dc_class_tmp)\n            names.append(im_name)\n            print('****')\n            \n            # VIS mode only saves mask and prompt information\n            if vis:\n                # Final shape: N*H*W*3\n                # N = number of predictions. 1 if box prompt, otherwise number of prompts\n                # H,W = size of mask\n                # 3 = number of outputs per prediction. SAM returns 3 outpus per prompt. \n                #     If no oracle mode, select 0\n                #     If oracle mode, select maximum slice. \n                #     You can do that later, or use variable \"max_slice\"\n                preds_mask_full = np.concatenate(preds_mask_full)\n                gt_mask_full = np.concatenate(gt_mask_full)\n                input_full = np.concatenate(input_full)\n                # If box:    N*4, N=number of boxes, 4=box coordinate in XYXY format\n                # If prompts:N*3, N=number of prmts, 3=cX, cY, pos/neg\n                prompts_full = np.array(prompts_full)\n                print(preds_mask_full.shape)\n                # TODO: replace with desired storage place\n                if not os.path.exists(save_path):\n                    os.mkdir(save_path)\n                np.save(save_path+'/%s_pred.npy' % im_name[:-4], preds_mask_full)\n                np.save(save_path+'/%s_prompt.npy' % im_name[:-4], prompts_full)\n                np.save(save_path+'/%s_gt.npy' % im_name[:-4], gt_mask_full)\n                np.save(save_path+'/%s_input.npy' % im_name[:-4], input_full)\n        \n        \n        if not vis:\n            dc_log = np.array(dc_log)\n            print(dc_log.shape)\n            print(np.nanmean(dc_log, axis=0))\n            print(np.nanmean(dc_log))\n                \n            version = 'sam_prompt'\n            #version = 'sam_oracle'\n            #version = 'sam_box'\n            if args.model == 'sc':\n                version = 'simpleclick'\n            if args.model == 'fc':\n                version = 'focalclick'\n            if args.model == 'ritm':\n                version = 'ritm'\n\n            json.dump(names, open('scores/v1_rerun/%s_binary_names_%s.json' % (version, dataset), 'w+'))\n            np.save('scores/v1_rerun/%s_binary_score_%s.npy' % (version, dataset), dc_log)\n\n\n"
  },
  {
    "path": "prompt_gen_and_exec_v2_allmode.py",
    "content": "from segment_anything import SamPredictor, sam_model_registry\nfrom PIL import Image, ImageDraw, ImageOps\nfrom shapely.geometry import LineString, MultiLineString, Polygon, Point, GeometryCollection\nfrom skimage.morphology import medial_axis\nfrom scipy.optimize import minimize_scalar\nfrom scipy.ndimage import binary_dilation\nfrom skimage.measure import label\nfrom sklearn.cluster import KMeans\n\nimport argparse\nimport os\nimport cv2\nimport json\nimport imutils\nimport random\nimport matplotlib.pyplot as plt\nimport numpy as np\n# Fix randomness in prompt selection\nnp.random.seed(1)\n\n#This is a helper function that should not be called directly\ndef _find_closest(centroid, pos_points):\n    dist_squared = np.sum((pos_points - centroid)**2, axis=1)\n    point_idx = np.argmin(dist_squared)\n    return pos_points[point_idx]\n\ndef IOU(pm, gt):\n    a = np.sum(np.bitwise_and(pm, gt))\n    b = np.sum(pm) + np.sum(gt) - a #+ 1e-8 \n    if b == 0:\n        return -1\n    else:\n        return a / b\n\ndef IOUMulti(y_pred, y):\n    score = 0\n    numLabels = np.max(y)\n    if np.max(y) == 1:\n        score = IOU(y_pred, y)\n        return score\n    else:\n        count = 1\n        for index in range(1,numLabels+1):\n            curr_score = IOU(y_pred[y==index], y[y==index])\n            print(index, curr_score)\n            if curr_score != -1:\n                score += curr_score\n                count += 1\n        return score / (count - 1) # taking average\n\n####################################################\n# input: raw_msk\n#   A mask should containing no 'void' class. \n#   Binary mask should have value {0,1} but not {0,255}\n# output:\n#   A list of region profiles; Each profile takes the form\n#   {'loc':[x0,y0,x1,y1], 'cls': cls}\n#   'loc' is a list with 4 elements ; 'cls' is object class as integer \n####################################################\ndef MaskToBoxSimple(mask):\n    mask = mask.squeeze()\n    #find coordinates of points in the region\n    row, col = np.argwhere(mask).T\n    # find the four corner coordinates\n    y0,x0 = row.min(),col.min()\n    y1,x1 = row.max(),col.max()\n\n    return [x0,y0,x1,y1]\n\nif __name__ == '__main__': \n    parser = argparse.ArgumentParser(description=\"SAG segmentor for medical images\")\n    parser.add_argument(\"--num-prompt\", default=1, type=int, help=\"number of prompts to include, negative number means using box as prompts\")\n    parser.add_argument(\"--class-type\", default=\"b\", type=str, help=\"binary or multi class, choose b or m\")\n    parser.add_argument(\"--model-path\", default=\"./\", type=str, help=\"the path of the model saved\")\n    parser.add_argument(\"--init-path\", default=\"./\", type=str, help=\"the path of the dataset\")\n    parser.add_argument(\"--model\", default=\"sam\", type=str, help=\"the model to use as predictor\")\n    parser.add_argument(\"--oracle\", default=False, type=bool, help=\"whether eval in the oracle mode, where best prediction is selected based on GT\")\n    parser.add_argument(\"--result-image\",default=\"./results\",type=str, help=\"the path to save segmented results\")\n    parser.add_argument(\"--result-score\",default=\"./scores\",type=str, help=\"the path to save result metrics\")\n    args = parser.parse_args()\n    \n    # Set up model\n    sam = sam_model_registry[\"default\"](checkpoint=os.path.join(args.model_path, \"sam_vit_h_4b8939.pth\"))\n    sam.to('cuda')\n    predictor = SamPredictor(sam)\n\n    # Set up dataset\n    dataset = input(\"Type of input: \")\n    if dataset == 'all':\n        # all\n        dataset_list = ['busi', 'breast_b', 'breast_d', 'chest', 'gmsc_sp', 'gmsc_gm', 'heart', 'liver', 'petwhole', 'prostate', 'brats_3m', 'xrayhip', \\ \n                        'ctliver', 'ctorgan', 'ctcolon', 'cthepaticvessel', 'ctpancreas', 'ctspleen', 'usmuscle', 'usnerve', 'usovariantumor']\n    else:\n        dataset_list = [dataset]\n\n    for dataset in dataset_list:\n        num_class = 1\n        if 'gmsc' in dataset:\n            input_img_dir = os.path.join(args.init_path, 'sa_gmsc/images') \n            input_seg_dir = os.path.join(args.init_path, 'sa_gmsc/masks')\n        elif 'breast' in dataset:\n            input_img_dir = \"../sa_dbc-2D/imgs\"\n            if dataset == 'breast_b':\n                input_seg_dir = \"../sa_dbc-2D/masks_breast\"\n            else:\n                input_seg_dir = \"../sa_dbc-2D/masks_dense-tissue\"\n        else:\n            input_img_dir = os.path.join(args.init_path, 'sa_%s/images' % dataset)\n            input_seg_dir = os.path.join(args.init_path, 'sa_%s/masks' % dataset)\n        \n        # Handle dataset with multi-class\n        if dataset == 'brats_3m':\n            num_class = 3\n        if dataset == 'xrayhip':\n            num_class = 2\n        if dataset == 'ctorgan':\n            num_class = 5 \n\n        # target is a variable only used by GMSC\n        if dataset == 'gmsc_sp':\n            target = 'sp'\n        if dataset == 'gmsc_gm':\n            target = 'gm'\n        print(input_img_dir)\n        print(input_seg_dir)\n\n        # Running\n        dc_log, names = [], []\n        mask_list = os.listdir(input_seg_dir)\n        print('# of dataset', len(mask_list))\n        \n        # VIS: now VIS function is separted into another file. Only provide mask if neede\n        vis = False\n        # Change to [name1, name2, ...] if only need to run on a few samples\n        im_list = None#['CHNCXR_0061_0_mask.png'] \n\n        for im_idx, im_name in enumerate(mask_list):\n            # Skip non-selected images if specified\n            print(im_name)\n            if im_list is not None:\n                if im_name not in im_list:\n                    continue\n\n            # GMSC: All masks in the same dir, separated by names\n            if 'gmsc' in dataset:\n                if target not in im_name:\n                    continue\n\n            if 'DS_Store' in im_name:\n                continue\n\n            # Read image and mask\n            try:\n                input_mask = cv2.imread(os.path.join(input_seg_dir, im_name), 0)  \n            except:\n                print('Cannot read mask', im_name)\n                continue\n            if np.max(input_mask) == 0:\n                print('Empty mask')\n                print('*****')\n                continue\n            \n            # In multi-class setting, we assume classes are labeled 0,1,2,3...\n            # BraTS has label 1,2,4\n            if 'brats' in dataset:\n                input_mask[input_mask == 4] = 3\n            \n            # In binary-class setting, some masks are encoded as 0, 255\n            if np.max(input_mask) == 255:\n                input_mask = np.uint8(input_mask / input_mask.max())\n\n            # Chest and GMSC: name inconsistentcy\n            if 'chest' in dataset:\n                im_name = im_name.replace('_mask', '')\n            if 'gmsc' in dataset:\n                im_name = im_name.replace('mask', 'image').replace(target+'-', '')\n            try:\n                input_image = Image.open(os.path.join(input_img_dir, im_name)).convert(\"RGB\")\n            except:\n                print('Cannot read image', im_name)\n                continue\n\n            input_array = np.array(input_image)\n            input_array = np.uint8(input_array / np.max(input_array) * 255)\n            print('Number of labels', np.max(input_mask))\n            print('Image maximum', np.max(input_array))\n            \n            # if we want to do multi-class classification\n            # else, we combine all the masks as the same class\n            #if args.class_type == 'm':\n            if num_class > 1:\n                #mask_one_hot = (np.arange(1, input_mask.max()+1) == input_mask[...,None]).astype(int) \n                mask_one_hot = (np.arange(1, num_class+1) == input_mask[...,None]).astype(int) \n            else: \n                mask_one_hot = np.array(input_mask > 0,dtype=int)\n            \n            if len(mask_one_hot.shape) < 3:\n                mask_one_hot = mask_one_hot[:,:,np.newaxis] # height*depth*1, to consistent with multi-class setting\n            \n            # Start prediction for each class\n            predictor.set_image(input_array)\n            \n            # Mask has to be float\n            dc_class_tmp = []\n            for cls in range(num_class):\n                dc_prompt_tmp = []\n                # Cls = 2 means to predict mask with label 3\n                # But BraTS use 1,2,4 to label differet classes\n                #if cls == 2 and 'brats' in dataset:\n                #    cls += 1\n                print('Predicting class %s' % cls)\n                # segment current class as binary segmentation\n                try:\n                    mask_cls = np.uint8(mask_one_hot[:,:,cls])\n                except:\n                    print('Mask do not contain this class, skipped')\n                    if num_class == 1:\n                        dc_class_tmp.append(np.nan)\n                    else:\n                        # Fixed with 5 modes for now\n                        dc_class_tmp.append([np.nan] * 5)\n                    continue\n\n                if np.sum(mask_cls) == 0:\n                    print('Empty single cls, skipped')\n                    #dc_class_tmp.append(np.nan)\n                    if num_class == 1:\n                        dc_class_tmp.append(np.nan)\n                    else:\n                        dc_class_tmp.append([np.nan] * 5)\n                    continue\n                \n                # ------ Generate prompt by our definition -------- #\n                preds_mask_full, prompts_full = [], []\n                \n                # Find all disconnected regions\n                label_msk, region_ids = label(mask_cls, connectivity=2, return_num=True)\n                print('num of regions found', region_ids)\n                ratio_list, regionid_list = [], []\n                for region_id in range(1, region_ids+1):\n                    #find coordinates of points in the region\n                    binary_msk = np.where(label_msk==region_id, 1, 0)\n\n                    # clean some region that is abnormally small\n                    r = np.sum(binary_msk) / np.sum(mask_cls)\n                    print('curr mask over all mask ratio', r)\n                    ratio_list.append(r)\n                    regionid_list.append(region_id)\n\n                ratio_list, regionid_list = zip(*sorted(zip(ratio_list, regionid_list)))\n                regionid_list = regionid_list[::-1]\n\n                # 5 modes for now\n                for mode in range(5):\n                    # Mode 0: middle point of LARGEST mask\n                    if mode == 0:\n                        binary_msk = np.where(label_msk==regionid_list[0], 1, 0)\n                        # Calculates the distance to the closest zero pixel for each pixel of the source image.\n                        # Ref from RITM: https://github.com/SamsungLabs/ritm_interactive_segmentation/blob/aa3bb52a77129e477599b5edfd041535bc67b259/isegm/data/points_sampler.py\n                        # NOTE: numpy and opencv have inverse definition of row and column\n                        # NOTE: SAM and opencv have the same definition\n                        padded_mask = np.uint8(np.pad(binary_msk, ((1, 1), (1, 1)), 'constant'))\n                        dist_img = cv2.distanceTransform(padded_mask, distanceType=cv2.DIST_L2, maskSize=5).astype(np.float32)[1:-1, 1:-1]\n                        cY, cX = np.where(dist_img==dist_img.max())\n                        random_idx = np.random.randint(0, len(cX))\n                        cX, cY = int(cX[random_idx]), int(cY[random_idx])\n\n                        prompt = [(cX,cY,1)]\n                    # Mode 1: middle point of top-3 LARGEST mask\n                    if mode == 1:\n                        prompt = []\n                        for mask_idx in range(3):\n                            if mask_idx < len(regionid_list):\n                                binary_msk = np.where(label_msk==regionid_list[mask_idx], 1, 0) \n                                padded_mask = np.uint8(np.pad(binary_msk, ((1, 1), (1, 1)), 'constant'))\n                                dist_img = cv2.distanceTransform(padded_mask, distanceType=cv2.DIST_L2, maskSize=5).astype(np.float32)[1:-1, 1:-1]\n                                cY, cX = np.where(dist_img==dist_img.max())\n                                random_idx = np.random.randint(0, len(cX))\n                                cX, cY = int(cX[random_idx]), int(cY[random_idx])\n                                \n                                prompt.append((cX,cY,1))\n                    # Mode 2: box of LARGEST mask\n                    if mode == 2:\n                        binary_msk = np.where(label_msk==regionid_list[0], 1, 0)\n                        box = MaskToBoxSimple(binary_msk)\n                        prompt = box\n                    # Mode 3: box of top-3 LARGEST mask\n                    if mode == 3:\n                        prompt = []\n                        for mask_idx in range(3):\n                            if mask_idx < len(regionid_list):\n                                binary_msk = np.where(label_msk==regionid_list[mask_idx], 1, 0)\n                                box = MaskToBoxSimple(binary_msk)\n                                prompt.append(box)\n                    # Mode 4: box of ENTIRE mask\n                    if mode == 4:\n                        box = MaskToBoxSimple(mask_cls)\n                        prompt = box\n\n                    # Get output based on prompt type\n                    prompt = np.array(prompt)\n                    print('mode %s: prompt: %s' % (mode, prompt))\n                    if prompt.shape[-1] == 3:\n                        pc = prompt[:,:2]\n                        pl = prompt[:, -1]\n                        preds, _, _ = predictor.predict(point_coords=pc, point_labels=pl)\n                    elif prompt.shape[-1] == 4:\n                        if len(prompt.shape) == 1:\n                            preds, _, _ = predictor.predict(box=prompt)\n                        else:\n                            preds = None\n                            for box in prompt:\n                                preds_single, _, _ = predictor.predict(box=box)\n                                if preds is None:\n                                    preds = preds_single\n                                else:\n                                    preds += preds_single\n\n                    preds = preds.transpose((1,2,0))\n                    if args.oracle:\n                        max_slice, max_dc = -1, 0\n                        for mask_slice in range(preds.shape[-1]):\n                            preds_mask_single = np.array(preds[:,:,mask_slice]>0,dtype=int)\n                            dc = IOUMulti(preds_mask_single, mask_cls)\n                            if dc > max_dc:\n                                max_dc = dc\n                                max_slice = mask_slice\n                            print(mask_slice, dc)\n                        preds_mask_single = np.array(preds[:,:,max_slice]>0,dtype=int)\n                    else:\n                        preds_mask_single = np.array(preds[:,:,0]>0,dtype=int)\n\n                    dc = IOUMulti(preds_mask_single, mask_cls)\n                    dc_prompt_tmp.append(dc)\n                    print('IoU:', dc)\n                    \n                    # Track prediction, only used when vis\n                    if vis:\n                        preds_mask_full.append(np.expand_dims(preds, 0))\n                        prompts_full.append(prompt)\n\n                # assgin final mask for this class to it\n                dc_class_tmp.append(dc_prompt_tmp)\n            \n            dc_log.append(dc_class_tmp)\n            names.append(im_name)\n            print('****')\n            \n            # VIS mode only saves mask and prompt information\n            if vis:\n                # Final shape: N*H*W*3\n                # N = number of predictions. 1 if box prompt, otherwise number of prompts\n                # H,W = size of mask\n                # 3 = number of outputs per prediction. SAM returns 3 outpus per prompt. \n                #     If no oracle mode, select 0\n                #     If oracle mode, select maximum slice. \n                #     You can do that later, or use variable \"max_slice\"\n                preds_mask_full = np.concatenate(preds_mask_full)\n\n                # If box:    N*4, N=number of boxes, 4=box coordinate in XYXY format\n                # If prompts:N*3, N=number of prmts, 3=cX, cY, pos/neg\n                prompts_full = np.array(prompts_full)\n                print(preds_mask_full.shape)\n                # TODO: replace with desired storage place\n                np.save('tmp/%s_pred.npy' % im_name[:-4], preds_mask_full)\n                np.save('tmp/%s_prompt.npy' % im_name[:-4], prompts_full)\n\n        if not vis:\n            # BRATS labelled class as 1,2,4\n            dc_log = np.array(dc_log)\n            print(dc_log.shape)\n            print(np.nanmean(dc_log, axis=0))\n            print(np.nanmean(dc_log))\n\n            version = 'sam_diffmode'\n            if args.oracle:\n                version += '_oracle'\n\n            json.dump(names, open('scores/v2/%s_binary_names_%s.json' % (version, dataset), 'w+'))\n            np.save('scores/v2/%s_binary_score_%s.npy' % (version, dataset), dc_log)\n\n\n"
  }
]