introvoyz041 commited on
Commit
3f31c34
1 Parent(s): 6d0a2f9

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .github/workflows/issue-translator.yml +18 -0
  2. .gitignore +4 -0
  3. LICENSE +674 -0
  4. README.md +176 -12
  5. __pycache__/cfg.cpython-37.pyc +0 -0
  6. __pycache__/cfg.cpython-38.pyc +0 -0
  7. __pycache__/dataset.cpython-37.pyc +0 -0
  8. __pycache__/dataset.cpython-38.pyc +0 -0
  9. __pycache__/function.cpython-37.pyc +0 -0
  10. __pycache__/function.cpython-38.pyc +0 -0
  11. __pycache__/utils.cpython-37.pyc +0 -0
  12. __pycache__/utils.cpython-38.pyc +0 -0
  13. cfg.py +59 -0
  14. conf/__init__.py +15 -0
  15. conf/__pycache__/__init__.cpython-37.pyc +0 -0
  16. conf/__pycache__/__init__.cpython-38.pyc +0 -0
  17. conf/__pycache__/global_settings.cpython-37.pyc +0 -0
  18. conf/__pycache__/global_settings.cpython-38.pyc +0 -0
  19. conf/global_settings.py +54 -0
  20. dataset/__init__.py +230 -0
  21. dataset/__pycache__/__init__.cpython-37.pyc +0 -0
  22. dataset/__pycache__/atlas.cpython-37.pyc +0 -0
  23. dataset/__pycache__/brat.cpython-37.pyc +0 -0
  24. dataset/__pycache__/ddti.cpython-37.pyc +0 -0
  25. dataset/__pycache__/isic.cpython-37.pyc +0 -0
  26. dataset/__pycache__/kits.cpython-37.pyc +0 -0
  27. dataset/__pycache__/lidc.cpython-37.pyc +0 -0
  28. dataset/__pycache__/pendal.cpython-37.pyc +0 -0
  29. dataset/__pycache__/refuge.cpython-37.pyc +0 -0
  30. dataset/__pycache__/segrap.cpython-37.pyc +0 -0
  31. dataset/__pycache__/stare.cpython-37.pyc +0 -0
  32. dataset/__pycache__/toothfairy.cpython-37.pyc +0 -0
  33. dataset/__pycache__/wbc.cpython-37.pyc +0 -0
  34. dataset/atlas.py +86 -0
  35. dataset/brat.py +90 -0
  36. dataset/ddti.py +99 -0
  37. dataset/isic.py +78 -0
  38. dataset/kits.py +87 -0
  39. dataset/lidc.py +96 -0
  40. dataset/lnq.py +80 -0
  41. dataset/pendal.py +71 -0
  42. dataset/refuge.py +91 -0
  43. dataset/segrap.py +65 -0
  44. dataset/stare.py +75 -0
  45. dataset/toothfairy.py +80 -0
  46. dataset/wbc.py +65 -0
  47. environment.yml +319 -0
  48. figs/EfficientSAM/EfficientSAM-S (ISIC)_loss.png +0 -0
  49. figs/EfficientSAM/EfficientSAM-S (ISIC)_performance.png +0 -0
  50. figs/EfficientSAM/EfficientSAM-S (REFUGE)_loss.png +0 -0
.github/workflows/issue-translator.yml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: 'issue-translator'
2
+ on:
3
+ issue_comment:
4
+ types: [created]
5
+ issues:
6
+ types: [opened]
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: usthe/[email protected]
13
+ with:
14
+ IS_MODIFY_TITLE: false
15
+ # not require, default false, . Decide whether to modify the issue title
16
+ # if true, the robot account @Issues-translate-bot must have modification permissions, invite @Issues-translate-bot to your project or use your custom bot.
17
+ CUSTOM_BOT_NOTE: Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑‍🤝‍🧑👫🧑🏿‍🤝‍🧑🏻👩🏾‍🤝‍👨🏿👬🏿
18
+ # not require. Customize the translation robot prefix message.
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ /checkpoint
2
+ /logs
3
+ /runs
4
+ pipline.sh
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md CHANGED
@@ -1,12 +1,176 @@
1
- ---
2
- title: Medical Segment Anything Adapter
3
- emoji: 🔥
4
- colorFrom: gray
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 4.37.2
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <h1 align="center">● Medical SAM Adapter</h1>
2
+
3
+ <p align="center">
4
+ <a href="https://discord.gg/DN4rvk95CC">
5
+ <img alt="Discord" src="https://img.shields.io/discord/1146610656779440188?logo=discord&style=flat&logoColor=white"/></a>
6
+ <img src="https://img.shields.io/static/v1?label=license&message=GPL&color=white&style=flat" alt="License"/>
7
+ </p>
8
+
9
+ Medical SAM Adapter, or say MSA, is a project to fineturn [SAM](https://github.com/facebookresearch/segment-anything) using [Adaption](https://lightning.ai/pages/community/tutorial/lora-llm/) for the Medical Imaging.
10
+ This method is elaborated on the paper [Medical SAM Adapter: Adapting Segment Anything Model for Medical Image Segmentation](https://arxiv.org/abs/2304.12620).
11
+
12
+ ## A Quick Overview
13
+ <img width="880" height="380" src="https://github.com/WuJunde/Medical-SAM-Adapter/blob/main/figs/medsamadpt.jpeg">
14
+
15
+ ## News
16
+ - [TOP] Join in our [Discord](https://discord.gg/EqbgSPEX) to ask questions and discuss with others.
17
+ - [TOP] 24-03-02 We have released our pre-trained Adapters in [Medical-Adapter-Zoo](https://huggingface.co/KidsWithTokens/Medical-Adapter-Zoo/tree/main). Try it without painful training 😉 Credit: @shinning0821
18
+ - 23-05-10. This project is still quickly updating 🌝. Check TODO list to see what will be released next.
19
+ - 23-05-11. GitHub Dicussion opened. You guys can now talk, code and make friends on the playground 👨‍❤️‍👨.
20
+ - 23-12-22. Released data loader and example case on [REFUGE](https://refuge.grand-challenge.org/) dataset. Credit: @jiayuanz3
21
+ - 24-01-04. Released the Efficient Med-SAM-Adapter❗️ A new, faster, and more lightweight version incorporates Meta [EfficientSAM](https://yformer.github.io/efficient-sam/)🏇. Full credit goes to @shinning0821.
22
+ - 24-01-07. The image resolution now can be resized by ``-image_size``. Credit: @shinning0821
23
+ - 24-01-11. Added a detailed guide on utilizing the Efficient Med-SAM-Adapter, complete with a comparison of performance and speed. You can find this resource in [guidance/efficient_sam.ipynb](./guidance/efficient_sam.ipynb). Credit: @shinning0821
24
+ - 24-01-14. We've just launched our first official version, v0.1.0-alpha 🥳. This release includes support for [MobileSAM](https://github.com/ChaoningZhang/MobileSAM), which can be activated by setting ``-net mobile_sam``. Additionally, you now have the flexibility to use ViT, Tiny ViT, and Efficient ViT as encoders. Check the details [here](https://github.com/KidsWithTokens/Medical-SAM-Adapter/releases/tag/v0.1.0-alpha). Credit: @shinning0821
25
+ - 24-01-20. Added a guide on utilizing the mobile sam in Med-SAM-Adapter, with a comparison of performance and speed. You can find it in [guidance/mobile_sam.ipynb](https://github.com/KidsWithTokens/Medical-SAM-Adapter/blob/main/guidance/mobile_sam.ipynb) Credit: @shinning0821
26
+ - 24-01-21. We've added [LoRA](https://huggingface.co/docs/diffusers/training/lora) to our framework🤖. Use it by setting ``-mod`` as ``sam_lora``.
27
+ A guidance can be found in [here](https://github.com/KidsWithTokens/Medical-SAM-Adapter/blob/main/guidance/lora.ipynb). Credit: @shinning0821
28
+ - 24-01-22. We've added dataloader for [LIDC dataset](https://paperswithcode.com/dataset/lidc-idri), a multi-rater(4 raters 👨‍⚕️🧑🏽‍⚕️👩‍⚕️🧑🏽‍⚕️) lesions segmentation from low-dose lung CTs 🩻. You can download the preprocessed LIDC dataset at [here](https://github.com/stefanknegt/Probabilistic-Unet-Pytorch). Also updated environment, and random_click function. Credit: @jiayuanz3
29
+ - 24-03-06. We've supported multi-class segmentation. Use it by setting ``-multimask_output`` to the number of classes favored. Also updated REFUGE example to two classes (optic disc & cup). Credit: @LJQCN101
30
+ - 24-03-06. We've supported many other datasets and rebuild the code of datasets and dataloaders. Seen in `guidance/Dataset.md` Credit: @shinning0821
31
+
32
+ ## Medical Adapter Zoo 🐘🐊🦍🦒🦨🦜🦥
33
+ We've released a bunch of pre-trained Adapters for various organs/lesions in [Medical-Adapter-Zoo](https://huggingface.co/KidsWithTokens/Medical-Adapter-Zoo/tree/main). Just pick the adapter that matches your disease and easily adjust SAM to suit your specific needs 😉.
34
+
35
+ If you can't find what you're looking for. Please suggest it through any contact method available to us (GitHub issue, HuggingFace community, or [Discord](https://discord.gg/EqbgSPEX)). We'll do our very best to include it.
36
+
37
+ ## Requirement
38
+
39
+ Install the environment:
40
+
41
+ ``conda env create -f environment.yml``
42
+
43
+ ``conda activate sam_adapt``
44
+
45
+ Then download [SAM checkpoint](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth), and put it at ./checkpoint/sam/
46
+
47
+ You can run:
48
+
49
+ ``wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth``
50
+
51
+ ``mv sam_vit_b_01ec64.pth ./checkpoint/sam``
52
+ creat the folder if it does not exist
53
+
54
+ ## Example Cases
55
+
56
+ ### Melanoma Segmentation from Skin Images (2D)
57
+
58
+ 1. Download ISIC dataset part 1 from https://challenge.isic-archive.com/data/. Then put the csv files in "./data/isic" under your data path. Your dataset folder under "your_data_path" should be like:
59
+ ISIC/
60
+ ISBI2016_ISIC_Part1_Test_Data/...
61
+
62
+ ISBI2016_ISIC_Part1_Training_Data/...
63
+
64
+ ISBI2016_ISIC_Part1_Test_GroundTruth.csv
65
+
66
+ ISBI2016_ISIC_Part1_Training_GroundTruth.csv
67
+
68
+ You can fine the csv files [here](https://github.com/KidsWithTokens/MedSegDiff/tree/master/data/isic_csv)
69
+
70
+ 3. Begin Adapting! run: ``python train.py -net sam -mod sam_adpt -exp_name *msa_test_isic* -sam_ckpt ./checkpoint/sam/sam_vit_b_01ec64.pth -image_size 1024 -b 32 -dataset isic -data_path *../data*``
71
+ change "data_path" and "exp_name" for your own useage. you can change "exp_name" to anything you want.
72
+
73
+ You can descrease the ``image size`` or batch size ``b`` if out of memory.
74
+
75
+ 3. Evaluation: The code can automatically evaluate the model on the test set during traing, set "--val_freq" to control how many epoches you want to evaluate once. You can also run val.py for the independent evaluation.
76
+
77
+ 4. Result Visualization: You can set "--vis" parameter to control how many epoches you want to see the results in the training or evaluation process.
78
+
79
+ In default, everything will be saved at `` ./logs/``
80
+
81
+ ### REFUGE: Optic-disc Segmentation from Fundus Images (2D)
82
+ [REFUGE](https://refuge.grand-challenge.org/) dataset contains 1200 fundus images with optic disc/cup segmentations and clinical glaucoma labels.
83
+
84
+ 1. Dowaload the dataset manually from [here](https://huggingface.co/datasets/realslimman/REFUGE-MultiRater/tree/main), or using command lines:
85
+
86
+ ``git lfs install``
87
+
88
+ ``git clone [email protected]:datasets/realslimman/REFUGE-MultiRater``
89
+
90
+ unzip and put the dataset to the target folder
91
+
92
+ ``unzip ./REFUGE-MultiRater.zip``
93
+
94
+ ``mv REFUGE-MultiRater ./data``
95
+
96
+ 2. For training the adapter, run: ``python train.py -net sam -mod sam_adpt -exp_name REFUGE-MSAdapt -sam_ckpt ./checkpoint/sam/sam_vit_b_01ec64.pth -image_size 1024 -b 32 -dataset REFUGE -data_path ./data/REFUGE-MultiRater``
97
+ you can change "exp_name" to anything you want.
98
+
99
+ You can descrease the ``image size`` or batch size ``b`` if out of memory.
100
+
101
+ ### Abdominal Multiple Organs Segmentation (3D)
102
+
103
+ This tutorial demonstrates how MSA can adapt SAM to 3D multi-organ segmentation task using the BTCV challenge dataset.
104
+ For BTCV dataset, under Institutional Review Board (IRB) supervision, 50 abdomen CT scans of were randomly selected from a combination of an ongoing colorectal cancer chemotherapy trial, and a retrospective ventral hernia study. The 50 scans were captured during portal venous contrast phase with variable volume sizes (512 x 512 x 85 - 512 x 512 x 198) and field of views (approx. 280 x 280 x 280 mm3 - 500 x 500 x 650 mm3). The in-plane resolution varies from 0.54 x 0.54 mm2 to 0.98 x 0.98 mm2, while the slice thickness ranges from 2.5 mm to 5.0 mm.
105
+ Target: 13 abdominal organs including
106
+ Spleen
107
+ Right Kidney
108
+ Left Kidney
109
+ Gallbladder
110
+ Esophagus
111
+ Liver
112
+ Stomach
113
+ Aorta
114
+ IVC
115
+ Portal and Splenic Veins
116
+ Pancreas
117
+ Right adrenal gland
118
+ Left adrenal gland.
119
+ Modality: CT
120
+ Size: 30 3D volumes (24 Training + 6 Testing)
121
+ Challenge: BTCV MICCAI Challenge
122
+ The following figure shows image patches with the organ sub-regions that are annotated in the CT (top left) and the final labels for the whole dataset (right).
123
+ 1. Prepare BTCV dataset following [MONAI](https://docs.monai.io/en/stable/index.html) instruction:
124
+ Download BTCV dataset from: https://www.synapse.org/#!Synapse:syn3193805/wiki/217752. After you open the link, navigate to the "Files" tab, then download Abdomen/RawData.zip.
125
+ After downloading the zip file, unzip. Then put images from RawData/Training/img in ../data/imagesTr, and put labels from RawData/Training/label in ../data/labelsTr.
126
+ Download the json file for data splits from this [link](https://drive.google.com/file/d/1qcGh41p-rI3H_sQ0JwOAhNiQSXriQqGi/view). Place the JSON file at ../data/dataset_0.json.
127
+ 2. For the Adaptation, run: ``python train.py -net sam -mod sam_adpt -exp_name msa-3d-sam-btcv -sam_ckpt ./checkpoint/sam/sam_vit_b_01ec64.pth -image_size 1024 -b 8 -dataset decathlon -thd True -chunk 96 -data_path ../data -num_sample 4``
128
+ You can modify following parameters to save the memory usage: '-b' the batch size, '-chunk' the 3D depth (channel) for each sample, '-num_sample' number of samples for [Monai.RandCropByPosNegLabeld](https://docs.monai.io/en/stable/transforms.html#randcropbyposneglabeld), 'evl_chunk' the 3D channel split step in the evaluation, decrease it if out of memory in the evaluation.
129
+ ## Run on your own dataset
130
+ It is simple to run MSA on the other datasets. Just write another dataset class following which in `` ./dataset.py``. You only need to make sure you return a dict with
131
+ {
132
+ 'image': A tensor saving images with size [C,H,W] for 2D image, size [C, H, W, D] for 3D data.
133
+ D is the depth of 3D volume, C is the channel of a scan/frame, which is commonly 1 for CT, MRI, US data.
134
+ If processing, say like a colorful surgical video, D could the number of time frames, and C will be 3 for a RGB frame.
135
+ 'label': The target masks. Same size with the images except the resolutions (H and W).
136
+ 'p_label': The prompt label to decide positive/negative prompt. To simplify, you can always set 1 if don't need the negative prompt function.
137
+ 'pt': The prompt. Should be the same as that in SAM, e.g., a click prompt should be [x of click, y of click], one click for each scan/frame if using 3d data.
138
+ 'image_meta_dict': Optional. if you want save/visulize the result, you should put the name of the image in it with the key ['filename_or_obj'].
139
+ ...(others as you want)
140
+ }
141
+ Welcome to open issues if you meet any problem. It would be appreciated if you could contribute your dataset extensions. Unlike natural images, medical images vary a lot depending on different tasks. Expanding the generalization of a method requires everyone's efforts.
142
+
143
+ ### TODO LIST
144
+
145
+ - [ ] Jupyter tutorials.
146
+ - [x] Fix bugs in BTCV. Add BTCV example.
147
+ - [ ] Release REFUGE2, BraTs dataloaders and examples
148
+ - [x] Changable Image Resolution
149
+ - [ ] Fix bugs in Multi-GPU parallel
150
+ - [x] Sample and Vis in training
151
+ - [ ] Release general data pre-processing and post-processing
152
+ - [x] Release evaluation
153
+ - [ ] Deploy on HuggingFace
154
+ - [x] configuration
155
+ - [ ] Release SSL code
156
+ - [ ] Release Medical Adapter Zoo
157
+
158
+ ## Cite
159
+ ~~~
160
+ @misc{wu2023medical,
161
+ title={Medical SAM Adapter: Adapting Segment Anything Model for Medical Image Segmentation},
162
+ author={Junde Wu and Wei Ji and Yuanpei Liu and Huazhu Fu and Min Xu and Yanwu Xu and Yueming Jin},
163
+ year={2023},
164
+ eprint={2304.12620},
165
+ archivePrefix={arXiv},
166
+ primaryClass={cs.CV}
167
+ }
168
+ ~~~
169
+
170
+ ## Buy Me A Coffee 🥤😉
171
+ https://ko-fi.com/jundewu
172
+
173
+
174
+
175
+
176
+
__pycache__/cfg.cpython-37.pyc ADDED
Binary file (2.7 kB). View file
 
__pycache__/cfg.cpython-38.pyc ADDED
Binary file (2.59 kB). View file
 
__pycache__/dataset.cpython-37.pyc ADDED
Binary file (12.4 kB). View file
 
__pycache__/dataset.cpython-38.pyc ADDED
Binary file (7.39 kB). View file
 
__pycache__/function.cpython-37.pyc ADDED
Binary file (9.27 kB). View file
 
__pycache__/function.cpython-38.pyc ADDED
Binary file (8.86 kB). View file
 
__pycache__/utils.cpython-37.pyc ADDED
Binary file (31.5 kB). View file
 
__pycache__/utils.cpython-38.pyc ADDED
Binary file (30.5 kB). View file
 
cfg.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+
4
+ def parse_args():
5
+ parser = argparse.ArgumentParser()
6
+ parser.add_argument('-net', type=str, default='sam', help='net type')
7
+ parser.add_argument('-baseline', type=str, default='unet', help='baseline net type')
8
+ parser.add_argument('-encoder', type=str, default='default', help='encoder type')
9
+ parser.add_argument('-seg_net', type=str, default='transunet', help='net type')
10
+ parser.add_argument('-mod', type=str, default='sam_adpt', help='mod type:seg,cls,val_ad')
11
+ parser.add_argument('-exp_name', default='msa_test_isic', type=str, help='net type')
12
+ parser.add_argument('-type', type=str, default='map', help='condition type:ave,rand,rand_map')
13
+ parser.add_argument('-vis', type=int, default=None, help='visualization')
14
+ parser.add_argument('-reverse', type=bool, default=False, help='adversary reverse')
15
+ parser.add_argument('-pretrain', type=bool, default=False, help='adversary reverse')
16
+ parser.add_argument('-val_freq',type=int,default=5,help='interval between each validation')
17
+ parser.add_argument('-gpu', type=bool, default=True, help='use gpu or not')
18
+ parser.add_argument('-gpu_device', type=int, default=0, help='use which gpu')
19
+ parser.add_argument('-sim_gpu', type=int, default=0, help='split sim to this gpu')
20
+ parser.add_argument('-epoch_ini', type=int, default=1, help='start epoch')
21
+ parser.add_argument('-image_size', type=int, default=256, help='image_size')
22
+ parser.add_argument('-out_size', type=int, default=256, help='output_size')
23
+ parser.add_argument('-patch_size', type=int, default=2, help='patch_size')
24
+ parser.add_argument('-dim', type=int, default=512, help='dim_size')
25
+ parser.add_argument('-depth', type=int, default=1, help='depth')
26
+ parser.add_argument('-heads', type=int, default=16, help='heads number')
27
+ parser.add_argument('-mlp_dim', type=int, default=1024, help='mlp_dim')
28
+ parser.add_argument('-w', type=int, default=4, help='number of workers for dataloader')
29
+ parser.add_argument('-b', type=int, default=2, help='batch size for dataloader')
30
+ parser.add_argument('-s', type=bool, default=True, help='whether shuffle the dataset')
31
+ parser.add_argument('-warm', type=int, default=1, help='warm up training phase')
32
+ parser.add_argument('-lr', type=float, default=1e-4, help='initial learning rate')
33
+ parser.add_argument('-uinch', type=int, default=1, help='input channel of unet')
34
+ parser.add_argument('-imp_lr', type=float, default=3e-4, help='implicit learning rate')
35
+ parser.add_argument('-weights', type=str, default = 0, help='the weights file you want to test')
36
+ parser.add_argument('-base_weights', type=str, default = 0, help='the weights baseline')
37
+ parser.add_argument('-sim_weights', type=str, default = 0, help='the weights sim')
38
+ parser.add_argument('-distributed', default='none' ,type=str,help='multi GPU ids to use')
39
+ parser.add_argument('-dataset', default='isic' ,type=str,help='dataset name')
40
+ parser.add_argument('-sam_ckpt', default=None , help='sam checkpoint address')
41
+ parser.add_argument('-thd', type=bool, default=False , help='3d or not')
42
+ parser.add_argument('-chunk', type=int, default=None , help='crop volume depth')
43
+ parser.add_argument('-num_sample', type=int, default=4 , help='sample pos and neg')
44
+ parser.add_argument('-roi_size', type=int, default=96 , help='resolution of roi')
45
+ parser.add_argument('-evl_chunk', type=int, default=None , help='evaluation chunk')
46
+ parser.add_argument('-mid_dim', type=int, default=None , help='middle dim of adapter or the rank of lora matrix')
47
+ parser.add_argument('-multimask_output', type=int, default=1 , help='the number of masks output for multi-class segmentation, set 2 for REFUGE dataset.')
48
+ parser.add_argument(
49
+ '-data_path',
50
+ type=str,
51
+ default='../data',
52
+ help='The path of segmentation data')
53
+ # '../dataset/RIGA/DiscRegion'
54
+ # '../dataset/ISIC'
55
+ opt = parser.parse_args()
56
+
57
+ return opt
58
+
59
+ # required=True,
conf/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ dynamically load settings
2
+
3
+ author baiyu
4
+ """
5
+ import conf.global_settings as settings
6
+
7
+
8
+ class Settings:
9
+ def __init__(self, settings):
10
+
11
+ for attr in dir(settings):
12
+ if attr.isupper():
13
+ setattr(self, attr, getattr(settings, attr))
14
+
15
+ settings = Settings(settings)
conf/__pycache__/__init__.cpython-37.pyc ADDED
Binary file (622 Bytes). View file
 
conf/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (630 Bytes). View file
 
conf/__pycache__/global_settings.cpython-37.pyc ADDED
Binary file (726 Bytes). View file
 
conf/__pycache__/global_settings.cpython-38.pyc ADDED
Binary file (726 Bytes). View file
 
conf/global_settings.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ configurations for this project
2
+
3
+ author Junde
4
+ """
5
+ import os
6
+ from datetime import datetime
7
+
8
+ #CIFAR100 dataset path (python version)
9
+ #CIFAR100_PATH = '/nfs/private/cifar100/cifar-100-python'
10
+
11
+ #mean and std of cifar100 dataset
12
+ CIFAR100_TRAIN_MEAN = (0.5070751592371323, 0.48654887331495095, 0.4409178433670343)
13
+ CIFAR100_TRAIN_STD = (0.2673342858792401, 0.2564384629170883, 0.27615047132568404)
14
+
15
+ GLAUCOMA_TRAIN_MEAN = (0.5070751592371323, 0.48654887331495095, 0.4409178433670343)
16
+ GLAUCOMA_TRAIN_STD = (0.2673342858792401, 0.2564384629170883, 0.27615047132568404)
17
+
18
+ MASK_TRAIN_MEAN = (2.654204690220496/255)
19
+ MASK_TRAIN_STD = (21.46473779720519/255)
20
+
21
+ #CIFAR100_TEST_MEAN = (0.5088964127604166, 0.48739301317401956, 0.44194221124387256)
22
+ #CIFAR100_TEST_STD = (0.2682515741720801, 0.2573637364478126, 0.2770957707973042)
23
+
24
+ #directory to save weights file
25
+ CHECKPOINT_PATH = 'checkpoint'
26
+
27
+ #total training epoches
28
+ EPOCH = 100
29
+ step_size = 10
30
+ i = 1
31
+ MILESTONES = []
32
+ while i * 5 <= EPOCH:
33
+ MILESTONES.append(i* step_size)
34
+ i += 1
35
+
36
+ #initial learning rate
37
+ #INIT_LR = 0.1
38
+
39
+ #time of we run the script
40
+ TIME_NOW = datetime.now().strftime("%F_%H-%M-%S.%f")
41
+
42
+ #tensorboard log dir
43
+ LOG_DIR = 'runs'
44
+
45
+ #save weights file per SAVE_EPOCH epoch
46
+ SAVE_EPOCH = 10
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
dataset/__init__.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torchvision.transforms as transforms
3
+ from torch.utils.data import DataLoader, random_split
4
+ from torch.utils.data.sampler import SubsetRandomSampler
5
+
6
+ from utils import *
7
+
8
+ from .atlas import Atlas
9
+ from .brat import Brat
10
+ from .ddti import DDTI
11
+ from .isic import ISIC2016
12
+ from .kits import KITS
13
+ from .lidc import LIDC
14
+ from .lnq import LNQ
15
+ from .pendal import Pendal
16
+ from .refuge import REFUGE
17
+ from .segrap import SegRap
18
+ from .stare import STARE
19
+ from .toothfairy import ToothFairy
20
+ from .wbc import WBC
21
+
22
+
23
+ def get_dataloader(args):
24
+ transform_train = transforms.Compose([
25
+ transforms.Resize((args.image_size,args.image_size)),
26
+ transforms.ToTensor(),
27
+ ])
28
+
29
+ transform_train_seg = transforms.Compose([
30
+ transforms.Resize((args.out_size,args.out_size)),
31
+ transforms.ToTensor(),
32
+ ])
33
+
34
+ transform_test = transforms.Compose([
35
+ transforms.Resize((args.image_size, args.image_size)),
36
+ transforms.ToTensor(),
37
+ ])
38
+
39
+ transform_test_seg = transforms.Compose([
40
+ transforms.Resize((args.out_size,args.out_size)),
41
+ transforms.ToTensor(),
42
+ ])
43
+
44
+ if args.dataset == 'isic':
45
+ '''isic data'''
46
+ isic_train_dataset = ISIC2016(args, args.data_path, transform = transform_train, transform_msk= transform_train_seg, mode = 'Training')
47
+ isic_test_dataset = ISIC2016(args, args.data_path, transform = transform_test, transform_msk= transform_test_seg, mode = 'Test')
48
+
49
+ nice_train_loader = DataLoader(isic_train_dataset, batch_size=args.b, shuffle=True, num_workers=8, pin_memory=True)
50
+ nice_test_loader = DataLoader(isic_test_dataset, batch_size=args.b, shuffle=False, num_workers=8, pin_memory=True)
51
+ '''end'''
52
+
53
+ elif args.dataset == 'decathlon':
54
+ nice_train_loader, nice_test_loader, transform_train, transform_val, train_list, val_list = get_decath_loader(args)
55
+
56
+
57
+ elif args.dataset == 'REFUGE':
58
+ '''REFUGE data'''
59
+ refuge_train_dataset = REFUGE(args, args.data_path, transform = transform_train, transform_msk= transform_train_seg, mode = 'Training')
60
+ refuge_test_dataset = REFUGE(args, args.data_path, transform = transform_test, transform_msk= transform_test_seg, mode = 'Test')
61
+
62
+ nice_train_loader = DataLoader(refuge_train_dataset, batch_size=args.b, shuffle=True, num_workers=8, pin_memory=True)
63
+ nice_test_loader = DataLoader(refuge_test_dataset, batch_size=args.b, shuffle=False, num_workers=8, pin_memory=True)
64
+ '''end'''
65
+
66
+ elif args.dataset == 'LIDC':
67
+ '''LIDC data'''
68
+ # dataset = LIDC(data_path = args.data_path)
69
+ dataset = MyLIDC(args, data_path = args.data_path,transform = transform_train, transform_msk= transform_train_seg)
70
+
71
+ dataset_size = len(dataset)
72
+ indices = list(range(dataset_size))
73
+ split = int(np.floor(0.2 * dataset_size))
74
+ np.random.shuffle(indices)
75
+ train_sampler = SubsetRandomSampler(indices[split:])
76
+ test_sampler = SubsetRandomSampler(indices[:split])
77
+
78
+ nice_train_loader = DataLoader(dataset, batch_size=args.b, sampler=train_sampler, num_workers=8, pin_memory=True)
79
+ nice_test_loader = DataLoader(dataset, batch_size=args.b, sampler=test_sampler, num_workers=8, pin_memory=True)
80
+ '''end'''
81
+
82
+ elif args.dataset == 'DDTI':
83
+ '''DDTI data'''
84
+ refuge_train_dataset = DDTI(args, args.data_path, transform = transform_train, transform_msk= transform_train_seg, mode = 'Training')
85
+ refuge_test_dataset = DDTI(args, args.data_path, transform = transform_test, transform_msk= transform_test_seg, mode = 'Test')
86
+
87
+ nice_train_loader = DataLoader(refuge_train_dataset, batch_size=args.b, shuffle=True, num_workers=8, pin_memory=True)
88
+ nice_test_loader = DataLoader(refuge_test_dataset, batch_size=args.b, shuffle=False, num_workers=8, pin_memory=True)
89
+ '''end'''
90
+
91
+ elif args.dataset == 'Brat':
92
+ '''Brat data'''
93
+ dataset = Brat(args, data_path = args.data_path,transform = transform_train, transform_msk= transform_train_seg)
94
+
95
+ dataset_size = len(dataset)
96
+ indices = list(range(dataset_size))
97
+ split = int(np.floor(0.3 * dataset_size))
98
+ np.random.shuffle(indices)
99
+ train_sampler = SubsetRandomSampler(indices[split:])
100
+ test_sampler = SubsetRandomSampler(indices[:split])
101
+
102
+ nice_train_loader = DataLoader(dataset, batch_size=args.b, sampler=train_sampler, num_workers=8, pin_memory=True)
103
+ nice_test_loader = DataLoader(dataset, batch_size=args.b, sampler=test_sampler, num_workers=8, pin_memory=True)
104
+ '''end'''
105
+
106
+ elif args.dataset == 'STARE':
107
+ '''STARE data'''
108
+ # dataset = LIDC(data_path = args.data_path)
109
+ dataset = STARE(args, data_path = args.data_path, transform = transform_train, transform_msk= transform_train_seg)
110
+
111
+ dataset_size = len(dataset)
112
+ indices = list(range(dataset_size))
113
+ split = int(np.floor(0.2 * dataset_size))
114
+ np.random.shuffle(indices)
115
+ train_sampler = SubsetRandomSampler(indices[split:])
116
+ test_sampler = SubsetRandomSampler(indices[:split])
117
+
118
+ nice_train_loader = DataLoader(dataset, batch_size=args.b, sampler=train_sampler, num_workers=8, pin_memory=True)
119
+ nice_test_loader = DataLoader(dataset, batch_size=args.b, sampler=test_sampler, num_workers=8, pin_memory=True)
120
+ '''end'''
121
+
122
+ elif args.dataset == 'kits':
123
+ '''kits data'''
124
+ dataset = KITS(args, data_path = args.data_path,transform = transform_train, transform_msk= transform_train_seg)
125
+
126
+ dataset_size = len(dataset)
127
+ indices = list(range(dataset_size))
128
+ split = int(np.floor(0.3 * dataset_size))
129
+ np.random.shuffle(indices)
130
+ train_sampler = SubsetRandomSampler(indices[split:])
131
+ test_sampler = SubsetRandomSampler(indices[:split])
132
+
133
+ nice_train_loader = DataLoader(dataset, batch_size=args.b, sampler=train_sampler, num_workers=8, pin_memory=True)
134
+ nice_test_loader = DataLoader(dataset, batch_size=args.b, sampler=test_sampler, num_workers=8, pin_memory=True)
135
+ '''end'''
136
+
137
+ elif args.dataset == 'WBC':
138
+ '''WBC data'''
139
+ dataset = WBC(args, data_path = args.data_path,transform = transform_train, transform_msk= transform_train_seg)
140
+
141
+ dataset_size = len(dataset)
142
+ indices = list(range(dataset_size))
143
+ split = int(np.floor(0.3 * dataset_size))
144
+ np.random.shuffle(indices)
145
+ train_sampler = SubsetRandomSampler(indices[split:])
146
+ test_sampler = SubsetRandomSampler(indices[:split])
147
+
148
+ nice_train_loader = DataLoader(dataset, batch_size=args.b, sampler=train_sampler, num_workers=8, pin_memory=True)
149
+ nice_test_loader = DataLoader(dataset, batch_size=args.b, sampler=test_sampler, num_workers=8, pin_memory=True)
150
+ '''end'''
151
+
152
+ elif args.dataset == 'segrap':
153
+ '''segrap data'''
154
+ dataset = SegRap(args, data_path = args.data_path,transform = transform_train, transform_msk= transform_train_seg)
155
+
156
+ dataset_size = len(dataset)
157
+ indices = list(range(dataset_size))
158
+ split = int(np.floor(0.3 * dataset_size))
159
+ np.random.shuffle(indices)
160
+ train_sampler = SubsetRandomSampler(indices[split:])
161
+ test_sampler = SubsetRandomSampler(indices[:split])
162
+
163
+ nice_train_loader = DataLoader(dataset, batch_size=args.b, sampler=train_sampler, num_workers=8, pin_memory=True)
164
+ nice_test_loader = DataLoader(dataset, batch_size=args.b, sampler=test_sampler, num_workers=8, pin_memory=True)
165
+ '''end'''
166
+
167
+ elif args.dataset == 'toothfairy':
168
+ '''toothfairy data'''
169
+ dataset = ToothFairy(args, data_path = args.data_path,transform = transform_train, transform_msk= transform_train_seg)
170
+
171
+ dataset_size = len(dataset)
172
+ indices = list(range(dataset_size))
173
+ split = int(np.floor(0.3 * dataset_size))
174
+ np.random.shuffle(indices)
175
+ train_sampler = SubsetRandomSampler(indices[split:])
176
+ test_sampler = SubsetRandomSampler(indices[:split])
177
+
178
+ nice_train_loader = DataLoader(dataset, batch_size=args.b, sampler=train_sampler, num_workers=8, pin_memory=True)
179
+ nice_test_loader = DataLoader(dataset, batch_size=args.b, sampler=test_sampler, num_workers=8, pin_memory=True)
180
+ '''end'''
181
+
182
+ elif args.dataset == 'atlas':
183
+ '''atlas data'''
184
+ dataset = Atlas(args, data_path = args.data_path,transform = transform_train, transform_msk= transform_train_seg)
185
+
186
+ dataset_size = len(dataset)
187
+ indices = list(range(dataset_size))
188
+ split = int(np.floor(0.3 * dataset_size))
189
+ np.random.shuffle(indices)
190
+ train_sampler = SubsetRandomSampler(indices[split:])
191
+ test_sampler = SubsetRandomSampler(indices[:split])
192
+
193
+ nice_train_loader = DataLoader(dataset, batch_size=args.b, sampler=train_sampler, num_workers=8, pin_memory=True)
194
+ nice_test_loader = DataLoader(dataset, batch_size=args.b, sampler=test_sampler, num_workers=8, pin_memory=True)
195
+ '''end'''
196
+
197
+ elif args.dataset == 'pendal':
198
+ '''pendal data'''
199
+ dataset = Pendal(args, data_path = args.data_path,transform = transform_train, transform_msk= transform_train_seg)
200
+
201
+ dataset_size = len(dataset)
202
+ indices = list(range(dataset_size))
203
+ split = int(np.floor(0.3 * dataset_size))
204
+ np.random.shuffle(indices)
205
+ train_sampler = SubsetRandomSampler(indices[split:])
206
+ test_sampler = SubsetRandomSampler(indices[:split])
207
+
208
+ nice_train_loader = DataLoader(dataset, batch_size=args.b, sampler=train_sampler, num_workers=8, pin_memory=True)
209
+ nice_test_loader = DataLoader(dataset, batch_size=args.b, sampler=test_sampler, num_workers=8, pin_memory=True)
210
+ '''end'''
211
+
212
+ elif args.dataset == 'lnq':
213
+ '''lnq data'''
214
+ dataset = LNQ(args, data_path = args.data_path,transform = transform_train, transform_msk= transform_train_seg)
215
+
216
+ dataset_size = len(dataset)
217
+ indices = list(range(dataset_size))
218
+ split = int(np.floor(0.3 * dataset_size))
219
+ np.random.shuffle(indices)
220
+ train_sampler = SubsetRandomSampler(indices[split:])
221
+ test_sampler = SubsetRandomSampler(indices[:split])
222
+
223
+ nice_train_loader = DataLoader(dataset, batch_size=args.b, sampler=train_sampler, num_workers=8, pin_memory=True)
224
+ nice_test_loader = DataLoader(dataset, batch_size=args.b, sampler=test_sampler, num_workers=8, pin_memory=True)
225
+ '''end'''
226
+
227
+ else:
228
+ print("the dataset is not supported now!!!")
229
+
230
+ return nice_train_loader, nice_test_loader
dataset/__pycache__/__init__.cpython-37.pyc ADDED
Binary file (3.84 kB). View file
 
dataset/__pycache__/atlas.cpython-37.pyc ADDED
Binary file (1.96 kB). View file
 
dataset/__pycache__/brat.cpython-37.pyc ADDED
Binary file (2.37 kB). View file
 
dataset/__pycache__/ddti.cpython-37.pyc ADDED
Binary file (2.4 kB). View file
 
dataset/__pycache__/isic.cpython-37.pyc ADDED
Binary file (1.91 kB). View file
 
dataset/__pycache__/kits.cpython-37.pyc ADDED
Binary file (1.98 kB). View file
 
dataset/__pycache__/lidc.cpython-37.pyc ADDED
Binary file (3.97 kB). View file
 
dataset/__pycache__/pendal.cpython-37.pyc ADDED
Binary file (1.84 kB). View file
 
dataset/__pycache__/refuge.cpython-37.pyc ADDED
Binary file (3.95 kB). View file
 
dataset/__pycache__/segrap.cpython-37.pyc ADDED
Binary file (1.97 kB). View file
 
dataset/__pycache__/stare.cpython-37.pyc ADDED
Binary file (1.76 kB). View file
 
dataset/__pycache__/toothfairy.cpython-37.pyc ADDED
Binary file (1.94 kB). View file
 
dataset/__pycache__/wbc.cpython-37.pyc ADDED
Binary file (1.77 kB). View file
 
dataset/atlas.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import pickle
4
+
5
+ import nibabel as nib
6
+ import numpy as np
7
+ import pandas as pd
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from PIL import Image
11
+ from torch.utils.data import Dataset
12
+
13
+ from utils import generate_click_prompt, random_box, random_click
14
+
15
+
16
+ class Atlas(Dataset):
17
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
18
+
19
+
20
+ self.args = args
21
+ self.data_path = os.path.join(data_path,'train')
22
+ with open(os.path.join(self.data_path,'dataset.json'),'r') as file:
23
+ data = json.load(file)
24
+ self.name_list = data['training']
25
+ self.mode = mode
26
+ self.prompt = prompt
27
+ self.img_size = args.image_size
28
+
29
+ self.transform = transform
30
+ self.transform_msk = transform_msk
31
+
32
+ def __len__(self):
33
+ return len(self.name_list)
34
+
35
+
36
+ def __getitem__(self, index):
37
+ point_label = 1
38
+ label = 1
39
+
40
+ """Get the images"""
41
+ img_name = self.name_list[index]['image']
42
+ mask_name = self.name_list[index]['label']
43
+
44
+ img = nib.load(os.path.join(self.data_path,img_name)).get_fdata()
45
+ mask = nib.load(os.path.join(self.data_path,mask_name)).get_fdata()
46
+
47
+ mask[mask!=label] = 0
48
+ mask[mask==label] = 1
49
+ # if self.mode == 'Training':
50
+ # label = 0 if self.label_list[index] == 'benign' else 1
51
+ # else:
52
+ # label = int(self.label_list[index])
53
+ img = np.transpose(img,(1,2,0))
54
+ mask = np.transpose(mask,(1,2,0))
55
+
56
+ # img = np.resize(mask,(self.args.image_size, self.args.image_size,128))
57
+ # mask = np.resize(mask,(self.args.out_size,self.args.out_size,128))
58
+
59
+ # # img = np.resize(img,(self.args.image_size, self.args.image_size,img.shape[-1]))
60
+ # # mask = np.resize(mask,(self.args.out_size,self.args.out_size,mask.shape[-1]))
61
+
62
+ img = torch.tensor(img).unsqueeze(0)
63
+ mask = torch.tensor(mask).unsqueeze(0)
64
+
65
+ if self.prompt == 'click':
66
+ point_label, pt = random_click(np.array(mask), point_label)
67
+ # if self.transform:
68
+ # state = torch.get_rng_state()
69
+ # img = self.transform(img)
70
+ # torch.set_rng_state(state)
71
+
72
+ # if self.transform_msk:
73
+ # mask = self.transform_msk(mask)
74
+
75
+ # # if (inout == 0 and point_label == 1) or (inout == 1 and point_label == 0):
76
+ # # mask = 1 - mask
77
+ name = img_name
78
+ image_meta_dict = {'filename_or_obj':name}
79
+ return {
80
+ 'image':img,
81
+ 'label': mask,
82
+ 'p_label':point_label,
83
+ 'pt':pt,
84
+ 'image_meta_dict':image_meta_dict,
85
+ }
86
+
dataset/brat.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from PIL import Image
9
+ from torch.utils.data import Dataset
10
+
11
+ from utils import generate_click_prompt, random_box, random_click
12
+
13
+
14
+ class Brat(Dataset):
15
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
16
+
17
+ self.args = args
18
+ self.data_path = os.path.join(data_path,'Data')
19
+ self.name_list = os.listdir(self.data_path)
20
+ self.mode = mode
21
+ self.prompt = prompt
22
+ self.img_size = args.image_size
23
+
24
+ self.transform = transform
25
+ self.transform_msk = transform_msk
26
+
27
+ def __len__(self):
28
+ return len(self.name_list)
29
+
30
+ def load_all_levels(self,path):
31
+ import nibabel as nib
32
+ data_dir = os.path.join(self.data_path)
33
+ levels = ['t1','flair','t2','t1ce']
34
+ raw_image = [nib.load(os.path.join
35
+ (data_dir,path,path+'_'+level+'.nii.gz')).get_fdata() for level in levels]
36
+ raw_seg = nib.load(os.path.join(data_dir,path,path+'_seg.nii.gz')).get_fdata()
37
+
38
+ return raw_image[0], raw_seg
39
+
40
+ def __getitem__(self, index):
41
+ # if self.mode == 'Training':
42
+ # point_label = random.randint(0, 1)
43
+ # inout = random.randint(0, 1)
44
+ # else:
45
+ # inout = 1
46
+ # point_label = 1
47
+ point_label = 1
48
+ label = 4 # the class to be segmented
49
+
50
+ """Get the images"""
51
+ name = self.name_list[index]
52
+ img,mask = self.load_all_levels(name)
53
+
54
+ mask[mask!=label] = 0
55
+ mask[mask==label] = 1
56
+ # if self.mode == 'Training':
57
+ # label = 0 if self.label_list[index] == 'benign' else 1
58
+ # else:
59
+ # label = int(self.label_list[index])
60
+
61
+
62
+ img = np.resize(img,(self.args.image_size, self.args.image_size,img.shape[-1]))
63
+ mask = np.resize(mask,(self.args.out_size,self.args.out_size,mask.shape[-1]))
64
+
65
+ img = torch.tensor(img).unsqueeze(0)
66
+ mask = torch.tensor(mask).unsqueeze(0)
67
+ mask = torch.clamp(mask,min=0,max=1).int()
68
+
69
+ if self.prompt == 'click':
70
+ point_label, pt = random_click(np.array(mask), point_label)
71
+ # if self.transform:
72
+ # state = torch.get_rng_state()
73
+ # img = self.transform(img)
74
+ # torch.set_rng_state(state)
75
+
76
+ # if self.transform_msk:
77
+ # mask = self.transform_msk(mask)
78
+
79
+ # # if (inout == 0 and point_label == 1) or (inout == 1 and point_label == 0):
80
+ # # mask = 1 - mask
81
+ name = name.split('/')[-1].split(".jpg")[0]
82
+ image_meta_dict = {'filename_or_obj':name}
83
+ return {
84
+ 'image':img,
85
+ 'label': mask,
86
+ 'p_label':point_label,
87
+ 'pt':pt,
88
+ 'image_meta_dict':image_meta_dict,
89
+ }
90
+
dataset/ddti.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import cv2
4
+ import numpy as np
5
+ import pandas as pd
6
+ import torch
7
+ from PIL import Image
8
+ from torch.utils.data import Dataset
9
+
10
+ from utils import random_box, random_click
11
+
12
+
13
+ class DDTI(Dataset):
14
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
15
+
16
+ self.name_list = os.listdir(os.path.join(data_path,mode,'images'))
17
+ self.data_path = data_path
18
+ self.mode = mode
19
+ self.prompt = prompt
20
+ self.img_size = args.image_size
21
+
22
+ self.transform = transform
23
+ self.transform_msk = transform_msk
24
+
25
+ def __len__(self):
26
+ return len(self.name_list)
27
+
28
+ def find_connected_components(self,mask):
29
+ mask = np.clip(mask,0,1)
30
+ num_labels, labels = cv2.connectedComponents(mask.astype(np.uint8))
31
+ point = []
32
+ point_labels = []
33
+
34
+ for label in range(1, num_labels):
35
+ component_mask = np.where(labels == label, 1, 0)
36
+ area = np.sum(component_mask)
37
+
38
+ if area > 400:
39
+ point_label, random_point = random_click(component_mask)
40
+ point.append(random_point)
41
+ point_labels.append(point_label)
42
+ # print(f"Random point in component {label}: {random_point}, label: {point_labels}")
43
+ if(len(point)==1):
44
+ point.append(point[0])
45
+ point_labels.append(point_labels[0])
46
+ if(len(point)>2):
47
+ point = point[:2]
48
+ point_labels = point_labels[:2]
49
+ point = np.array(point)
50
+ point_labels = np.array(point_labels)
51
+ return point_labels,point
52
+
53
+ def __getitem__(self, index):
54
+ point_label = 1
55
+
56
+ """Get the images"""
57
+ name = self.name_list[index]
58
+ img_path = os.path.join(self.data_path, self.mode, 'images', name)
59
+ msk_path = os.path.join(self.data_path, self.mode, 'masks', name)
60
+
61
+ img = Image.open(img_path).convert('RGB')
62
+ mask = Image.open(msk_path).convert('L')
63
+
64
+ # if self.mode == 'Training':
65
+ # label = 0 if self.label_list[index] == 'benign' else 1
66
+ # else:
67
+ # label = int(self.label_list[index])
68
+
69
+ newsize = (self.img_size, self.img_size)
70
+ mask = mask.resize(newsize)
71
+
72
+ if self.prompt == 'click':
73
+ # two prompt
74
+ point_label, pt = self.find_connected_components(np.array(mask))
75
+ # one prompt
76
+ # point_label, pt = random_click(np.array(mask) / 255, point_label)
77
+
78
+ if self.transform:
79
+ state = torch.get_rng_state()
80
+ img = self.transform(img)
81
+ torch.set_rng_state(state)
82
+
83
+
84
+ if self.transform_msk:
85
+ mask = self.transform_msk(mask)
86
+
87
+ # if (inout == 0 and point_label == 1) or (inout == 1 and point_label == 0):
88
+ # mask = 1 - mask
89
+ mask = torch.clamp(mask,min=0,max=1).int()
90
+
91
+ name = name.split('/')[-1].split(".jpg")[0]
92
+ image_meta_dict = {'filename_or_obj':name}
93
+ return {
94
+ 'image':img,
95
+ 'label': mask,
96
+ 'p_label':point_label,
97
+ 'pt':pt,
98
+ 'image_meta_dict':image_meta_dict,
99
+ }
dataset/isic.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import torch
6
+ from PIL import Image
7
+ from torch.utils.data import Dataset
8
+
9
+ from utils import random_box, random_click
10
+
11
+
12
+ class ISIC2016(Dataset):
13
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
14
+
15
+ df = pd.read_csv(os.path.join(data_path, 'ISBI2016_ISIC_Part1_' + mode + '_GroundTruth.csv'), encoding='gbk')
16
+ self.name_list = df.iloc[:,1].tolist()
17
+ self.label_list = df.iloc[:,2].tolist()
18
+ self.data_path = data_path
19
+ self.mode = mode
20
+ self.prompt = prompt
21
+ self.img_size = args.image_size
22
+
23
+ self.transform = transform
24
+ self.transform_msk = transform_msk
25
+
26
+ def __len__(self):
27
+ return len(self.name_list)
28
+
29
+ def __getitem__(self, index):
30
+ # if self.mode == 'Training':
31
+ # point_label = random.randint(0, 1)
32
+ # inout = random.randint(0, 1)
33
+ # else:
34
+ # inout = 1
35
+ # point_label = 1
36
+ point_label = 1
37
+
38
+ """Get the images"""
39
+ name = self.name_list[index]
40
+ img_path = os.path.join(self.data_path, name)
41
+
42
+ mask_name = self.label_list[index]
43
+ msk_path = os.path.join(self.data_path, mask_name)
44
+
45
+ img = Image.open(img_path).convert('RGB')
46
+ mask = Image.open(msk_path).convert('L')
47
+
48
+ # if self.mode == 'Training':
49
+ # label = 0 if self.label_list[index] == 'benign' else 1
50
+ # else:
51
+ # label = int(self.label_list[index])
52
+
53
+ newsize = (self.img_size, self.img_size)
54
+ mask = mask.resize(newsize)
55
+
56
+ if self.prompt == 'click':
57
+ point_label, pt = random_click(np.array(mask) / 255, point_label)
58
+
59
+ if self.transform:
60
+ state = torch.get_rng_state()
61
+ img = self.transform(img)
62
+ torch.set_rng_state(state)
63
+
64
+
65
+ if self.transform_msk:
66
+ mask = self.transform_msk(mask).int()
67
+
68
+ # if (inout == 0 and point_label == 1) or (inout == 1 and point_label == 0):
69
+ # mask = 1 - mask
70
+ name = name.split('/')[-1].split(".jpg")[0]
71
+ image_meta_dict = {'filename_or_obj':name}
72
+ return {
73
+ 'image':img,
74
+ 'label': mask,
75
+ 'p_label':point_label,
76
+ 'pt':pt,
77
+ 'image_meta_dict':image_meta_dict,
78
+ }
dataset/kits.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+
4
+ import nibabel as nib
5
+ import numpy as np
6
+ import pandas as pd
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from PIL import Image
10
+ from torch.utils.data import Dataset
11
+
12
+ from utils import generate_click_prompt, random_box, random_click
13
+
14
+
15
+ class KITS(Dataset):
16
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
17
+
18
+
19
+ self.args = args
20
+ self.data_path = os.path.join(data_path,'kits21','data')
21
+ self.name_list = os.listdir(self.data_path)
22
+ self.mode = mode
23
+ self.prompt = prompt
24
+ self.img_size = args.image_size
25
+
26
+ self.transform = transform
27
+ self.transform_msk = transform_msk
28
+
29
+ def __len__(self):
30
+ return len(self.name_list)
31
+
32
+
33
+ def __getitem__(self, index):
34
+ # if self.mode == 'Training':
35
+ # point_label = random.randint(0, 1)
36
+ # inout = random.randint(0, 1)
37
+ # else:
38
+ # inout = 1
39
+ # point_label = 1
40
+ point_label = 1
41
+
42
+
43
+ """Get the images"""
44
+ name = self.name_list[index]
45
+ img = nib.load(os.path.join(self.data_path,name,'imaging.nii.gz')).get_fdata()
46
+ mask = nib.load(os.path.join(self.data_path,name,'aggregated_AND_seg.nii.gz')).get_fdata()
47
+
48
+ mask = np.clip(mask,0,1)
49
+ # if self.mode == 'Training':
50
+ # label = 0 if self.label_list[index] == 'benign' else 1
51
+ # else:
52
+ # label = int(self.label_list[index])
53
+ img = np.transpose(img,(1,2,0))
54
+ mask = np.transpose(mask,(1,2,0))
55
+
56
+ # img = np.resize(mask,(self.args.image_size, self.args.image_size,img.shape[-1]))
57
+ # mask = np.resize(mask,(self.args.out_size,self.args.out_size,mask.shape[-1]))
58
+
59
+ img = np.resize(img,(self.args.image_size, self.args.image_size,img.shape[-1]))
60
+ mask = np.resize(mask,(self.args.out_size,self.args.out_size,mask.shape[-1]))
61
+
62
+ img = torch.tensor(img).unsqueeze(0)
63
+ mask = torch.tensor(mask).unsqueeze(0)
64
+ mask = torch.clamp(mask,min=0,max=1).int()
65
+
66
+ if self.prompt == 'click':
67
+ point_label, pt = random_click(np.array(mask), point_label)
68
+ # if self.transform:
69
+ # state = torch.get_rng_state()
70
+ # img = self.transform(img)
71
+ # torch.set_rng_state(state)
72
+
73
+ # if self.transform_msk:
74
+ # mask = self.transform_msk(mask)
75
+
76
+ # # if (inout == 0 and point_label == 1) or (inout == 1 and point_label == 0):
77
+ # # mask = 1 - mask
78
+ name = name.split('/')[-1].split(".jpg")[0]
79
+ image_meta_dict = {'filename_or_obj':name}
80
+ return {
81
+ 'image':img,
82
+ 'label': mask,
83
+ 'p_label':point_label,
84
+ 'pt':pt,
85
+ 'image_meta_dict':image_meta_dict,
86
+ }
87
+
dataset/lidc.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from PIL import Image
9
+ from torch.utils.data import Dataset
10
+
11
+ from utils import random_box, random_click
12
+
13
+
14
+ class LIDC(Dataset):
15
+ names = []
16
+ images = []
17
+ labels = []
18
+ series_uid = []
19
+
20
+ def __init__(self, data_path, transform=None, transform_msk = None, prompt = 'click'):
21
+ self.prompt = prompt
22
+ self.transform = transform
23
+ self.transform_msk = transform_msk
24
+
25
+ max_bytes = 2**31 - 1
26
+ data = {}
27
+ for file in os.listdir(data_path):
28
+ filename = os.fsdecode(file)
29
+ if '.pickle' in filename:
30
+ file_path = data_path + filename
31
+ bytes_in = bytearray(0)
32
+ input_size = os.path.getsize(file_path)
33
+ with open(file_path, 'rb') as f_in:
34
+ for _ in range(0, input_size, max_bytes):
35
+ bytes_in += f_in.read(max_bytes)
36
+ new_data = pickle.loads(bytes_in)
37
+ data.update(new_data)
38
+
39
+
40
+ for key, value in data.items():
41
+ self.names.append(key)
42
+ self.images.append(value['image'].astype(float))
43
+ self.labels.append(value['masks'])
44
+ self.series_uid.append(value['series_uid'])
45
+
46
+ assert (len(self.images) == len(self.labels) == len(self.series_uid))
47
+
48
+ for img in self.images:
49
+ assert np.max(img) <= 1 and np.min(img) >= 0
50
+ for label in self.labels:
51
+ assert np.max(label) <= 1 and np.min(label) >= 0
52
+
53
+ del new_data
54
+ del data
55
+
56
+ def __len__(self):
57
+ return len(self.images)
58
+
59
+ def __getitem__(self, index):
60
+
61
+ point_label = 1
62
+
63
+ """Get the images"""
64
+ img = np.expand_dims(self.images[index], axis=0)
65
+ name = self.names[index]
66
+ multi_rater = self.labels[index]
67
+
68
+ # first click is the target most agreement among raters, otherwise, background agreement
69
+ if self.prompt == 'click':
70
+ point_label, pt = random_click(np.array(np.mean(np.stack(multi_rater), axis=0)) / 255, point_label)
71
+
72
+ # Convert image (ensure three channels) and multi-rater labels to torch tensors
73
+ img = torch.from_numpy(img).type(torch.float32)
74
+ img = img.repeat(3, 1, 1)
75
+ multi_rater = [torch.from_numpy(single_rater).type(torch.float32) for single_rater in multi_rater]
76
+
77
+ multi_rater = torch.stack(multi_rater, dim=0)
78
+ multi_rater = multi_rater.unsqueeze(1)
79
+
80
+ if self.prompt == 'box':
81
+ x_min, x_max, y_min, y_max = random_box(multi_rater)
82
+ box = [x_min, x_max, y_min, y_max]
83
+
84
+ mask = multi_rater.mean(dim=0) # average
85
+
86
+ image_meta_dict = {'filename_or_obj':name}
87
+ return {
88
+ 'image':img,
89
+ 'multi_rater': multi_rater,
90
+ 'label': mask,
91
+ 'p_label':point_label,
92
+ 'pt':pt,
93
+ 'box': box,
94
+ 'image_meta_dict':image_meta_dict,
95
+ }
96
+
dataset/lnq.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import pickle
4
+
5
+ import nibabel as nib
6
+ import numpy as np
7
+ import pandas as pd
8
+ import SimpleITK as sitk
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from PIL import Image
12
+ from torch.utils.data import Dataset
13
+
14
+ from utils import generate_click_prompt, random_box, random_click
15
+
16
+
17
+ class LNQ(Dataset):
18
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
19
+
20
+
21
+ self.args = args
22
+ self.data_path = os.path.join(data_path,'train')
23
+
24
+ files = os.listdir(self.data_path)
25
+
26
+ self.name_list = [file for file in files if file.endswith('.png')]
27
+ self.mode = mode
28
+ self.prompt = prompt
29
+ self.img_size = args.image_size
30
+
31
+ self.transform = transform
32
+ self.transform_msk = transform_msk
33
+
34
+ def __len__(self):
35
+ return len(self.name_list)
36
+
37
+
38
+ def __getitem__(self, index):
39
+ point_label = 1
40
+ label = 1
41
+
42
+ """Get the images"""
43
+ name = self.name_list[index].split('.')[0]
44
+ img_name = name + '-ct.nrrd'
45
+ mask_name = name + '-seg.nrrd'
46
+
47
+ img = sitk.GetArrayFromImage(sitk.ReadImage(os.path.join(self.data_path,img_name)))
48
+ mask = sitk.GetArrayFromImage(sitk.ReadImage(os.path.join(self.data_path,mask_name)))
49
+
50
+ mask[mask!=label] = 0
51
+ mask[mask==label] = 1
52
+ # if self.mode == 'Training':
53
+ # label = 0 if self.label_list[index] == 'benign' else 1
54
+ # else:
55
+ # label = int(self.label_list[index])
56
+ img = np.transpose(img,(1,2,0))
57
+ mask = np.transpose(mask,(1,2,0))
58
+
59
+ # img = np.resize(mask,(self.args.image_size, self.args.image_size,128))
60
+ # mask = np.resize(mask,(self.args.out_size,self.args.out_size,128))
61
+
62
+ # # img = np.resize(img,(self.args.image_size, self.args.image_size,img.shape[-1]))
63
+ # # mask = np.resize(mask,(self.args.out_size,self.args.out_size,mask.shape[-1]))
64
+
65
+ img = torch.tensor(img).unsqueeze(0).int()
66
+ mask = torch.tensor(mask).unsqueeze(0).int()
67
+
68
+ if self.prompt == 'click':
69
+ point_label, pt = random_click(np.array(mask), point_label)
70
+
71
+ name = img_name
72
+ image_meta_dict = {'filename_or_obj':name}
73
+ return {
74
+ 'image':img,
75
+ 'label': mask,
76
+ 'p_label':point_label,
77
+ 'pt':pt,
78
+ 'image_meta_dict':image_meta_dict,
79
+ }
80
+
dataset/pendal.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+
4
+ import nibabel as nib
5
+ import numpy as np
6
+ import pandas as pd
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from PIL import Image
10
+ from torch.utils.data import Dataset
11
+
12
+ from utils import generate_click_prompt, random_box, random_click
13
+
14
+
15
+ class Pendal(Dataset):
16
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
17
+
18
+ self.args = args
19
+ self.data_path = data_path
20
+ self.name_list = os.listdir(os.path.join(self.data_path,'Images'))
21
+ self.mode = mode
22
+ self.prompt = prompt
23
+ self.img_size = args.image_size
24
+
25
+ self.transform = transform
26
+ self.transform_msk = transform_msk
27
+
28
+ def __len__(self):
29
+ return len(self.name_list)
30
+
31
+
32
+ def __getitem__(self, index):
33
+ # if self.mode == 'Training':
34
+ # point_label = random.randint(0, 1)
35
+ # inout = random.randint(0, 1)
36
+ # else:
37
+ # inout = 1
38
+ # point_label = 1
39
+ point_label = 1
40
+
41
+ """Get the images"""
42
+ name = self.name_list[index]
43
+ img = Image.open(os.path.join(self.data_path, 'Images',name)).convert('RGB')
44
+ mask = Image.open(os.path.join(self.data_path, 'Segmentation1',name)).convert('L')
45
+
46
+ mask = np.array(mask)
47
+ mask[mask==mask.min()]=0
48
+ mask[mask>0] = 255
49
+
50
+ if self.prompt == 'click':
51
+ point_label, pt = random_click(np.array(mask) / 255, point_label)
52
+
53
+ if self.transform:
54
+ state = torch.get_rng_state()
55
+ img = self.transform(img)
56
+ torch.set_rng_state(state)
57
+
58
+
59
+ if self.transform_msk:
60
+ mask = Image.fromarray(mask)
61
+ mask = self.transform_msk(mask).int()
62
+
63
+ image_meta_dict = {'filename_or_obj':name}
64
+ return {
65
+ 'image':img,
66
+ 'label': mask,
67
+ 'p_label':point_label,
68
+ 'pt':pt,
69
+ 'image_meta_dict':image_meta_dict,
70
+ }
71
+
dataset/refuge.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from PIL import Image
8
+ from torch.utils.data import Dataset
9
+
10
+ from utils import random_box, random_click
11
+
12
+
13
+ class REFUGE(Dataset):
14
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'none', plane = False):
15
+ self.data_path = data_path
16
+ self.subfolders = [f.path for f in os.scandir(os.path.join(data_path, mode + '-400')) if f.is_dir()]
17
+ self.mode = mode
18
+ self.prompt = prompt
19
+ self.img_size = args.image_size
20
+ self.mask_size = args.out_size
21
+
22
+ self.transform = transform
23
+ self.transform_msk = transform_msk
24
+
25
+ def __len__(self):
26
+ return len(self.subfolders)
27
+
28
+ def __getitem__(self, index):
29
+ point_label = 1
30
+
31
+ """Get the images"""
32
+ subfolder = self.subfolders[index]
33
+ name = subfolder.split('/')[-1]
34
+
35
+ # raw image and raters path
36
+ img_path = os.path.join(subfolder, name + '.jpg')
37
+ multi_rater_cup_path = [os.path.join(subfolder, name + '_seg_cup_' + str(i) + '.png') for i in range(1, 8)]
38
+ multi_rater_disc_path = [os.path.join(subfolder, name + '_seg_disc_' + str(i) + '.png') for i in range(1, 8)]
39
+
40
+ # raw image and raters images
41
+ img = Image.open(img_path).convert('RGB')
42
+ multi_rater_cup = [Image.open(path).convert('L') for path in multi_rater_cup_path]
43
+ multi_rater_disc = [Image.open(path).convert('L') for path in multi_rater_disc_path]
44
+
45
+ # resize raters images for generating initial point click
46
+ newsize = (self.img_size, self.img_size)
47
+ multi_rater_cup_np = [np.array(single_rater.resize(newsize)) for single_rater in multi_rater_cup]
48
+ multi_rater_disc_np = [np.array(single_rater.resize(newsize)) for single_rater in multi_rater_disc]
49
+
50
+ # first click is the target agreement among most raters
51
+ if self.prompt == 'click':
52
+ point_label, pt = random_click(np.array(np.mean(np.stack(multi_rater_cup_np), axis=0)) / 255, point_label)
53
+ point_label, pt_disc = random_click(np.array(np.mean(np.stack(multi_rater_disc_np), axis=0)) / 255, point_label)
54
+ else:
55
+ # you may want to get rid of click prompts
56
+ pt = np.array([0, 0], dtype=np.int32)
57
+
58
+ if self.transform:
59
+ state = torch.get_rng_state()
60
+ img = self.transform(img)
61
+ multi_rater_cup = [torch.as_tensor((self.transform(single_rater) >0.5).float(), dtype=torch.float32) for single_rater in multi_rater_cup]
62
+ multi_rater_cup = torch.stack(multi_rater_cup, dim=0)
63
+ # transform to mask size (out_size) for mask define
64
+ mask_cup = F.interpolate(multi_rater_cup, size=(self.mask_size, self.mask_size), mode='bilinear', align_corners=False).mean(dim=0)
65
+
66
+ multi_rater_disc = [torch.as_tensor((self.transform(single_rater) >0.5).float(), dtype=torch.float32) for single_rater in multi_rater_disc]
67
+ multi_rater_disc = torch.stack(multi_rater_disc, dim=0)
68
+ mask_disc = F.interpolate(multi_rater_disc, size=(self.mask_size, self.mask_size), mode='bilinear', align_corners=False).mean(dim=0)
69
+ torch.set_rng_state(state)
70
+
71
+ mask = torch.concat([mask_cup, mask_disc], dim=0)
72
+
73
+ if self.prompt == 'box':
74
+ x_min_cup, x_max_cup, y_min_cup, y_max_cup = random_box(multi_rater_cup)
75
+ box_cup = [x_min_cup, x_max_cup, y_min_cup, y_max_cup]
76
+ x_min_disc, x_max_disc, y_min_disc, y_max_disc = random_box(multi_rater_disc)
77
+ box_disc = [x_min_disc, x_max_disc, y_min_disc, y_max_disc]
78
+ else:
79
+ # you may want to get rid of box prompts
80
+ box_cup = [0, 0, 0, 0]
81
+ box_disc = [0, 0, 0, 0]
82
+
83
+ image_meta_dict = {'filename_or_obj':name}
84
+ return {
85
+ 'image':img,
86
+ 'label': mask,
87
+ 'p_label':point_label,
88
+ 'pt':pt,
89
+ 'box': box_cup,
90
+ 'image_meta_dict':image_meta_dict,
91
+ }
dataset/segrap.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+
4
+ import nibabel as nib
5
+ import numpy as np
6
+ import pandas as pd
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from PIL import Image
10
+ from torch.utils.data import Dataset
11
+
12
+ from utils import generate_click_prompt, random_box, random_click
13
+
14
+
15
+ class SegRap(Dataset):
16
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
17
+
18
+ self.args = args
19
+ self.data_path = data_path
20
+ self.name_list = os.listdir(os.path.join(self.data_path,'SegRap2023_Training_Set_120cases_OneHot_Labels','Task001'))
21
+ self.mode = mode
22
+ self.prompt = prompt
23
+ self.img_size = args.image_size
24
+
25
+ self.transform = transform
26
+ self.transform_msk = transform_msk
27
+
28
+ def __len__(self):
29
+ return len(self.name_list)
30
+
31
+
32
+ def __getitem__(self, index):
33
+ # if self.mode == 'Training':
34
+ # point_label = random.randint(0, 1)
35
+ # inout = random.randint(0, 1)
36
+ # else:
37
+ # inout = 1
38
+ # point_label = 1
39
+ point_label = 1
40
+ label = 1 # 待分割的类别
41
+
42
+ """Get the images"""
43
+ name = self.name_list[index].split('.')[0]
44
+ img = nib.load(os.path.join(self.data_path,'SegRap2023_Training_Set_120cases',name,'image.nii.gz')).get_fdata()
45
+ mask = nib.load(os.path.join(self.data_path,'SegRap2023_Training_Set_120cases_OneHot_Labels','Task001',name+'.nii.gz')).get_fdata()
46
+
47
+ img = np.resize(img,(self.args.image_size, self.args.image_size,img.shape[-1]))
48
+ mask = np.resize(mask,(self.args.out_size,self.args.out_size,mask.shape[-1]))
49
+ mask[mask!=label] = 0
50
+ mask[mask==label] = 1
51
+
52
+ img = torch.tensor(img).unsqueeze(0)
53
+ mask = torch.tensor(mask).unsqueeze(0).int()
54
+ if self.prompt == 'click':
55
+ point_label, pt = random_click(np.array(mask), point_label)
56
+
57
+ image_meta_dict = {'filename_or_obj':name}
58
+ return {
59
+ 'image':img,
60
+ 'label': mask,
61
+ 'p_label':point_label,
62
+ 'pt':pt,
63
+ 'image_meta_dict':image_meta_dict,
64
+ }
65
+
dataset/stare.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import torch
6
+ from PIL import Image
7
+ from torch.utils.data import Dataset
8
+
9
+ from utils import random_box, random_click
10
+
11
+
12
+ class STARE(Dataset):
13
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
14
+
15
+ self.data_path = data_path
16
+ self.name_list = os.listdir(os.path.join(data_path,'masks'))
17
+ self.prompt = prompt
18
+ self.img_size = args.image_size
19
+
20
+ self.transform = transform
21
+ self.transform_msk = transform_msk
22
+
23
+ def __len__(self):
24
+ return len(self.name_list)
25
+
26
+ def __getitem__(self, index):
27
+ # if self.mode == 'Training':
28
+ # point_label = random.randint(0, 1)
29
+ # inout = random.randint(0, 1)
30
+ # else:
31
+ # inout = 1
32
+ # point_label = 1
33
+ point_label = 1
34
+
35
+ """Get the images"""
36
+ name = self.name_list[index].split('.')[0]
37
+
38
+ img_path = os.path.join(self.data_path, 'images',name+'.ppm')
39
+
40
+ msk_path = os.path.join(self.data_path, 'masks', name+'.ah.ppm')
41
+
42
+ img = Image.open(img_path).convert('RGB')
43
+ mask = Image.open(msk_path).convert('L')
44
+
45
+ # if self.mode == 'Training':
46
+ # label = 0 if self.label_list[index] == 'benign' else 1
47
+ # else:
48
+ # label = int(self.label_list[index])
49
+
50
+ newsize = (self.img_size, self.img_size)
51
+ mask = mask.resize(newsize)
52
+
53
+ if self.prompt == 'click':
54
+ point_label, pt = random_click(np.array(mask) / 255, point_label)
55
+
56
+ if self.transform:
57
+ state = torch.get_rng_state()
58
+ img = self.transform(img)
59
+ torch.set_rng_state(state)
60
+
61
+
62
+ if self.transform_msk:
63
+ mask = self.transform_msk(mask).int()
64
+
65
+ # if (inout == 0 and point_label == 1) or (inout == 1 and point_label == 0):
66
+ # mask = 1 - mask
67
+ name = name.split('/')[-1].split(".jpg")[0]
68
+ image_meta_dict = {'filename_or_obj':name}
69
+ return {
70
+ 'image':img,
71
+ 'label': mask,
72
+ 'p_label':point_label,
73
+ 'pt':pt,
74
+ 'image_meta_dict':image_meta_dict,
75
+ }
dataset/toothfairy.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+
4
+ import nibabel as nib
5
+ import numpy as np
6
+ import pandas as pd
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from PIL import Image
10
+ from torch.utils.data import Dataset
11
+
12
+ from utils import generate_click_prompt, random_box, random_click
13
+
14
+
15
+ class ToothFairy(Dataset):
16
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
17
+
18
+
19
+ self.args = args
20
+ self.data_path = os.path.join(data_path,'Dataset')
21
+ self.name_list = os.listdir(self.data_path)
22
+ self.mode = mode
23
+ self.prompt = prompt
24
+ self.img_size = args.image_size
25
+
26
+ self.transform = transform
27
+ self.transform_msk = transform_msk
28
+
29
+ def __len__(self):
30
+ return len(self.name_list)
31
+
32
+
33
+ def __getitem__(self, index):
34
+ point_label = 1
35
+
36
+
37
+ """Get the images"""
38
+ name = self.name_list[index]
39
+ img = np.load(os.path.join(self.data_path,name,'data.npy'))
40
+ mask = np.load(os.path.join(self.data_path,name,'gt_sparse.npy'))
41
+
42
+ # if self.mode == 'Training':
43
+ # label = 0 if self.label_list[index] == 'benign' else 1
44
+ # else:
45
+ # label = int(self.label_list[index])
46
+ img = np.transpose(img,(1,2,0))
47
+ mask = np.transpose(mask,(1,2,0))
48
+
49
+ # img = np.resize(mask,(self.args.image_size, self.args.image_size,img.shape[-1]))
50
+ # mask = np.resize(mask,(self.args.out_size,self.args.out_size,mask.shape[-1]))
51
+
52
+ img = np.resize(img,(self.args.image_size, self.args.image_size,img.shape[-1]))
53
+ mask = np.resize(mask,(self.args.out_size,self.args.out_size,mask.shape[-1]))
54
+
55
+ img = torch.tensor(img).unsqueeze(0)
56
+ mask = torch.tensor(mask).unsqueeze(0)
57
+ mask = torch.clamp(mask,min=0,max=1).int()
58
+
59
+ if self.prompt == 'click':
60
+ point_label, pt = random_click(np.array(mask), point_label)
61
+ # if self.transform:
62
+ # state = torch.get_rng_state()
63
+ # img = self.transform(img)
64
+ # torch.set_rng_state(state)
65
+
66
+ # if self.transform_msk:
67
+ # mask = self.transform_msk(mask)
68
+
69
+ # # if (inout == 0 and point_label == 1) or (inout == 1 and point_label == 0):
70
+ # # mask = 1 - mask
71
+ name = name.split('/')[-1].split(".jpg")[0]
72
+ image_meta_dict = {'filename_or_obj':name}
73
+ return {
74
+ 'image':img,
75
+ 'label': mask,
76
+ 'p_label':point_label,
77
+ 'pt':pt,
78
+ 'image_meta_dict':image_meta_dict,
79
+ }
80
+
dataset/wbc.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ import torch
7
+ from PIL import Image
8
+ from torch.utils.data import Dataset
9
+
10
+ from utils import random_box, random_click
11
+
12
+
13
+ class WBC(Dataset):
14
+ def __init__(self, args, data_path , transform = None, transform_msk = None, mode = 'Training',prompt = 'click', plane = False):
15
+
16
+ self.data_path = os.path.join(data_path,'Dataset1')
17
+ self.name_list = glob.glob(self.data_path + "/*.bmp")
18
+ self.mode = mode
19
+ self.prompt = prompt
20
+ self.img_size = args.image_size
21
+
22
+ self.transform = transform
23
+ self.transform_msk = transform_msk
24
+
25
+ def __len__(self):
26
+ return len(self.name_list)
27
+
28
+ def __getitem__(self, index):
29
+ point_label = 1 # available: 1 2
30
+
31
+ """Get the images"""
32
+ name = os.path.basename(self.name_list[index]).split('.')[0]
33
+
34
+ img_path = os.path.join(self.data_path, name + '.bmp')
35
+ msk_path = os.path.join(self.data_path, name + '.png')
36
+
37
+ img = Image.open(img_path).convert('RGB')
38
+ mask = Image.open(msk_path).convert('L')
39
+
40
+ mask = np.array(mask) // 127
41
+ mask[mask!=point_label] = 0
42
+ mask[mask==point_label] = 255
43
+
44
+ if self.prompt == 'click':
45
+ point_label, pt = random_click(np.array(mask) / 255, point_label)
46
+
47
+ if self.transform:
48
+ state = torch.get_rng_state()
49
+ img = self.transform(img)
50
+ torch.set_rng_state(state)
51
+
52
+ if self.transform_msk:
53
+ mask = Image.fromarray(mask)
54
+ mask = self.transform_msk(mask).int()
55
+
56
+ # if (inout == 0 and point_label == 1) or (inout == 1 and point_label == 0):
57
+ # mask = 1 - mask
58
+ image_meta_dict = {'filename_or_obj':name}
59
+ return {
60
+ 'image':img,
61
+ 'label': mask,
62
+ 'p_label':point_label,
63
+ 'pt':pt,
64
+ 'image_meta_dict':image_meta_dict,
65
+ }
environment.yml ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: sam_adapt
2
+ channels:
3
+ - pytorch
4
+ - conda-forge
5
+ - defaults
6
+ dependencies:
7
+ - _libgcc_mutex=0.1=main
8
+ - _openmp_mutex=5.1=1_gnu
9
+ - abseil-cpp=20211102.0=hd4dd3e8_0
10
+ - absl-py=1.3.0=py310h06a4308_0
11
+ - aiohttp=3.8.3=py310h5eee18b_0
12
+ - async-timeout=4.0.2=py310h06a4308_0
13
+ - attrs=22.1.0=py310h06a4308_0
14
+ - blas=1.0=mkl
15
+ - blosc=1.21.3=h6a678d5_0
16
+ - bottleneck=1.3.5=py310ha9d4c09_0
17
+ - brotli=1.0.9=h5eee18b_7
18
+ - brotli-bin=1.0.9=h5eee18b_7
19
+ - brotlipy=0.7.0=py310h7f8727e_1002
20
+ - brunsli=0.1=h2531618_0
21
+ - bzip2=1.0.8=h7b6447c_0
22
+ - c-ares=1.19.0=h5eee18b_0
23
+ - ca-certificates=2023.11.17=hbcca054_0
24
+ - cffi=1.15.1=py310h5eee18b_3
25
+ - cfitsio=3.470=h5893167_7
26
+ - charls=2.2.0=h2531618_0
27
+ - cloudpickle=2.2.1=py310h06a4308_0
28
+ - comm=0.1.4=pyhd8ed1ab_0
29
+ - contourpy=1.0.5=py310hdb19cb5_0
30
+ - cpuonly=2.0=0
31
+ - cryptography=39.0.1=py310h9ce1e76_0
32
+ - cudatoolkit=11.3.1=h2bc3f7f_2
33
+ - cytoolz=0.12.0=py310h5eee18b_0
34
+ - dask-core=2023.4.1=py310h06a4308_0
35
+ - dbus=1.13.18=hb2f20db_0
36
+ - debugpy=1.6.7=py310h6a678d5_0
37
+ - decorator=5.1.1=pyhd8ed1ab_0
38
+ - expat=2.4.9=h6a678d5_0
39
+ - ffmpeg=4.3=hf484d3e_0
40
+ - fontconfig=2.14.1=h4c34cd2_2
41
+ - freetype=2.12.1=h4a9f257_0
42
+ - frozenlist=1.3.3=py310h5eee18b_0
43
+ - fsspec=2023.4.0=py310h06a4308_0
44
+ - giflib=5.2.1=h5eee18b_3
45
+ - glib=2.69.1=he621ea3_2
46
+ - gmp=6.2.1=h295c915_3
47
+ - gnutls=3.6.15=he1e5248_0
48
+ - grpc-cpp=1.48.2=h5bf31a4_0
49
+ - grpcio=1.48.2=py310h5bf31a4_0
50
+ - gst-plugins-base=1.14.1=h6a678d5_1
51
+ - gstreamer=1.14.1=h5eee18b_1
52
+ - icu=58.2=he6710b0_3
53
+ - idna=3.4=py310h06a4308_0
54
+ - imagecodecs=2021.8.26=py310h46e8fbd_2
55
+ - imageio=2.26.0=py310h06a4308_0
56
+ - importlib-metadata=6.0.0=py310h06a4308_0
57
+ - importlib_metadata=6.0.0=hd8ed1ab_0
58
+ - intel-openmp=2021.4.0=h06a4308_3561
59
+ - ipykernel=6.26.0=pyhf8b6a83_0
60
+ - joblib=1.1.1=py310h06a4308_0
61
+ - jpeg=9e=h5eee18b_1
62
+ - jupyter_client=8.6.0=pyhd8ed1ab_0
63
+ - jupyter_core=5.5.0=py310hff52083_0
64
+ - jxrlib=1.1=h7b6447c_2
65
+ - kiwisolver=1.4.4=py310h6a678d5_0
66
+ - krb5=1.19.4=h568e23c_0
67
+ - lame=3.100=h7b6447c_0
68
+ - lazy_loader=0.1=py310h06a4308_0
69
+ - lcms2=2.12=h3be6417_0
70
+ - ld_impl_linux-64=2.38=h1181459_1
71
+ - lerc=3.0=h295c915_0
72
+ - libaec=1.0.4=he6710b0_1
73
+ - libbrotlicommon=1.0.9=h5eee18b_7
74
+ - libbrotlidec=1.0.9=h5eee18b_7
75
+ - libbrotlienc=1.0.9=h5eee18b_7
76
+ - libclang=14.0.6=default_hc6dbbc7_1
77
+ - libclang13=14.0.6=default_he11475f_1
78
+ - libcurl=7.88.1=h91b91d3_0
79
+ - libdeflate=1.17=h5eee18b_0
80
+ - libedit=3.1.20221030=h5eee18b_0
81
+ - libev=4.33=h7f8727e_1
82
+ - libevent=2.1.12=h8f2d780_0
83
+ - libffi=3.4.2=h6a678d5_6
84
+ - libgcc=7.2.0=h69d50b8_2
85
+ - libgcc-ng=11.2.0=h1234567_1
86
+ - libgfortran-ng=11.2.0=h00389a5_1
87
+ - libgfortran5=11.2.0=h1234567_1
88
+ - libgomp=11.2.0=h1234567_1
89
+ - libiconv=1.16=h7f8727e_2
90
+ - libidn2=2.3.2=h7f8727e_0
91
+ - libllvm14=14.0.6=hdb19cb5_2
92
+ - libnghttp2=1.46.0=hce63b2e_0
93
+ - libpng=1.6.39=h5eee18b_0
94
+ - libpq=12.9=h16c4e8d_3
95
+ - libprotobuf=3.20.3=he621ea3_0
96
+ - libsodium=1.0.18=h36c2ea0_1
97
+ - libssh2=1.10.0=h8f2d780_0
98
+ - libstdcxx-ng=11.2.0=h1234567_1
99
+ - libtasn1=4.19.0=h5eee18b_0
100
+ - libtiff=4.5.0=h6a678d5_2
101
+ - libunistring=0.9.10=h27cfd23_0
102
+ - libuuid=1.41.5=h5eee18b_0
103
+ - libwebp=1.2.4=h11a3e52_1
104
+ - libwebp-base=1.2.4=h5eee18b_1
105
+ - libxcb=1.15=h7f8727e_0
106
+ - libxkbcommon=1.0.1=h5eee18b_1
107
+ - libxml2=2.10.3=hcbfbd50_0
108
+ - libxslt=1.1.37=h2085143_0
109
+ - libzopfli=1.0.3=he6710b0_0
110
+ - locket=1.0.0=py310h06a4308_0
111
+ - lz4-c=1.9.4=h6a678d5_0
112
+ - markdown=3.4.1=py310h06a4308_0
113
+ - markupsafe=2.1.1=py310h7f8727e_0
114
+ - matplotlib=3.7.1=py310h06a4308_1
115
+ - matplotlib-base=3.7.1=py310h1128e8f_1
116
+ - matplotlib-inline=0.1.6=pyhd8ed1ab_0
117
+ - mkl=2021.4.0=h06a4308_640
118
+ - mkl-service=2.4.0=py310h7f8727e_0
119
+ - mkl_fft=1.3.1=py310hd6ae3a3_0
120
+ - mkl_random=1.2.2=py310h00e6091_0
121
+ - monai=1.1.0=pyhd8ed1ab_0
122
+ - multidict=6.0.2=py310h5eee18b_0
123
+ - munkres=1.1.4=pyh9f0ad1d_0
124
+ - ncurses=6.4=h6a678d5_0
125
+ - nest-asyncio=1.5.8=pyhd8ed1ab_0
126
+ - nettle=3.7.3=hbbd107a_1
127
+ - networkx=2.8.4=py310h06a4308_1
128
+ - nspr=4.33=h295c915_0
129
+ - nss=3.74=h0370c37_0
130
+ - numexpr=2.8.4=py310h8879344_0
131
+ - numpy=1.24.3=py310hd5efca6_0
132
+ - numpy-base=1.24.3=py310h8e6c178_0
133
+ - oauthlib=3.2.2=py310h06a4308_0
134
+ - openh264=2.1.1=h4ff587b_0
135
+ - openjpeg=2.4.0=h3ad879b_0
136
+ - openssl=1.1.1w=h7f8727e_0
137
+ - packaging=23.0=py310h06a4308_0
138
+ - pandas=1.5.3=py310h1128e8f_0
139
+ - parso=0.8.3=pyhd8ed1ab_0
140
+ - pcre=8.45=h295c915_0
141
+ - pexpect=4.8.0=pyh1a96a4e_2
142
+ - pickleshare=0.7.5=py_1003
143
+ - pillow=9.4.0=py310h6a678d5_0
144
+ - pip=23.0.1=py310h06a4308_0
145
+ - platformdirs=4.1.0=pyhd8ed1ab_0
146
+ - ply=3.11=py310h06a4308_0
147
+ - protobuf=3.20.3=py310h6a678d5_0
148
+ - ptyprocess=0.7.0=pyhd3deb0d_0
149
+ - pure_eval=0.2.2=pyhd8ed1ab_0
150
+ - pycparser=2.21=pyhd8ed1ab_0
151
+ - pyjwt=2.4.0=py310h06a4308_0
152
+ - pyopenssl=23.0.0=py310h06a4308_0
153
+ - pyparsing=3.0.9=py310h06a4308_0
154
+ - pyqt=5.15.7=py310h6a678d5_1
155
+ - pysocks=1.7.1=py310h06a4308_0
156
+ - python=3.10.11=h7a1cb2a_2
157
+ - python-dateutil=2.8.2=pyhd8ed1ab_0
158
+ - python_abi=3.10=2_cp310
159
+ - pytorch-mutex=1.0=cpu
160
+ - pytz=2022.7=py310h06a4308_0
161
+ - pyu2f=0.1.5=pyhd8ed1ab_0
162
+ - pywavelets=1.4.1=py310h5eee18b_0
163
+ - pyyaml=6.0=py310h5eee18b_1
164
+ - pyzmq=23.0.0=py310h330234f_0
165
+ - qt-main=5.15.2=h8373d8f_8
166
+ - qt-webengine=5.15.9=hbbf29b9_6
167
+ - qtwebkit=5.212=h3fafdc1_5
168
+ - re2=2022.04.01=h295c915_0
169
+ - readline=8.2=h5eee18b_0
170
+ - requests=2.29.0=py310h06a4308_0
171
+ - scikit-image=0.20.0=py310h6a678d5_0
172
+ - scikit-learn=1.2.2=py310h6a678d5_0
173
+ - scipy=1.10.1=py310hd5efca6_0
174
+ - seaborn=0.12.2=py310h06a4308_0
175
+ - setuptools=66.0.0=py310h06a4308_0
176
+ - sip=6.6.2=py310h6a678d5_0
177
+ - six=1.16.0=pyh6c4a22f_0
178
+ - snappy=1.1.9=h295c915_0
179
+ - sqlite=3.41.2=h5eee18b_0
180
+ - stack_data=0.6.2=pyhd8ed1ab_0
181
+ - tensorboard=2.11.0=py310h06a4308_0
182
+ - tensorboard-data-server=0.6.1=py310h52d8a92_0
183
+ - tensorboard-plugin-wit=1.8.1=py310h06a4308_0
184
+ - tk=8.6.12=h1ccaba5_0
185
+ - toml=0.10.2=pyhd8ed1ab_0
186
+ - toolz=0.12.0=py310h06a4308_0
187
+ - torchaudio=0.12.1=py310_cpu
188
+ - tornado=6.2=py310h5eee18b_0
189
+ - tqdm=4.65.0=py310h2f386ee_0
190
+ - typing_extensions=4.5.0=py310h06a4308_0
191
+ - tzdata=2023c=h04d1e81_0
192
+ - unicodedata2=14.0.0=py310h5764c6d_1
193
+ - urllib3=1.26.15=py310h06a4308_0
194
+ - wheel=0.38.4=py310h06a4308_0
195
+ - xz=5.4.2=h5eee18b_0
196
+ - yaml=0.2.5=h7b6447c_0
197
+ - yarl=1.8.1=py310h5eee18b_0
198
+ - zeromq=4.3.4=h9c3ff4c_1
199
+ - zfp=0.5.5=h295c915_6
200
+ - zipp=3.11.0=py310h06a4308_0
201
+ - zlib=1.2.13=h5eee18b_0
202
+ - zstd=1.5.5=hc292b87_0
203
+ - pip:
204
+ - aiosignal==1.2.0
205
+ - alembic==1.10.4
206
+ - appdirs==1.4.4
207
+ - astor==0.8.1
208
+ - asttokens==2.2.1
209
+ - backcall==0.2.0
210
+ - beautifulsoup4==4.12.2
211
+ - blinker==1.6.2
212
+ - cachetools==4.2.2
213
+ - certifi==2022.12.7
214
+ - charset-normalizer==2.0.4
215
+ - click==8.1.3
216
+ - cmaes==0.9.1
217
+ - colorama==0.4.6
218
+ - colorlog==6.7.0
219
+ - contextlib2==21.6.0
220
+ - coverage==6.5.0
221
+ - coveralls==3.3.1
222
+ - cucim==23.4.1
223
+ - cycler==0.11.0
224
+ - databricks-cli==0.17.7
225
+ - docker==6.1.1
226
+ - docopt==0.6.2
227
+ - einops==0.6.1
228
+ - entrypoints==0.4
229
+ - exceptiongroup==1.1.1
230
+ - executing==1.2.0
231
+ - filelock==3.12.0
232
+ - fire==0.5.0
233
+ - flask==2.3.2
234
+ - fonttools==4.25.0
235
+ - future==0.18.3
236
+ - gdown==4.7.1
237
+ - gitdb==4.0.10
238
+ - gitpython==3.1.31
239
+ - google-auth==2.6.0
240
+ - google-auth-oauthlib==0.4.4
241
+ - greenlet==2.0.2
242
+ - gunicorn==20.1.0
243
+ - h5py==3.8.0
244
+ - huggingface-hub==0.14.1
245
+ - iniconfig==2.0.0
246
+ - ipython==8.13.1
247
+ - itk==5.3.0
248
+ - itk-core==5.3.0
249
+ - itk-filtering==5.3.0
250
+ - itk-io==5.3.0
251
+ - itk-numerics==5.3.0
252
+ - itk-registration==5.3.0
253
+ - itk-segmentation==5.3.0
254
+ - itsdangerous==2.1.2
255
+ - jedi==0.18.2
256
+ - jinja2==3.1.2
257
+ - json-tricks==3.16.1
258
+ - jsonschema==4.17.3
259
+ - kornia==0.4.1
260
+ - lmdb==1.4.1
261
+ - lucent==0.1.0
262
+ - mako==1.2.4
263
+ - mlflow==2.3.1
264
+ - nibabel==5.1.0
265
+ - ninja==1.11.1
266
+ - nni==2.10
267
+ - nptyping==2.5.0
268
+ - opencv-python==4.7.0.72
269
+ - openslide-python==1.1.2
270
+ - optuna==3.1.1
271
+ - partd==1.2.0
272
+ - pluggy==1.0.0
273
+ - pooch==1.4.0
274
+ - prettytable==3.7.0
275
+ - prompt-toolkit==3.0.38
276
+ - psutil==5.9.5
277
+ - pyarrow==11.0.0
278
+ - pyasn1==0.4.8
279
+ - pyasn1-modules==0.2.8
280
+ - pydicom==2.3.1
281
+ - pygments==2.15.1
282
+ - pynrrd==1.0.0
283
+ - pyqt5-sip==12.11.0
284
+ - pyrsistent==0.19.3
285
+ - pytest==7.3.1
286
+ - pytest-mock==3.10.0
287
+ - pythonwebhdfs==0.2.3
288
+ - pytorch-ignite==0.4.10
289
+ - querystring-parser==1.2.4
290
+ - regex==2023.5.5
291
+ - requests-oauthlib==1.3.0
292
+ - responses==0.23.1
293
+ - rsa==4.7.2
294
+ - safetensors==0.4.1
295
+ - schema==0.7.5
296
+ - simplejson==3.19.1
297
+ - smmap==5.0.0
298
+ - soupsieve==2.4.1
299
+ - sqlalchemy==2.0.12
300
+ - sqlparse==0.4.4
301
+ - tabulate==0.9.0
302
+ - tensorboardx==2.2
303
+ - termcolor==2.3.0
304
+ - threadpoolctl==2.2.0
305
+ - tifffile==2021.7.2
306
+ - timm==0.9.12
307
+ - tokenizers==0.12.1
308
+ - tomli==2.0.1
309
+ - torch==1.12.1+cu113
310
+ - torch-lucent==0.1.8
311
+ - torchvision==0.13.1+cu113
312
+ - traitlets==5.9.0
313
+ - transformers==4.21.3
314
+ - typeguard==3.0.2
315
+ - types-pyyaml==6.0.12.9
316
+ - wcwidth==0.2.6
317
+ - websocket-client==1.5.1
318
+ - websockets==11.0.3
319
+ - werkzeug==2.3.4
figs/EfficientSAM/EfficientSAM-S (ISIC)_loss.png ADDED
figs/EfficientSAM/EfficientSAM-S (ISIC)_performance.png ADDED
figs/EfficientSAM/EfficientSAM-S (REFUGE)_loss.png ADDED