FatemehT commited on
Commit
b5cbaa6
·
0 Parent(s):

feat:first commit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LICENSE.txt +674 -0
  2. README.md +26 -0
  3. angioPyFunctions.py +265 -0
  4. angioPySegmentation.py +335 -0
  5. predict.py +65 -0
  6. requirements.txt +29 -0
  7. segmentation_models_pytorch/.github/FUNDING.yml +12 -0
  8. segmentation_models_pytorch/.github/stale.yml +17 -0
  9. segmentation_models_pytorch/.github/workflows/pypi.yml +26 -0
  10. segmentation_models_pytorch/.github/workflows/tests.yml +34 -0
  11. segmentation_models_pytorch/.gitignore +105 -0
  12. segmentation_models_pytorch/HALLOFFAME.md +90 -0
  13. segmentation_models_pytorch/LICENSE +21 -0
  14. segmentation_models_pytorch/MANIFEST.in +1 -0
  15. segmentation_models_pytorch/README.md +409 -0
  16. segmentation_models_pytorch/__init__.py +1 -0
  17. segmentation_models_pytorch/docker/Dockerfile +3 -0
  18. segmentation_models_pytorch/docker/Dockerfile.dev +10 -0
  19. segmentation_models_pytorch/docs/Makefile +20 -0
  20. segmentation_models_pytorch/docs/conf.py +120 -0
  21. segmentation_models_pytorch/docs/encoders.rst +301 -0
  22. segmentation_models_pytorch/docs/index.rst +26 -0
  23. segmentation_models_pytorch/docs/insights.rst +119 -0
  24. segmentation_models_pytorch/docs/install.rst +8 -0
  25. segmentation_models_pytorch/docs/losses.rst +34 -0
  26. segmentation_models_pytorch/docs/make.bat +35 -0
  27. segmentation_models_pytorch/docs/models.rst +52 -0
  28. segmentation_models_pytorch/docs/quickstart.rst +36 -0
  29. segmentation_models_pytorch/docs/requirements.txt +2 -0
  30. segmentation_models_pytorch/examples/cars segmentation (camvid).ipynb +0 -0
  31. segmentation_models_pytorch/misc/generate_table.py +33 -0
  32. segmentation_models_pytorch/requirements.txt +4 -0
  33. segmentation_models_pytorch/segmentation_models_pytorch/__init__.py +49 -0
  34. segmentation_models_pytorch/segmentation_models_pytorch/__version__.py +3 -0
  35. segmentation_models_pytorch/segmentation_models_pytorch/base/__init__.py +12 -0
  36. segmentation_models_pytorch/segmentation_models_pytorch/base/heads.py +24 -0
  37. segmentation_models_pytorch/segmentation_models_pytorch/base/initialization.py +27 -0
  38. segmentation_models_pytorch/segmentation_models_pytorch/base/model.py +42 -0
  39. segmentation_models_pytorch/segmentation_models_pytorch/base/modules.py +206 -0
  40. segmentation_models_pytorch/segmentation_models_pytorch/deeplabv3/__init__.py +1 -0
  41. segmentation_models_pytorch/segmentation_models_pytorch/deeplabv3/decoder.py +220 -0
  42. segmentation_models_pytorch/segmentation_models_pytorch/deeplabv3/model.py +183 -0
  43. segmentation_models_pytorch/segmentation_models_pytorch/efficientunetplusplus/__init__.py +1 -0
  44. segmentation_models_pytorch/segmentation_models_pytorch/efficientunetplusplus/decoder.py +148 -0
  45. segmentation_models_pytorch/segmentation_models_pytorch/efficientunetplusplus/model.py +125 -0
  46. segmentation_models_pytorch/segmentation_models_pytorch/encoders/__init__.py +84 -0
  47. segmentation_models_pytorch/segmentation_models_pytorch/encoders/_base.py +41 -0
  48. segmentation_models_pytorch/segmentation_models_pytorch/encoders/_preprocessing.py +23 -0
  49. segmentation_models_pytorch/segmentation_models_pytorch/encoders/_utils.py +50 -0
  50. segmentation_models_pytorch/segmentation_models_pytorch/encoders/densenet.py +146 -0
LICENSE.txt 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 ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AngioPy Segmentation
2
+
3
+ ## AngioPy paper
4
+ Please see [here](https://doi.org/10.1016/j.ijcard.2024.132598) for our paper in the International Journal of Cardiology
5
+
6
+ Please cite it!
7
+ > Mahendiran, T., Thanou, D., Senouf, O., Jamaa, Y., Fournier, S., De Bruyne, B., ... & Andò, E. (2025). AngioPy Segmentation: An open-source, user-guided deep learning tool for coronary artery segmentation. International journal of cardiology, 418, 132598.
8
+
9
+ ## AngioPy in the news
10
+ AngioPy segmentation is being used in [this RTS reportage on AI in Cardiology](https://www.rts.ch/play/tv/19h30/video/lia-fait-irruption-en-cardiologie-et-redefinit-le-role-des-medecins?urn=urn:rts:video:15479233) (in French)
11
+
12
+ ## Online Example
13
+ Please visit https://imaging.epfl.ch/angiopy-segmentation/ for a live demo of this code on some example DICOM images
14
+
15
+ ![](illustration.mp4)
16
+
17
+ ## Description
18
+ This software allows single arteries to be segmented given a few clicks on a single time frame with a PyTorch 2 Deep Learning model.
19
+
20
+ ## Installing and running
21
+ - Install dependencies: ` pip install -r requirements.txt`
22
+ - Launch Streamlit Web Interface: `streamlit run angioPySegmentation.py --server.fileWatcherType none`
23
+
24
+ ...a website should pop up in your browser!
25
+
26
+ You need to create a /Dicom folder and put some angiography DICOMs in there
angioPyFunctions.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy
2
+ import scipy.interpolate
3
+ import skimage.filters
4
+ import skimage.morphology
5
+ import scipy.ndimage
6
+ import scipy.optimize
7
+ import predict
8
+ from PIL import Image
9
+ from fil_finder import FilFinder2D
10
+ import astropy.units as u
11
+ from tqdm import tqdm
12
+ import pooch
13
+ import utils.dataset
14
+ import cv2
15
+
16
+
17
+ colourTableHex = {
18
+ 'LAD': "#f03b20",
19
+ 'D': "#fd8d3c",
20
+ 'CX': "#31a354",
21
+ 'OM': "#74c476",
22
+ 'RCA': "#08519c",
23
+ 'AM': "#3182bd",
24
+ 'LM': "#984ea3",
25
+ }
26
+
27
+ colourTableList = {}
28
+
29
+ for item in colourTableHex.keys():
30
+ ### WARNING HACK: The colours go in backwards here for some reason perhaps related to RGBA?
31
+ colourTableList[item] = [int(colourTableHex[item][5:7], 16),
32
+ int(colourTableHex[item][3:5], 16),
33
+ int(colourTableHex[item][1:3], 16)]
34
+
35
+
36
+ def skeletonise(maskArray):
37
+ # if len(maskArray.shape) == 3:
38
+ maskArray = cv2.cvtColor(maskArray, cv2.COLOR_BGR2GRAY)
39
+
40
+ skeleton = skimage.morphology.skeletonize(maskArray.astype('bool'))
41
+
42
+ # Process the skeleton and find the longest path
43
+ fil = FilFinder2D(skeleton.astype('uint8'),
44
+ distance=250 * u.pc, mask=skeleton, beamwidth=10.0*u.pix)
45
+ fil.preprocess_image(flatten_percent=85)
46
+ fil.create_mask(border_masking=True, verbose=False,
47
+ use_existing_mask=True)
48
+ fil.medskel(verbose=False)
49
+ fil.analyze_skeletons(branch_thresh=400 * u.pix,
50
+ skel_thresh=10 * u.pix, prune_criteria='length')
51
+
52
+ # add image arrays dictionary
53
+ # tifffile.imwrite(os.path.join(arteryFolder, "skel.tif"), fil.skeleton.astype('<u1')*255)
54
+
55
+ skel = fil.skeleton.astype('<u1')*255
56
+
57
+ return skel
58
+
59
+
60
+ def skelEndpoints(skel):
61
+ #skel[skel!=0] = 1
62
+ skel = numpy.uint8(skel>0)
63
+
64
+ # Apply the convolution.
65
+ kernel = numpy.uint8([[1, 1, 1],
66
+ [1, 10, 1],
67
+ [1, 1, 1]])
68
+ src_depth = -1
69
+ filtered = cv2.filter2D(skel,src_depth,kernel)
70
+
71
+ # Look through to find the value of 11.
72
+ # This returns a mask of the endpoints, but if you
73
+ # just want the coordinates, you could simply
74
+ # return np.where(filtered==11)
75
+ out = numpy.zeros_like(skel)
76
+ out[numpy.where(filtered==11)] = 1
77
+ endCoords = numpy.where(filtered==11)
78
+ endCoords = list(zip(*endCoords))
79
+ startPoint = endCoords[0]
80
+ endPoint = endCoords[1]
81
+
82
+ # print(f"Skel starts at {startPoint} and finishes at {endPoint}")
83
+
84
+ return startPoint, endPoint
85
+
86
+
87
+ def skelPointsInOrder(skel, startPoint=None):
88
+ """
89
+ put in a skel image, get the y, x points out in order
90
+ """
91
+
92
+ # Lazy!!
93
+ if startPoint is None:
94
+ startPoint, _ = skelEndpoints(skel)
95
+
96
+ # get the coordinates of all points in the skeleton
97
+ skelXY = numpy.array(numpy.where(skel))
98
+ skelPoints = list(zip(skelXY[0], skelXY[1]))
99
+ skelLength = len(skelPoints)
100
+
101
+ # Loop through the skeleton starting with startPoint, deleting the starting point from the skelPoints list, and finding the closest pixel. This is appended to orderedPoints. startPoint now becomes the last point to be appended.
102
+ startPointCopy = startPoint # copied as we are going to loop and overwrite, but want to also keep the original startPoint
103
+ orderedPoints = []
104
+
105
+ while len(skelPoints) > 1:
106
+
107
+ skelPoints.remove(startPointCopy)
108
+
109
+ # Calculate the point that is closest to the start point
110
+ diffs = numpy.abs(numpy.array(skelPoints)-numpy.array(startPointCopy))
111
+ dists = numpy.sum(diffs,axis=1) #l1-distance
112
+ closest_point_index = numpy.argmin(dists)
113
+ closestPoint = skelPoints[closest_point_index]
114
+ orderedPoints.append(closestPoint)
115
+
116
+ startPointCopy = closestPoint
117
+
118
+ orderedPoints = numpy.array(orderedPoints)
119
+
120
+ # YX points
121
+ return orderedPoints
122
+
123
+
124
+ def skelSplinerWithThickness(skel, EDT, smoothing=50, order=3, decimation=2):
125
+ # NOTE: the coordinate seem to come out with y first, then x
126
+ startPoint, endPoint = skelEndpoints(skel)
127
+
128
+ # Impose an order to points
129
+ orderedPoints = skelPointsInOrder(skel, startPoint)
130
+
131
+ # unzip ordered points to extract x and y arrays
132
+ x = orderedPoints[:, 1].ravel()
133
+ y = orderedPoints[:, 0].ravel()
134
+
135
+ x = x[::decimation]
136
+ y = y[::decimation]
137
+
138
+ #NOTE: Should the EDT be median filtered? I wonder in fact if doing so will reduce the accuracy of the model.
139
+ # EDT = skimage.filters.median(EDT)
140
+
141
+ t = EDT[y, x]
142
+
143
+ x = x[0:-1]
144
+ y = y[0:-1]
145
+ t = t[0:-1]
146
+
147
+ print(x.shape, y.shape, t.shape)
148
+
149
+ tcko, uo = scipy.interpolate.splprep(
150
+ [y, x, t], s=smoothing, k=order, per=False)
151
+
152
+ return tcko
153
+
154
+
155
+ def arterySegmentation(inputImage, groundTruthPoints, segmentationModelWeights=None):
156
+ """
157
+ Segment a single greyscale artery with a UNet model.
158
+
159
+ Parameters
160
+ ----------
161
+ inputImage: 2D numpy array
162
+ Ideally this input is normalised 0-255 and 512x512
163
+ If a different size it is rescaled along with groundTruthPoints
164
+
165
+ groundTruthPoints: Nx2 numpy array
166
+ Y and X positions of annotated points along the artery,
167
+ Ordering is not important except that start and end points should be top and bottom of the array
168
+
169
+ segmentationModelWeights: segmentation model weights (pth), optional
170
+ Segmentation model weights to use.
171
+ If not set the default ones from this paper: https://doi.org/10.1016/j.ijcard.2024.132598
172
+
173
+ Returns
174
+ -------
175
+ mask : 512x512 numpy array (int64)
176
+ Mask selecting the selected artery, 0 = background and 1 = artery
177
+ """
178
+ if segmentationModelWeights is None:
179
+ segmentationModelWeights = pooch.retrieve(
180
+ url="doi:10.5281/zenodo.13848135/modelWeights-InternalData-inceptionresnetv2-fold2-e40-b10-a4.pth",
181
+ known_hash="md5:bf893ef57adaf39cfee33b25c7c1d87b",
182
+ )
183
+
184
+ if inputImage.shape[0] != 512 and inputImage.shape[1] != 512:
185
+ ratioYX = numpy.array([512./inputImage.shape[0], 512./inputImage.shape[1]])
186
+ print(f"arterySegmentation(): Rescaling image to 512x512 by {ratioYX=}, and also applying this to input points")
187
+ inputImage = scipy.ndimage.zoom(inputImage, ratioYX)
188
+ points = groundTruthPoints.copy() * ratioYX
189
+ print(inputImage.shape)
190
+ else:
191
+ points = groundTruthPoints
192
+
193
+ imageSize = inputImage.shape
194
+
195
+ n_classes = 2 # binary output
196
+
197
+ net = predict.smp.Unet(
198
+ encoder_name='inceptionresnetv2',
199
+ encoder_weights="imagenet",
200
+ in_channels=3,
201
+ classes=n_classes
202
+ )
203
+
204
+ net = predict.nn.DataParallel(net)
205
+
206
+ device = predict.torch.device('cuda' if predict.torch.cuda.is_available() else 'cpu')
207
+ net.to(device=device)
208
+
209
+ net.load_state_dict(
210
+ predict.torch.load(
211
+ segmentationModelWeights,
212
+ map_location=device
213
+ )
214
+ )
215
+
216
+ orig_image = Image.fromarray(inputImage)
217
+
218
+ image = predict.Image.new('RGB', imageSize, (0, 0, 0))
219
+ image.paste(orig_image, (0, 0))
220
+
221
+ imageArray = numpy.array(image).astype('uint8')
222
+
223
+ # Clear last channels
224
+ imageArray[:, :, -1] = 0
225
+ imageArray[:, :, -2] = 0
226
+
227
+ ## Get endpoints of skeleton
228
+ startPoint = points[0]
229
+ endPoint = points[-1]
230
+
231
+ # End points on Channel 1
232
+ for y, x in [startPoint, endPoint]:
233
+ y = int(numpy.round(y))
234
+ x = int(numpy.round(x))
235
+ imageArray[y-2:y+2, x-2:x+2, 1] = 255
236
+
237
+ # All other points on Channel 2
238
+ for y, x in points[1:-1]:
239
+ y = int(numpy.round(y))
240
+ x = int(numpy.round(x))
241
+ imageArray[y-2:y+ 2, x-2:x+2, 2] = 255
242
+
243
+ image = Image.fromarray(imageArray.astype(numpy.uint8))
244
+
245
+ mask = predict.predict_img(
246
+ net=net,
247
+ dataset_class=utils.dataset.CoronaryDataset,
248
+ full_img=image,
249
+ scale_factor=1,
250
+ device=device
251
+ )
252
+
253
+ return mask
254
+
255
+
256
+
257
+ def maskOutliner(labelledArtery, outlineThickness=3):
258
+
259
+ # Compute the boundary of the mask
260
+ contours, _ = cv2.findContours(labelledArtery, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
261
+ tmp = numpy.zeros_like(labelledArtery)
262
+ boundary = cv2.drawContours(tmp, contours, -1, (255,255,255), outlineThickness)
263
+ boundary = boundary > 0
264
+
265
+ return boundary
angioPySegmentation.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os.path
3
+ import matplotlib.pyplot as plt
4
+ import numpy
5
+ import pandas as pd
6
+ import streamlit as st
7
+ import SimpleITK as sitk
8
+ import pydicom
9
+ import glob
10
+ import mpld3
11
+ import streamlit.components.v1 as components
12
+ import plotly.express as px
13
+ import plotly.graph_objects as go
14
+ import tifffile
15
+ from streamlit_plotly_events import plotly_events
16
+ from streamlit_drawable_canvas import st_canvas
17
+ from PIL import Image
18
+ # from streamlit_image_coordinates import streamlit_image_coordinates
19
+ import predict
20
+ import angioPyFunctions
21
+ import scipy
22
+ import cv2
23
+
24
+ import ssl
25
+
26
+ ssl._create_default_https_context = ssl._create_unverified_context
27
+
28
+ st.set_page_config(page_title="AngioPy Segmentation", layout="wide")
29
+
30
+ if 'stage' not in st.session_state:
31
+ st.session_state.stage = 0
32
+
33
+
34
+
35
+ # Make output folder
36
+ # os.makedirs(name=outputPath, exist_ok=True)
37
+
38
+ # arteryDictionary = {
39
+ # 'LAD': {'colour': "#f03b20"},
40
+ # 'CX': {'colour': "#31a354"},
41
+ # 'OM': {'colour' : "#74c476"},
42
+ # 'RCA': {'colour': "#08519c"},
43
+ # 'AM': {'colour' : "#3182bd"},
44
+ # 'LM': {'colour' : "#984ea3"},
45
+ # }
46
+
47
+ # def file_selector(folder_path='.'):
48
+ # fileNames = [file for file in glob.glob(f"{folder_path}/*")]
49
+ # selectedDicom = st.sidebar.selectbox('Select a DICOM file:', fileNames)
50
+ # if selectedDicom is None:
51
+ # return None
52
+
53
+ # return selectedDicom
54
+
55
+ @st.cache_data
56
+ def selectSlice(slice_ix, pixelArray, fileName):
57
+
58
+ # Save the selected frame
59
+ tifffile.imwrite(f"{outputPath}/{fileName}", pixelArray[slice_ix, :, :])
60
+
61
+ # Set the button as clicked
62
+ st.session_state.btnSelectSlice = True
63
+
64
+
65
+ DicomFolder = "Dicoms/"
66
+ # exampleDicoms = {
67
+ # 'RCA2' : 'Dicoms/RCA1',
68
+ # 'RCA1' : 'Dicoms/RCA4',
69
+ # # 'RCA2' : 'Dicoms/RCA2',
70
+ # # 'RCA3' : 'Dicoms/RCA3',
71
+ # # 'LCA1' : 'Dicoms/LCA1',
72
+ # # 'LCA2' : 'Dicoms/LCA2',
73
+ #
74
+ # }
75
+ exampleDicoms = {}
76
+ files = sorted(glob.glob(DicomFolder+"/*"))
77
+ for file in files:
78
+ exampleDicoms[os.path.basename(file)] = file
79
+
80
+
81
+ # Main text
82
+ st.markdown("<h1 style='text-align: center;'>AngioPy Segmentation</h1>", unsafe_allow_html=True)
83
+ st.markdown("<h5 style='text-align: center;'> Welcome to <b>AngioPy Segmentation</b>, an AI-driven, coronary angiography segmentation tool.</h1>", unsafe_allow_html=True)
84
+ st.markdown("")
85
+
86
+ # Build the sidebar
87
+ # Select DICOM file: here eventually we will use the file_uploader widget, but for the demo this is deactivate. Instead we will have a choice of 3 anonymised DICOMs to pick from
88
+ # selectedDicom = st.sidebar.file_uploader("Upload DICOM file:",type=["dcm"], accept_multiple_files=False)
89
+
90
+ # def changeSessionState():
91
+
92
+ # # value += 1
93
+
94
+ # print("CHANGED!")
95
+
96
+
97
+ DropDownDicom = st.sidebar.selectbox("Select example DICOM file:",
98
+ options = list(exampleDicoms.keys()),
99
+ # on_change=changeSessionState(st.session_state.key),
100
+ key="dicomDropDown"
101
+ )
102
+
103
+ selectedDicom = exampleDicoms[DropDownDicom]
104
+
105
+ stepOne = st.sidebar.expander("STEP ONE", True)
106
+ stepTwo = st.sidebar.expander("STEP TWO", True)
107
+
108
+ # Create tabs
109
+ tab1, tab2 = st.tabs(["Segmentation", "Analysis"])
110
+
111
+ # Increase tab font size
112
+ css = '''
113
+ <style>
114
+ .stTabs [data-baseweb="tab-list"] button [data-testid="stMarkdownContainer"] p {
115
+ font-size:16px;
116
+ }
117
+ </style>
118
+ '''
119
+
120
+ st.markdown(css, unsafe_allow_html=True)
121
+
122
+ # while True:
123
+ # Once a file is uploaded, the following annotation sequence is initiated
124
+ if selectedDicom is not None:
125
+ try:
126
+ print(f"Trying to load {selectedDicom}")
127
+ dcm = pydicom.dcmread(selectedDicom, force=True)
128
+
129
+ # handAngle = dcm.PositionerPrimaryAngle
130
+ # headAngle = dcm.PositionerSecondaryAngle
131
+ # dcmLabel = f"{'LAO' if handAngle > 0 else 'RAO'} {numpy.abs(handAngle):04.1f}° {'CRA' if headAngle > 0 else 'CAU'} {numpy.abs(headAngle):04.1f}°"
132
+
133
+ pixelArray = dcm.pixel_array
134
+
135
+ # Just take first channel if it's RGB?
136
+ if len(pixelArray.shape) == 4:
137
+ pixelArray = pixelArray[:,:,:,0]
138
+
139
+ n_slices = pixelArray.shape[0]
140
+
141
+ slice_ix = 0
142
+ except:
143
+ selectedDicom = None
144
+ # continue
145
+
146
+ with tab1:
147
+
148
+ with stepOne:
149
+ st.write("Select frame for annotation. Aim for an end-diastolic frame with good visualisation of the artery of interest.")
150
+
151
+ slice_ix = st.slider('Frame', 0, n_slices-1, int(n_slices/2), key='sliceSlider')
152
+
153
+
154
+ predictedMask = numpy.zeros_like(pixelArray[slice_ix, :, :])
155
+
156
+
157
+ with stepTwo:
158
+
159
+ selectedArtery = st.selectbox("Select artery for annotation:",
160
+ ['LAD', 'CX', 'RCA', 'LM', 'OM', 'AM', 'D'],
161
+ key="arteryDropMenu"
162
+ )
163
+
164
+ st.write("Beginning with the desired start point and finishing at the desired end point, click along the artery aiming for ~5-10 points.")
165
+
166
+
167
+ stroke_color = angioPyFunctions.colourTableList[selectedArtery]
168
+
169
+
170
+ col1, col2 = st.columns((15,15))
171
+
172
+ with col1:
173
+ col1a, col1b, col1c = st.columns((1,10,1))
174
+
175
+ with col1b:
176
+
177
+ leftImageText = "<p style='text-align: center; color: white;'>Beginning with the desired <u><b>start point</b></u> and finishing at the desired <u><b>end point</b></u>, click along the artery aiming for ~5-10 points. Segmentation is automatic.</p>"
178
+
179
+ st.markdown(f"<h5 style='text-align: center; color: white;'>Selected frame</h5>", unsafe_allow_html=True)
180
+
181
+ st.markdown(leftImageText, unsafe_allow_html=True)
182
+
183
+ selectedFrame = pixelArray[slice_ix, :, :]
184
+ selectedFrame = cv2.resize(selectedFrame, (512,512))
185
+
186
+ # Create a canvas component
187
+ annotationCanvas = st_canvas(
188
+ fill_color="red", # Fixed fill color with some opacity
189
+ stroke_width=1,
190
+ stroke_color="red",
191
+ background_color='black',
192
+ background_image= Image.fromarray(selectedFrame),
193
+ update_streamlit=True,
194
+ height=512,
195
+ width=512,
196
+ drawing_mode="point",
197
+ point_display_radius=2,
198
+ key=st.session_state.dicomDropDown,
199
+ )
200
+
201
+
202
+ # Do something interesting with the image data and paths
203
+ if annotationCanvas.json_data is not None:
204
+ objects = pd.json_normalize(annotationCanvas.json_data["objects"]) # need to convert obj to str because PyArrow
205
+
206
+ if len(objects) != 0:
207
+
208
+ for col in objects.select_dtypes(include=['object']).columns:
209
+ objects[col] = objects[col].astype("str")
210
+
211
+ groundTruthPoints = numpy.vstack(
212
+ (
213
+ numpy.array(objects['top']),
214
+ numpy.array(objects['left']+3.5) # compensate for some streamlit offset or something
215
+ )
216
+ ).T
217
+
218
+ mask = angioPyFunctions.arterySegmentation(
219
+ pixelArray[slice_ix],
220
+ groundTruthPoints,
221
+ )
222
+ predictedMask = predict.CoronaryDataset.mask2image(mask)
223
+ # predictedMask = predictedMask.crop((0, 0, imageSize[0], imageSize[1]))
224
+ predictedMask = numpy.asarray(predictedMask)
225
+
226
+ with col2:
227
+ col2a, col2b, col2c = st.columns((1,10,1))
228
+
229
+ with col2b:
230
+ st.markdown(f"<h5 style='text-align: center; color: white;'>Predicted mask</h1>", unsafe_allow_html=True)
231
+ st.markdown(f"<p style='text-align: center; color: white;'>If the predicted mask has errors, restart and select more points to help the segmentation model. </p>", unsafe_allow_html=True)
232
+
233
+ stroke_color = "rgba(255, 255, 255, 255)"
234
+
235
+ maskCanvas = st_canvas(
236
+ fill_color=angioPyFunctions.colourTableList[selectedArtery], # Fixed fill color with some opacity
237
+ stroke_width=0,
238
+ stroke_color=stroke_color,
239
+ background_color='black',
240
+ background_image= Image.fromarray(predictedMask),
241
+ update_streamlit=True,
242
+ height=512,
243
+ width=512,
244
+ drawing_mode="freedraw",
245
+ point_display_radius=3,
246
+ key="maskCanvas",
247
+ )
248
+
249
+
250
+ # Check that the mask array is not blank
251
+ if numpy.sum(predictedMask) > 0 and len(objects)>4:
252
+ # add alpha channel to predict mask in order to merge
253
+ b_channel, g_channel, r_channel = cv2.split(predictedMask)
254
+ a_channel = numpy.full_like(predictedMask[:,:,0], fill_value=255)
255
+
256
+ predictedMaskRGBA = cv2.merge((predictedMask, a_channel))
257
+
258
+
259
+ with tab2:
260
+ # combinedMask = cv2.cvtColor(predictedMaskRGBA, cv2.COLOR_RGBA2RGB)
261
+
262
+ # print(combinedMask.shape)
263
+ # tifffile.imwrite(f"{outputPath}/test.tif", combinedMask)
264
+
265
+
266
+ # tab2Col1, tab2Col2, tab2Col3 = st.columns([1,15,1])
267
+ tab2Col1, tab2Col2 = st.columns([20,10])
268
+
269
+ with tab2Col1:
270
+ st.markdown(f"<h5 style='text-align: center; color: white;'><br>Artery profile</h5>", unsafe_allow_html=True)
271
+
272
+ # Extract thickness information from mask
273
+ EDT = scipy.ndimage.distance_transform_edt(cv2.cvtColor(predictedMaskRGBA, cv2.COLOR_RGBA2GRAY))
274
+
275
+ # Skeletonise, get a list of ordered centreline points, and spline them
276
+ skel = angioPyFunctions.skeletonise(predictedMaskRGBA)
277
+ tck = angioPyFunctions.skelSplinerWithThickness(skel=skel, EDT=EDT)
278
+
279
+ # Interogate the spline function over 1000 points
280
+ splinePointsY, splinePointsX, splineThicknesses = scipy.interpolate.splev(
281
+ numpy.linspace(
282
+ 0.0,
283
+ 1.0,
284
+ 1000),
285
+ tck)
286
+
287
+ clippingLength = 20
288
+
289
+ vesselThicknesses = splineThicknesses[clippingLength:-clippingLength]*2
290
+
291
+ fig = px.line(x=numpy.arange(1,len(vesselThicknesses)+1),y=vesselThicknesses, labels=dict(x="Centreline point", y="Thickness (pixels)"), width=800)
292
+ # fig.update_layout(showlegend=False, xaxis={'showgrid': False, 'zeroline': True})
293
+ fig.update_traces(line_color='rgb(31, 119, 180)', textfont_color="white", line={'width':4})
294
+ fig.update_xaxes(showline=True, linewidth=2, linecolor='white', showgrid=False,gridcolor='white')
295
+ fig.update_yaxes(showline=True, linewidth=2, linecolor='white', gridcolor='white')
296
+
297
+ fig.update_layout(yaxis_range=[0,numpy.max(vesselThicknesses)*1.2])
298
+ fig.update_layout(font_color="white",title_font_color="white")
299
+ fig.update_layout({'plot_bgcolor': 'rgba(0, 0, 0, 0)','paper_bgcolor': 'rgba(0, 0, 0, 0)'})
300
+
301
+
302
+ selected_points = plotly_events(fig)
303
+
304
+
305
+
306
+ with tab2Col2:
307
+
308
+ st.markdown(f"<h5 style='text-align: center; color: white;'><br>Contours</h5>", unsafe_allow_html=True)
309
+
310
+
311
+ selectedFrameRGBA = cv2.cvtColor(selectedFrame, cv2.COLOR_GRAY2RGBA)
312
+
313
+ contour = angioPyFunctions.maskOutliner(labelledArtery=predictedMaskRGBA[:,:,0], outlineThickness=1)
314
+
315
+ selectedFrameRGBA[contour, :] = [angioPyFunctions.colourTableList[selectedArtery][2],
316
+ angioPyFunctions.colourTableList[selectedArtery][1],
317
+ angioPyFunctions.colourTableList[selectedArtery][0],
318
+ 255]
319
+
320
+ fig2 = px.imshow(selectedFrameRGBA)
321
+
322
+
323
+ fig2.update_xaxes(visible=False)
324
+ fig2.update_yaxes(visible=False)
325
+ fig2.update_layout(margin={"t": 0, "b": 0, "r": 0, "l": 0, "pad": 0},) #remove margins
326
+ # fig2.coloraxis(visible=False)
327
+
328
+ fig2.update_traces(dict(
329
+ showscale=False,
330
+ coloraxis=None,
331
+ colorscale='gray'), selector={'type':'heatmap'})
332
+
333
+ fig2.add_trace(go.Scatter(x=splinePointsX[clippingLength:-clippingLength], y=splinePointsY[clippingLength:-clippingLength], line=dict(width=1)))
334
+
335
+ st.plotly_chart(fig2, use_container_width=True)
predict.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from PIL import Image
8
+ from torchvision import transforms
9
+
10
+ from utils.dataset import CoronaryDataset
11
+ import segmentation_models_pytorch.segmentation_models_pytorch as smp
12
+
13
+ from torch.backends import cudnn
14
+
15
+ '''
16
+ This uses a pytorch coronary segmentation model (EfficientNetPLusPlus) that has been trained using a freely available dataset of labelled coronary angiograms from: http://personal.cimat.mx:8181/~ivan.cruz/DB_Angiograms.html
17
+ The input is a raw angiogram image, and the output is a segmentation mask of all the arteries. This output will be used as the 'first guess' to speed up artery annotation.
18
+ '''
19
+
20
+ def predict_img(net, dataset_class, full_img, device, scale_factor=1, n_classes=3):
21
+ # NOTE n_classes is the number of possible values that can be predicted for a given pixel. In a standard binary segmentation task, this will be 2 i.e. black or white
22
+
23
+ net.eval()
24
+
25
+ img = torch.from_numpy(dataset_class.preprocess(full_img, scale_factor))
26
+
27
+ img = img.unsqueeze(0)
28
+ img = img.to(device=device, dtype=torch.float32)
29
+
30
+ with torch.no_grad():
31
+ output = net(img)
32
+
33
+ if n_classes > 1:
34
+ probs = torch.softmax(output, dim=1)
35
+ else:
36
+ probs = torch.sigmoid(output)
37
+
38
+ probs = probs.squeeze(0)
39
+
40
+ tf = transforms.Compose(
41
+ [
42
+ transforms.ToPILImage(),
43
+ transforms.Resize(full_img.size[1]),
44
+ transforms.ToTensor()
45
+ ]
46
+ )
47
+
48
+ full_mask = tf(probs.cpu())
49
+
50
+ if n_classes > 1:
51
+ return dataset_class.one_hot2mask(full_mask)
52
+ else:
53
+ return full_mask > 0.5
54
+
55
+
56
+ def get_args():
57
+ parser = argparse.ArgumentParser(description='Predict masks from input images', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
58
+ # parser.add_argument('-d', '--dataset', type=str, help='Specifies the dataset to be used', dest='dataset', required=True)
59
+ parser.add_argument('--model', '-m', default='MODEL.pth', metavar='FILE', help="Specify the file in which the model is stored")
60
+ parser.add_argument('--input', '-i', metavar='INPUT', nargs='+', help='filenames of input images', required=True)
61
+ parser.add_argument('--output', '-o', metavar='INPUT', nargs='+', help='Filenames of output images')
62
+
63
+ return parser.parse_args()
64
+
65
+
requirements.txt ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Automatically generated by https://github.com/damnever/pigar.
2
+
3
+ astropy==5.2.2
4
+ efficientnet-pytorch==0.7.1
5
+ fil-finder==1.7.2
6
+ matplotlib==3.7.2
7
+ mpld3==0.5.9
8
+ numpy==1.24.4
9
+ opencv-python==4.8.0.76
10
+ pandas==2.0.3
11
+ Pillow==9.5.0
12
+ plotly==5.16.1
13
+ pretrainedmodels==0.7.4
14
+ pydicom==2.4.3
15
+ PyYAML==6.0.1
16
+ scikit-image==0.21.0
17
+ scikit-learn==1.3.0
18
+ scipy==1.10.1
19
+ setuptools==47.1.0
20
+ SimpleITK==2.2.1
21
+ streamlit<=1.38.0
22
+ streamlit-drawable-canvas==0.9.3
23
+ streamlit-plotly-events==0.0.6
24
+ tifffile==2023.7.10
25
+ timm==0.9.6
26
+ torch==2.0.1
27
+ torchvision==0.15.2
28
+ tqdm==4.61.1
29
+ pooch
segmentation_models_pytorch/.github/FUNDING.yml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4
+ patreon: # Replace with a single Patreon username
5
+ open_collective: # Replace with a single Open Collective username
6
+ ko_fi: qubvel
7
+ tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8
+ community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9
+ liberapay: qubvel
10
+ issuehunt: # Replace with a single IssueHunt username
11
+ otechie: # Replace with a single Otechie username
12
+ custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
segmentation_models_pytorch/.github/stale.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Number of days of inactivity before an issue becomes stale
2
+ daysUntilStale: 60
3
+ # Number of days of inactivity before a stale issue is closed
4
+ daysUntilClose: 7
5
+ # Issues with these labels will never be considered stale
6
+ exemptLabels:
7
+ - pinned
8
+ - security
9
+ # Label to use when marking an issue as stale
10
+ staleLabel: wontfix
11
+ # Comment to post when marking an issue as stale. Set to `false` to disable
12
+ markComment: >
13
+ This issue has been automatically marked as stale because it has not had
14
+ recent activity. It will be closed if no further activity occurs. Thank you
15
+ for your contributions.
16
+ # Comment to post when closing a stale issue. Set to `false` to disable
17
+ closeComment: false
segmentation_models_pytorch/.github/workflows/pypi.yml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Upload Python Package
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ deploy:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v2
12
+ - name: Set up Python
13
+ uses: actions/setup-python@v2
14
+ with:
15
+ python-version: '3.6'
16
+ - name: Install dependencies
17
+ run: |
18
+ python -m pip install --upgrade pip
19
+ pip install setuptools wheel twine mock
20
+ - name: Build and publish
21
+ env:
22
+ TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
23
+ TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
24
+ run: |
25
+ python setup.py sdist bdist_wheel
26
+ twine upload dist/*
segmentation_models_pytorch/.github/workflows/tests.yml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # This workflow will install Python dependencies, run tests and lint with a variety of Python versions
3
+ # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
4
+
5
+ name: CI
6
+
7
+ on:
8
+ push:
9
+ branches: [ master ]
10
+ pull_request:
11
+ branches: [ master ]
12
+
13
+ jobs:
14
+ test:
15
+
16
+ runs-on: ubuntu-18.04
17
+
18
+ steps:
19
+ - uses: actions/checkout@v2
20
+
21
+ - name: Set up Python ${{ matrix.python-version }}
22
+ uses: actions/setup-python@v2
23
+ with:
24
+ python-version: 3.6
25
+
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m pip install --upgrade pip
29
+ python -m pip install codecov pytest mock
30
+ pip install torch==1.7.1+cpu torchvision==0.8.2+cpu torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html
31
+ pip install .
32
+ - name: Test
33
+ run: |
34
+ python -m pytest -s tests
segmentation_models_pytorch/.gitignore ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ .idea/
6
+
7
+ # C extensions
8
+ *.so
9
+
10
+ # Distribution / packaging
11
+ .Python
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ lib/
19
+ lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .coverage
43
+ .coverage.*
44
+ .cache
45
+ nosetests.xml
46
+ coverage.xml
47
+ *.cover
48
+ .hypothesis/
49
+ .pytest_cache/
50
+
51
+ # Translations
52
+ *.mo
53
+ *.pot
54
+
55
+ # Django stuff:
56
+ *.log
57
+ local_settings.py
58
+ db.sqlite3
59
+
60
+ # Flask stuff:
61
+ instance/
62
+ .webassets-cache
63
+
64
+ # Scrapy stuff:
65
+ .scrapy
66
+
67
+ # Sphinx documentation
68
+ docs/_build/
69
+
70
+ # PyBuilder
71
+ target/
72
+
73
+ # Jupyter Notebook
74
+ .ipynb_checkpoints
75
+
76
+ # pyenv
77
+ .python-version
78
+
79
+ # celery beat schedule file
80
+ celerybeat-schedule
81
+
82
+ # SageMath parsed files
83
+ *.sage.py
84
+
85
+ # Environments
86
+ .env
87
+ .venv
88
+ env/
89
+ venv/
90
+ ENV/
91
+ env.bak/
92
+ venv.bak/
93
+
94
+ # Spyder project settings
95
+ .spyderproject
96
+ .spyproject
97
+
98
+ # Rope project settings
99
+ .ropeproject
100
+
101
+ # mkdocs documentation
102
+ /site
103
+
104
+ # mypy
105
+ .mypy_cache/
segmentation_models_pytorch/HALLOFFAME.md ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hall of Fame
2
+
3
+ `Segmentation Models` package is widely used in the image segmentation competitions.
4
+ Here you can find competitions, names of the winners and links to their solutions.
5
+
6
+ Please, follow these rules, when adding a solution to the "Hall of Fame":
7
+
8
+ 1. Solution should be high rated (e.g. for Kaggle gold or silver medal)
9
+ 2. There should be a description of the solution (post at the forum / code / blog post / paper / pre-print)
10
+
11
+
12
+ ## Kaggle
13
+
14
+ ### [Severstal: Steel Defect Detection](https://www.kaggle.com/c/severstal-steel-defect-detection)
15
+
16
+ - 1st place.
17
+ [Wuxi Jiangsu](https://www.kaggle.com/rguo97),
18
+ [Hongbo Zhu](https://www.kaggle.com/zhuhongbo),
19
+ [Yizhuo Yu](https://www.kaggle.com/paffpaffyu)
20
+ [[description](https://www.kaggle.com/c/severstal-steel-defect-detection/discussion/114254#latest-675874)]
21
+
22
+ - 5th place.
23
+ [Guanshuo Xu](https://www.kaggle.com/wowfattie)
24
+ [[description](https://www.kaggle.com/c/severstal-steel-defect-detection/discussion/117208#latest-675385)]
25
+
26
+ - 9th place.
27
+ [Jacek Poplawski](https://www.linkedin.com/in/jacekpoplawski/)
28
+ [[description](https://www.kaggle.com/c/severstal-steel-defect-detection/discussion/114297#latest-660842)]
29
+
30
+ - 10th place.
31
+ [Alexey Rozhkov](https://www.linkedin.com/in/alexisrozhkov)
32
+ [[description](https://www.kaggle.com/c/severstal-steel-defect-detection/discussion/114465#latest-659615)]
33
+
34
+ - 12th place.
35
+ [Pavel Yakubovskiy](https://www.linkedin.com/in/pavel-yakubovskiy/),
36
+ [Ilya Dobrynin](https://www.linkedin.com/in/ilya-dobrynin-79a89b106/),
37
+ [Denis Kolpakov](https://www.linkedin.com/in/denis-kolpakov-ab3137197/)
38
+ [[description](https://www.kaggle.com/c/severstal-steel-defect-detection/discussion/114309#latest-661404)]
39
+
40
+ - 31st place.
41
+ [Insaf Ashrapov](https://www.linkedin.com/in/iashrapov/),
42
+ [Igor Krashenyi](https://www.linkedin.com/in/igor-krashenyi-38b89b98),
43
+ [Pavel Pleskov](https://www.linkedin.com/in/ppleskov),
44
+ [Anton Zakharenkov](https://www.linkedin.com/in/anton-zakharenkov/),
45
+ [Nikolai Popov](https://www.linkedin.com/in/nikolai-popov-b2157370/)
46
+ [[description](https://www.kaggle.com/c/severstal-steel-defect-detection/discussion/114383#latest-658438)]
47
+ [[code](https://github.com/Diyago/Severstal-Steel-Defect-Detection)]
48
+
49
+ - 55th place.
50
+ [Karl Hornlund](https://www.linkedin.com/in/karl-hornlund/)
51
+ [[description](https://www.kaggle.com/c/severstal-steel-defect-detection/discussion/114410#latest-672682)]
52
+ [[code](https://github.com/khornlund/severstal-steel-defect-detection)]
53
+
54
+ - Efficiency round 1st place.
55
+ [Stefan Stefanov](https://www.linkedin.com/in/stefan-stefanov-63a77b1)
56
+ [[description](https://www.kaggle.com/c/severstal-steel-defect-detection/discussion/117486#latest-674229)]
57
+
58
+
59
+ ### [Understanding Clouds from Satellite Images](https://www.kaggle.com/c/understanding_cloud_organization)
60
+
61
+ - 2nd place.
62
+ [Andrey Kiryasov](https://www.kaggle.com/ekydna)
63
+ [[description](https://www.kaggle.com/c/understanding_cloud_organization/discussion/118255#latest-678189)]
64
+
65
+ - 4th place.
66
+ [Ching-Loong Seow](https://www.linkedin.com/in/clseow/)
67
+ [[description](https://www.kaggle.com/c/understanding_cloud_organization/discussion/118016#latest-677333)]
68
+
69
+ - 34th place.
70
+ [Karl Hornlund](https://www.linkedin.com/in/karl-hornlund/)
71
+ [[description](https://www.kaggle.com/c/understanding_cloud_organization/discussion/118250#latest-678176)]
72
+ [[code](https://github.com/khornlund/understanding-cloud-organization)]
73
+
74
+ - 55th place.
75
+ [Pavel Yakubovskiy](https://www.linkedin.com/in/pavel-yakubovskiy/)
76
+ [[description](https://www.kaggle.com/c/understanding_cloud_organization/discussion/118019#latest-678626)]
77
+
78
+ ## Other platforms
79
+
80
+ ### [MICCAI 2020 TN-SCUI challenge](https://tn-scui2020.grand-challenge.org/Home/)
81
+ - 1st place.
82
+ [Mingyu Wang](https://github.com/WAMAWAMA)
83
+ [[description](https://github.com/WAMAWAMA/TNSCUI2020-Seg-Rank1st)]
84
+ [[code](https://github.com/WAMAWAMA/TNSCUI2020-Seg-Rank1st)]
85
+
86
+ ### [Open Cities AI Challenge: Segmenting Buildings for Disaster Resilience](https://www.drivendata.org/competitions/60/building-segmentation-disaster-resilience/)
87
+ - 1st place.
88
+ [Pavel Yakubovskiy](https://www.linkedin.com/in/pavel-yakubovskiy/).
89
+ [[code and description](https://github.com/qubvel/open-cities-challenge)]
90
+
segmentation_models_pytorch/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License
2
+
3
+ Copyright (c) 2019, Pavel Yakubovskiy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
segmentation_models_pytorch/MANIFEST.in ADDED
@@ -0,0 +1 @@
 
 
1
+ include README.md LICENSE requirements.txt
segmentation_models_pytorch/README.md ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ ![logo](https://i.ibb.co/dc1XdhT/Segmentation-Models-V2-Side-1-1.png)
4
+ **Python library with Neural Networks for Image
5
+ Segmentation based on [PyTorch](https://pytorch.org/).**
6
+
7
+ [![Documentation Status](https://readthedocs.org/projects/smp/badge/?version=latest)](https://segmentation-models-pytorch.readthedocs.io/en/latest/?badge=latest) <br> [![Generic badge](https://img.shields.io/badge/License-MIT-<COLOR>.svg)](https://shields.io/)
8
+
9
+ </div>
10
+
11
+ The main features of this library are:
12
+
13
+ - High level API (just two lines to create a neural network)
14
+ - 12 models architectures for binary and multi class segmentation (including legendary Unet)
15
+ - 104 available encoders
16
+ - All encoders have pre-trained weights for faster and better convergence
17
+
18
+ ### [📚 Project Documentation 📚](http://smp.readthedocs.io/)
19
+
20
+ Visit [Read The Docs Project Page](https://segmentation-models-pytorch.readthedocs.io/en/latest/) or read following README to know more about Segmentation Models Pytorch (SMP for short) library
21
+
22
+ ### 📋 Table of content
23
+ 1. [Quick start](#start)
24
+ 2. [Examples](#examples)
25
+ 3. [Models](#models)
26
+ 1. [Architectures](#architectures)
27
+ 2. [Encoders](#encoders)
28
+ 4. [Models API](#api)
29
+ 1. [Input channels](#input-channels)
30
+ 2. [Auxiliary classification output](#auxiliary-classification-output)
31
+ 3. [Depth](#depth)
32
+ 5. [Installation](#installation)
33
+ 6. [Competitions won with the library](#competitions-won-with-the-library)
34
+ 7. [Contributing](#contributing)
35
+ 8. [Citing](#citing)
36
+ 9. [License](#license)
37
+
38
+ ### ⏳ Quick start <a name="start"></a>
39
+
40
+ #### 1. Create your first Segmentation model with SMP
41
+
42
+ Segmentation model is just a PyTorch nn.Module, which can be created as easy as:
43
+
44
+ ```python
45
+ import segmentation_models_pytorch as smp
46
+
47
+ model = smp.Unet(
48
+ encoder_name="resnet34", # choose encoder, e.g. mobilenet_v2 or efficientnet-b7
49
+ encoder_weights="imagenet", # use `imagenet` pre-trained weights for encoder initialization
50
+ in_channels=1, # model input channels (1 for gray-scale images, 3 for RGB, etc.)
51
+ classes=3, # model output channels (number of classes in your dataset)
52
+ )
53
+ ```
54
+ - see [table](#architectures) with available model architectures
55
+ - see [table](#encoders) with available encoders and their corresponding weights
56
+
57
+ #### 2. Configure data preprocessing
58
+
59
+ All encoders have pretrained weights. Preparing your data the same way as during weights pre-training may give your better results (higher metric score and faster convergence). But it is relevant only for 1-2-3-channels images and **not necessary** in case you train the whole model, not only decoder.
60
+
61
+ ```python
62
+ from segmentation_models_pytorch.encoders import get_preprocessing_fn
63
+
64
+ preprocess_input = get_preprocessing_fn('resnet18', pretrained='imagenet')
65
+ ```
66
+
67
+ Congratulations! You are done! Now you can train your model with your favorite framework!
68
+
69
+ ### 💡 Examples <a name="examples"></a>
70
+ - Training model for cars segmentation on CamVid dataset [here](https://github.com/qubvel/segmentation_models.pytorch/blob/master/examples/cars%20segmentation%20(camvid).ipynb).
71
+ - Training SMP model with [Catalyst](https://github.com/catalyst-team/catalyst) (high-level framework for PyTorch), [TTAch](https://github.com/qubvel/ttach) (TTA library for PyTorch) and [Albumentations](https://github.com/albu/albumentations) (fast image augmentation library) - [here](https://github.com/catalyst-team/catalyst/blob/master/examples/notebooks/segmentation-tutorial.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/catalyst-team/catalyst/blob/master/examples/notebooks/segmentation-tutorial.ipynb)
72
+ - Training SMP model with [Pytorch-Lightning](https://pytorch-lightning.readthedocs.io) framework - [here](https://github.com/ternaus/cloths_segmentation) (clothes binary segmentation by [@teranus](https://github.com/ternaus)).
73
+
74
+ ### 📦 Models <a name="models"></a>
75
+
76
+ #### Architectures <a name="architectures"></a>
77
+ - Unet [[paper](https://arxiv.org/abs/1505.04597)] [[docs](https://smp.readthedocs.io/en/latest/models.html#unet)]
78
+ - Unet++ [[paper1](https://arxiv.org/abs/1807.10165), [paper2](https://arxiv.org/abs/1912.05074)] [[docs](https://smp.readthedocs.io/en/latest/models.html#id2)]
79
+ - EfficientUNet++ [[paper]()] [[docs](https://segmentation-models-pytorch.readthedocs.io/en/latest/models.html#efficientunet)]
80
+ - ResUnet [[paper](https://arxiv.org/abs/1711.10684)] [[docs](https://segmentation-models-pytorch.readthedocs.io/en/latest/models.html#resunet)]
81
+ - ResUnet++ [[paper](https://arxiv.org/abs/1911.07067)] [[docs](https://segmentation-models-pytorch.readthedocs.io/en/latest/models.html#id4)]
82
+ - MAnet [[paper](https://ieeexplore.ieee.org/abstract/document/9201310)] [[docs](https://smp.readthedocs.io/en/latest/models.html#manet)]
83
+ - Linknet [[paper](https://arxiv.org/abs/1707.03718)] [[docs](https://smp.readthedocs.io/en/latest/models.html#linknet)]
84
+ - FPN [[paper](http://presentations.cocodataset.org/COCO17-Stuff-FAIR.pdf)] [[docs](https://smp.readthedocs.io/en/latest/models.html#fpn)]
85
+ - PSPNet [[paper](https://arxiv.org/abs/1612.01105)] [[docs](https://smp.readthedocs.io/en/latest/models.html#pspnet)]
86
+ - PAN [[paper](https://arxiv.org/abs/1805.10180)] [[docs](https://smp.readthedocs.io/en/latest/models.html#pan)]
87
+ - DeepLabV3 [[paper](https://arxiv.org/abs/1706.05587)] [[docs](https://smp.readthedocs.io/en/latest/models.html#deeplabv3)]
88
+ - DeepLabV3+ [[paper](https://arxiv.org/abs/1802.02611)] [[docs](https://smp.readthedocs.io/en/latest/models.html#id9)]
89
+
90
+ #### Encoders <a name="encoders"></a>
91
+
92
+ The following is a list of supported encoders in the SMP. Select the appropriate family of encoders and click to expand the table and select a specific encoder and its pre-trained weights (`encoder_name` and `encoder_weights` parameters).
93
+
94
+ <details>
95
+ <summary style="margin-left: 25px;">ResNet</summary>
96
+ <div style="margin-left: 25px;">
97
+
98
+ |Encoder |Weights |Params, M |
99
+ |--------------------------------|:------------------------------:|:------------------------------:|
100
+ |resnet18 |imagenet / ssl / swsl |11M |
101
+ |resnet34 |imagenet |21M |
102
+ |resnet50 |imagenet / ssl / swsl |23M |
103
+ |resnet101 |imagenet |42M |
104
+ |resnet152 |imagenet |58M |
105
+
106
+ </div>
107
+ </details>
108
+
109
+ <details>
110
+ <summary style="margin-left: 25px;">ResNeXt</summary>
111
+ <div style="margin-left: 25px;">
112
+
113
+ |Encoder |Weights |Params, M |
114
+ |--------------------------------|:------------------------------:|:------------------------------:|
115
+ |resnext50_32x4d |imagenet / ssl / swsl |22M |
116
+ |resnext101_32x4d |ssl / swsl |42M |
117
+ |resnext101_32x8d |imagenet / instagram / ssl / swsl|86M |
118
+ |resnext101_32x16d |instagram / ssl / swsl |191M |
119
+ |resnext101_32x32d |instagram |466M |
120
+ |resnext101_32x48d |instagram |826M |
121
+
122
+ </div>
123
+ </details>
124
+
125
+ <details>
126
+ <summary style="margin-left: 25px;">ResNeSt</summary>
127
+ <div style="margin-left: 25px;">
128
+
129
+ |Encoder |Weights |Params, M |
130
+ |--------------------------------|:------------------------------:|:------------------------------:|
131
+ |timm-resnest14d |imagenet |8M |
132
+ |timm-resnest26d |imagenet |15M |
133
+ |timm-resnest50d |imagenet |25M |
134
+ |timm-resnest101e |imagenet |46M |
135
+ |timm-resnest200e |imagenet |68M |
136
+ |timm-resnest269e |imagenet |108M |
137
+ |timm-resnest50d_4s2x40d |imagenet |28M |
138
+ |timm-resnest50d_1s4x24d |imagenet |23M |
139
+
140
+ </div>
141
+ </details>
142
+
143
+ <details>
144
+ <summary style="margin-left: 25px;">Res2Ne(X)t</summary>
145
+ <div style="margin-left: 25px;">
146
+
147
+ |Encoder |Weights |Params, M |
148
+ |--------------------------------|:------------------------------:|:------------------------------:|
149
+ |timm-res2net50_26w_4s |imagenet |23M |
150
+ |timm-res2net101_26w_4s |imagenet |43M |
151
+ |timm-res2net50_26w_6s |imagenet |35M |
152
+ |timm-res2net50_26w_8s |imagenet |46M |
153
+ |timm-res2net50_48w_2s |imagenet |23M |
154
+ |timm-res2net50_14w_8s |imagenet |23M |
155
+ |timm-res2next50 |imagenet |22M |
156
+
157
+ </div>
158
+ </details>
159
+
160
+ <details>
161
+ <summary style="margin-left: 25px;">RegNet(x/y)</summary>
162
+ <div style="margin-left: 25px;">
163
+
164
+ |Encoder |Weights |Params, M |
165
+ |--------------------------------|:------------------------------:|:------------------------------:|
166
+ |timm-regnetx_002 |imagenet |2M |
167
+ |timm-regnetx_004 |imagenet |4M |
168
+ |timm-regnetx_006 |imagenet |5M |
169
+ |timm-regnetx_008 |imagenet |6M |
170
+ |timm-regnetx_016 |imagenet |8M |
171
+ |timm-regnetx_032 |imagenet |14M |
172
+ |timm-regnetx_040 |imagenet |20M |
173
+ |timm-regnetx_064 |imagenet |24M |
174
+ |timm-regnetx_080 |imagenet |37M |
175
+ |timm-regnetx_120 |imagenet |43M |
176
+ |timm-regnetx_160 |imagenet |52M |
177
+ |timm-regnetx_320 |imagenet |105M |
178
+ |timm-regnety_002 |imagenet |2M |
179
+ |timm-regnety_004 |imagenet |3M |
180
+ |timm-regnety_006 |imagenet |5M |
181
+ |timm-regnety_008 |imagenet |5M |
182
+ |timm-regnety_016 |imagenet |10M |
183
+ |timm-regnety_032 |imagenet |17M |
184
+ |timm-regnety_040 |imagenet |19M |
185
+ |timm-regnety_064 |imagenet |29M |
186
+ |timm-regnety_080 |imagenet |37M |
187
+ |timm-regnety_120 |imagenet |49M |
188
+ |timm-regnety_160 |imagenet |80M |
189
+ |timm-regnety_320 |imagenet |141M |
190
+
191
+ </div>
192
+ </details>
193
+
194
+ <details>
195
+ <summary style="margin-left: 25px;">SE-Net</summary>
196
+ <div style="margin-left: 25px;">
197
+
198
+ |Encoder |Weights |Params, M |
199
+ |--------------------------------|:------------------------------:|:------------------------------:|
200
+ |senet154 |imagenet |113M |
201
+ |se_resnet50 |imagenet |26M |
202
+ |se_resnet101 |imagenet |47M |
203
+ |se_resnet152 |imagenet |64M |
204
+ |se_resnext50_32x4d |imagenet |25M |
205
+ |se_resnext101_32x4d |imagenet |46M |
206
+
207
+ </div>
208
+ </details>
209
+
210
+ <details>
211
+ <summary style="margin-left: 25px;">SK-ResNe(X)t</summary>
212
+ <div style="margin-left: 25px;">
213
+
214
+ |Encoder |Weights |Params, M |
215
+ |--------------------------------|:------------------------------:|:------------------------------:|
216
+ |timm-skresnet18 |imagenet |11M |
217
+ |timm-skresnet34 |imagenet |21M |
218
+ |timm-skresnext50_32x4d |imagenet |25M |
219
+
220
+ </div>
221
+ </details>
222
+
223
+ <details>
224
+ <summary style="margin-left: 25px;">DenseNet</summary>
225
+ <div style="margin-left: 25px;">
226
+
227
+ |Encoder |Weights |Params, M |
228
+ |--------------------------------|:------------------------------:|:------------------------------:|
229
+ |densenet121 |imagenet |6M |
230
+ |densenet169 |imagenet |12M |
231
+ |densenet201 |imagenet |18M |
232
+ |densenet161 |imagenet |26M |
233
+
234
+ </div>
235
+ </details>
236
+
237
+ <details>
238
+ <summary style="margin-left: 25px;">Inception</summary>
239
+ <div style="margin-left: 25px;">
240
+
241
+ |Encoder |Weights |Params, M |
242
+ |--------------------------------|:------------------------------:|:------------------------------:|
243
+ |inceptionresnetv2 |imagenet / imagenet+background |54M |
244
+ |inceptionv4 |imagenet / imagenet+background |41M |
245
+ |xception |imagenet |22M |
246
+
247
+ </div>
248
+ </details>
249
+
250
+ <details>
251
+ <summary style="margin-left: 25px;">EfficientNet</summary>
252
+ <div style="margin-left: 25px;">
253
+
254
+ |Encoder |Weights |Params, M |
255
+ |--------------------------------|:------------------------------:|:------------------------------:|
256
+ |efficientnet-b0 |imagenet |4M |
257
+ |efficientnet-b1 |imagenet |6M |
258
+ |efficientnet-b2 |imagenet |7M |
259
+ |efficientnet-b3 |imagenet |10M |
260
+ |efficientnet-b4 |imagenet |17M |
261
+ |efficientnet-b5 |imagenet |28M |
262
+ |efficientnet-b6 |imagenet |40M |
263
+ |efficientnet-b7 |imagenet |63M |
264
+ |timm-efficientnet-b0 |imagenet / advprop / noisy-student|4M |
265
+ |timm-efficientnet-b1 |imagenet / advprop / noisy-student|6M |
266
+ |timm-efficientnet-b2 |imagenet / advprop / noisy-student|7M |
267
+ |timm-efficientnet-b3 |imagenet / advprop / noisy-student|10M |
268
+ |timm-efficientnet-b4 |imagenet / advprop / noisy-student|17M |
269
+ |timm-efficientnet-b5 |imagenet / advprop / noisy-student|28M |
270
+ |timm-efficientnet-b6 |imagenet / advprop / noisy-student|40M |
271
+ |timm-efficientnet-b7 |imagenet / advprop / noisy-student|63M |
272
+ |timm-efficientnet-b8 |imagenet / advprop |84M |
273
+ |timm-efficientnet-l2 |noisy-student |474M |
274
+ |timm-efficientnet-lite0 |imagenet |4M |
275
+ |timm-efficientnet-lite1 |imagenet |5M |
276
+ |timm-efficientnet-lite2 |imagenet |6M |
277
+ |timm-efficientnet-lite3 |imagenet |8M |
278
+ |timm-efficientnet-lite4 |imagenet |13M |
279
+
280
+ </div>
281
+ </details>
282
+
283
+ <details>
284
+ <summary style="margin-left: 25px;">MobileNet</summary>
285
+ <div style="margin-left: 25px;">
286
+
287
+ |Encoder |Weights |Params, M |
288
+ |--------------------------------|:------------------------------:|:------------------------------:|
289
+ |mobilenet_v2 |imagenet |2M |
290
+
291
+ </div>
292
+ </details>
293
+
294
+ <details>
295
+ <summary style="margin-left: 25px;">DPN</summary>
296
+ <div style="margin-left: 25px;">
297
+
298
+ |Encoder |Weights |Params, M |
299
+ |--------------------------------|:------------------------------:|:------------------------------:|
300
+ |dpn68 |imagenet |11M |
301
+ |dpn68b |imagenet+5k |11M |
302
+ |dpn92 |imagenet+5k |34M |
303
+ |dpn98 |imagenet |58M |
304
+ |dpn107 |imagenet+5k |84M |
305
+ |dpn131 |imagenet |76M |
306
+
307
+ </div>
308
+ </details>
309
+
310
+ <details>
311
+ <summary style="margin-left: 25px;">VGG</summary>
312
+ <div style="margin-left: 25px;">
313
+
314
+ |Encoder |Weights |Params, M |
315
+ |--------------------------------|:------------------------------:|:------------------------------:|
316
+ |vgg11 |imagenet |9M |
317
+ |vgg11_bn |imagenet |9M |
318
+ |vgg13 |imagenet |9M |
319
+ |vgg13_bn |imagenet |9M |
320
+ |vgg16 |imagenet |14M |
321
+ |vgg16_bn |imagenet |14M |
322
+ |vgg19 |imagenet |20M |
323
+ |vgg19_bn |imagenet |20M |
324
+
325
+ </div>
326
+ </details>
327
+
328
+
329
+ \* `ssl`, `swsl` - semi-supervised and weakly-supervised learning on ImageNet ([repo](https://github.com/facebookresearch/semi-supervised-ImageNet1K-models)).
330
+
331
+
332
+ ### 🔁 Models API <a name="api"></a>
333
+
334
+ - `model.encoder` - pretrained backbone to extract features of different spatial resolution
335
+ - `model.decoder` - depends on models architecture (`Unet`/`Linknet`/`PSPNet`/`FPN`)
336
+ - `model.segmentation_head` - last block to produce required number of mask channels (include also optional upsampling and activation)
337
+ - `model.classification_head` - optional block which create classification head on top of encoder
338
+ - `model.forward(x)` - sequentially pass `x` through model\`s encoder, decoder and segmentation head (and classification head if specified)
339
+
340
+ ##### Input channels
341
+ Input channels parameter allows you to create models, which process tensors with arbitrary number of channels.
342
+ If you use pretrained weights from imagenet - weights of first convolution will be reused for
343
+ 1- or 2- channels inputs, for input channels > 4 weights of first convolution will be initialized randomly.
344
+ ```python
345
+ model = smp.FPN('resnet34', in_channels=1)
346
+ mask = model(torch.ones([1, 1, 64, 64]))
347
+ ```
348
+
349
+ ##### Auxiliary classification output
350
+ All models support `aux_params` parameters, which is default set to `None`.
351
+ If `aux_params = None` then classification auxiliary output is not created, else
352
+ model produce not only `mask`, but also `label` output with shape `NC`.
353
+ Classification head consists of GlobalPooling->Dropout(optional)->Linear->Activation(optional) layers, which can be
354
+ configured by `aux_params` as follows:
355
+ ```python
356
+ aux_params=dict(
357
+ pooling='avg', # one of 'avg', 'max'
358
+ dropout=0.5, # dropout ratio, default is None
359
+ activation='sigmoid', # activation function, default is None
360
+ classes=4, # define number of output labels
361
+ )
362
+ model = smp.Unet('resnet34', classes=4, aux_params=aux_params)
363
+ mask, label = model(x)
364
+ ```
365
+
366
+ ##### Depth
367
+ Depth parameter specify a number of downsampling operations in encoder, so you can make
368
+ your model lighter if specify smaller `depth`.
369
+ ```python
370
+ model = smp.Unet('resnet34', encoder_depth=4)
371
+ ```
372
+
373
+
374
+ ### 🛠 Installation <a name="installation"></a>
375
+ Latest version from source:
376
+ ```bash
377
+ $ pip install git+https://github.com/jlcsilva/segmentation_models.pytorch
378
+ ````
379
+
380
+ ### 🏆 Competitions won with the library
381
+
382
+ `Segmentation Models` package is widely used in the image segmentation competitions.
383
+ [Here](https://github.com/qubvel/segmentation_models.pytorch/blob/master/HALLOFFAME.md) you can find competitions, names of the winners and links to their solutions.
384
+
385
+ ### 🤝 Contributing
386
+
387
+ ##### Run test
388
+ ```bash
389
+ $ docker build -f docker/Dockerfile.dev -t smp:dev . && docker run --rm smp:dev pytest -p no:cacheprovider
390
+ ```
391
+ ##### Generate table
392
+ ```bash
393
+ $ docker build -f docker/Dockerfile.dev -t smp:dev . && docker run --rm smp:dev python misc/generate_table.py
394
+ ```
395
+
396
+ ### 📝 Citing
397
+ ```
398
+ @misc{Yakubovskiy:2019,
399
+ Author = {Pavel Yakubovskiy},
400
+ Title = {Segmentation Models Pytorch},
401
+ Year = {2020},
402
+ Publisher = {GitHub},
403
+ Journal = {GitHub repository},
404
+ Howpublished = {\url{https://github.com/qubvel/segmentation_models.pytorch}}
405
+ }
406
+ ```
407
+
408
+ ### 🛡️ License <a name="license"></a>
409
+ Project is distributed under [MIT License](https://github.com/qubvel/segmentation_models.pytorch/blob/master/LICENSE)
segmentation_models_pytorch/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from segmentation_models_pytorch import *
segmentation_models_pytorch/docker/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM anibali/pytorch:cuda-9.0
2
+
3
+ RUN pip install segmentation-models-pytorch
segmentation_models_pytorch/docker/Dockerfile.dev ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM anibali/pytorch:1.5.0-nocuda
2
+
3
+ WORKDIR /tmp/smp/
4
+
5
+ COPY ./requirements.txt /tmp/smp/requirements.txt
6
+ RUN pip install -r requirements.txt
7
+ RUN pip install pytest mock
8
+
9
+ COPY . /tmp/smp/
10
+ RUN pip install .
segmentation_models_pytorch/docs/Makefile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Minimal makefile for Sphinx documentation
2
+ #
3
+
4
+ # You can set these variables from the command line, and also
5
+ # from the environment for the first two.
6
+ SPHINXOPTS ?=
7
+ SPHINXBUILD ?= sphinx-build
8
+ SOURCEDIR = .
9
+ BUILDDIR = build
10
+
11
+ # Put it first so that "make" without argument is like "make help".
12
+ help:
13
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14
+
15
+ .PHONY: help Makefile
16
+
17
+ # Catch-all target: route all unknown targets to Sphinx using the new
18
+ # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19
+ %: Makefile
20
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
segmentation_models_pytorch/docs/conf.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration file for the Sphinx documentation builder.
2
+ #
3
+ # This file only contains a selection of the most common options. For a full
4
+ # list see the documentation:
5
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html
6
+
7
+ # -- Path setup --------------------------------------------------------------
8
+
9
+ # If extensions (or modules to document with autodoc) are in another directory,
10
+ # add these directories to sys.path here. If the directory is relative to the
11
+ # documentation root, use os.path.abspath to make it absolute, like shown here.
12
+ #
13
+ # import os
14
+ # import sys
15
+ # sys.path.insert(0, os.path.abspath('.'))
16
+
17
+ import os
18
+ import re
19
+ import sys
20
+ import datetime
21
+ sys.path.append('..')
22
+
23
+ # -- Project information -----------------------------------------------------
24
+
25
+ project = 'Segmentation Models'
26
+ copyright = '{}, Pavel Yakubovskiy'.format(datetime.datetime.now().year)
27
+ author = 'Pavel Yakubovskiy'
28
+
29
+ def get_version():
30
+ sys.path.append('../segmentation_models_pytorch')
31
+ from __version__ import __version__ as version
32
+ sys.path.pop(-1)
33
+ return version
34
+
35
+ version = get_version()
36
+
37
+ # -- General configuration ---------------------------------------------------
38
+
39
+ # Add any Sphinx extension module names here, as strings. They can be
40
+ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
41
+ # ones.
42
+
43
+ extensions = [
44
+ 'sphinx.ext.autodoc',
45
+ 'sphinx.ext.coverage',
46
+ 'sphinx.ext.napoleon',
47
+ 'sphinx.ext.viewcode',
48
+ 'sphinx.ext.mathjax',
49
+ ]
50
+
51
+ # Add any paths that contain templates here, relative to this directory.
52
+ templates_path = ['_templates']
53
+
54
+ # List of patterns, relative to source directory, that match files and
55
+ # directories to ignore when looking for source files.
56
+ # This pattern also affects html_static_path and html_extra_path.
57
+ exclude_patterns = []
58
+
59
+
60
+ # -- Options for HTML output -------------------------------------------------
61
+
62
+ # The theme to use for HTML and HTML Help pages. See the documentation for
63
+ # a list of builtin themes.
64
+ #
65
+
66
+ import sphinx_rtd_theme
67
+ html_theme = "sphinx_rtd_theme"
68
+ html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
69
+
70
+ # import karma_sphinx_theme
71
+ # html_theme = "karma_sphinx_theme"
72
+ import faculty_sphinx_theme
73
+ html_theme = "faculty_sphinx_theme"
74
+
75
+ # import catalyst_sphinx_theme
76
+ # html_theme = "catalyst_sphinx_theme"
77
+ # html_theme_path = [catalyst_sphinx_theme.get_html_theme_path()]
78
+
79
+ html_logo = "logo.png"
80
+
81
+ # Add any paths that contain custom static files (such as style sheets) here,
82
+ # relative to this directory. They are copied after the builtin static files,
83
+ # so a file named "default.css" will overwrite the builtin "default.css".
84
+ html_static_path = ['_static']
85
+
86
+ # -- Extension configuration -------------------------------------------------
87
+
88
+ autodoc_inherit_docstrings = False
89
+ napoleon_google_docstring = True
90
+ napoleon_include_init_with_doc = True
91
+ napoleon_numpy_docstring = False
92
+
93
+ autodoc_mock_imports = [
94
+ 'torch',
95
+ 'tqdm',
96
+ 'numpy',
97
+ 'timm',
98
+ 'pretrainedmodels',
99
+ 'torchvision',
100
+ 'efficientnet-pytorch',
101
+ 'segmentation_models_pytorch.encoders',
102
+ 'segmentation_models_pytorch.utils',
103
+ # 'segmentation_models_pytorch.base',
104
+ ]
105
+
106
+ autoclass_content = 'both'
107
+ autodoc_typehints = 'description'
108
+
109
+ # --- Work around to make autoclass signatures not (*args, **kwargs) ----------
110
+
111
+ class FakeSignature():
112
+ def __getattribute__(self, *args):
113
+ raise ValueError
114
+
115
+ def f(app, obj, bound_method):
116
+ if "__new__" in obj.__name__:
117
+ obj.__signature__ = FakeSignature()
118
+
119
+ def setup(app):
120
+ app.connect('autodoc-before-process-signature', f)
segmentation_models_pytorch/docs/encoders.rst ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 🏔 Available Encoders
2
+ =====================
3
+
4
+ ResNet
5
+ ~~~~~~
6
+
7
+ +-------------+-------------------------+-------------+
8
+ | Encoder | Weights | Params, M |
9
+ +=============+=========================+=============+
10
+ | resnet18 | imagenet / ssl / swsl | 11M |
11
+ +-------------+-------------------------+-------------+
12
+ | resnet34 | imagenet | 21M |
13
+ +-------------+-------------------------+-------------+
14
+ | resnet50 | imagenet / ssl / swsl | 23M |
15
+ +-------------+-------------------------+-------------+
16
+ | resnet101 | imagenet | 42M |
17
+ +-------------+-------------------------+-------------+
18
+ | resnet152 | imagenet | 58M |
19
+ +-------------+-------------------------+-------------+
20
+
21
+ ResNeXt
22
+ ~~~~~~~
23
+
24
+ +----------------------+-------------------------------------+-------------+
25
+ | Encoder | Weights | Params, M |
26
+ +======================+=====================================+=============+
27
+ | resnext50\_32x4d | imagenet / ssl / swsl | 22M |
28
+ +----------------------+-------------------------------------+-------------+
29
+ | resnext101\_32x4d | ssl / swsl | 42M |
30
+ +----------------------+-------------------------------------+-------------+
31
+ | resnext101\_32x8d | imagenet / instagram / ssl / swsl | 86M |
32
+ +----------------------+-------------------------------------+-------------+
33
+ | resnext101\_32x16d | instagram / ssl / swsl | 191M |
34
+ +----------------------+-------------------------------------+-------------+
35
+ | resnext101\_32x32d | instagram | 466M |
36
+ +----------------------+-------------------------------------+-------------+
37
+ | resnext101\_32x48d | instagram | 826M |
38
+ +----------------------+-------------------------------------+-------------+
39
+
40
+ ResNeSt
41
+ ~~~~~~~
42
+
43
+ +----------------------------+------------+-------------+
44
+ | Encoder | Weights | Params, M |
45
+ +============================+============+=============+
46
+ | timm-resnest14d | imagenet | 8M |
47
+ +----------------------------+------------+-------------+
48
+ | timm-resnest26d | imagenet | 15M |
49
+ +----------------------------+------------+-------------+
50
+ | timm-resnest50d | imagenet | 25M |
51
+ +----------------------------+------------+-------------+
52
+ | timm-resnest101e | imagenet | 46M |
53
+ +----------------------------+------------+-------------+
54
+ | timm-resnest200e | imagenet | 68M |
55
+ +----------------------------+------------+-------------+
56
+ | timm-resnest269e | imagenet | 108M |
57
+ +----------------------------+------------+-------------+
58
+ | timm-resnest50d\_4s2x40d | imagenet | 28M |
59
+ +----------------------------+------------+-------------+
60
+ | timm-resnest50d\_1s4x24d | imagenet | 23M |
61
+ +----------------------------+------------+-------------+
62
+
63
+ Res2Ne(X)t
64
+ ~~~~~~~~~~
65
+
66
+ +----------------------------+------------+-------------+
67
+ | Encoder | Weights | Params, M |
68
+ +============================+============+=============+
69
+ | timm-res2net50\_26w\_4s | imagenet | 23M |
70
+ +----------------------------+------------+-------------+
71
+ | timm-res2net101\_26w\_4s | imagenet | 43M |
72
+ +----------------------------+------------+-------------+
73
+ | timm-res2net50\_26w\_6s | imagenet | 35M |
74
+ +----------------------------+------------+-------------+
75
+ | timm-res2net50\_26w\_8s | imagenet | 46M |
76
+ +----------------------------+------------+-------------+
77
+ | timm-res2net50\_48w\_2s | imagenet | 23M |
78
+ +----------------------------+------------+-------------+
79
+ | timm-res2net50\_14w\_8s | imagenet | 23M |
80
+ +----------------------------+------------+-------------+
81
+ | timm-res2next50 | imagenet | 22M |
82
+ +----------------------------+------------+-------------+
83
+
84
+ RegNet(x/y)
85
+ ~~~~~~~~~~~
86
+
87
+ +---------------------+------------+-------------+
88
+ | Encoder | Weights | Params, M |
89
+ +=====================+============+=============+
90
+ | timm-regnetx\_002 | imagenet | 2M |
91
+ +---------------------+------------+-------------+
92
+ | timm-regnetx\_004 | imagenet | 4M |
93
+ +---------------------+------------+-------------+
94
+ | timm-regnetx\_006 | imagenet | 5M |
95
+ +---------------------+------------+-------------+
96
+ | timm-regnetx\_008 | imagenet | 6M |
97
+ +---------------------+------------+-------------+
98
+ | timm-regnetx\_016 | imagenet | 8M |
99
+ +---------------------+------------+-------------+
100
+ | timm-regnetx\_032 | imagenet | 14M |
101
+ +---------------------+------------+-------------+
102
+ | timm-regnetx\_040 | imagenet | 20M |
103
+ +---------------------+------------+-------------+
104
+ | timm-regnetx\_064 | imagenet | 24M |
105
+ +---------------------+------------+-------------+
106
+ | timm-regnetx\_080 | imagenet | 37M |
107
+ +---------------------+------------+-------------+
108
+ | timm-regnetx\_120 | imagenet | 43M |
109
+ +---------------------+------------+-------------+
110
+ | timm-regnetx\_160 | imagenet | 52M |
111
+ +---------------------+------------+-------------+
112
+ | timm-regnetx\_320 | imagenet | 105M |
113
+ +---------------------+------------+-------------+
114
+ | timm-regnety\_002 | imagenet | 2M |
115
+ +---------------------+------------+-------------+
116
+ | timm-regnety\_004 | imagenet | 3M |
117
+ +---------------------+------------+-------------+
118
+ | timm-regnety\_006 | imagenet | 5M |
119
+ +---------------------+------------+-------------+
120
+ | timm-regnety\_008 | imagenet | 5M |
121
+ +---------------------+------------+-------------+
122
+ | timm-regnety\_016 | imagenet | 10M |
123
+ +---------------------+------------+-------------+
124
+ | timm-regnety\_032 | imagenet | 17M |
125
+ +---------------------+------------+-------------+
126
+ | timm-regnety\_040 | imagenet | 19M |
127
+ +---------------------+------------+-------------+
128
+ | timm-regnety\_064 | imagenet | 29M |
129
+ +---------------------+------------+-------------+
130
+ | timm-regnety\_080 | imagenet | 37M |
131
+ +---------------------+------------+-------------+
132
+ | timm-regnety\_120 | imagenet | 49M |
133
+ +---------------------+------------+-------------+
134
+ | timm-regnety\_160 | imagenet | 80M |
135
+ +---------------------+------------+-------------+
136
+ | timm-regnety\_320 | imagenet | 141M |
137
+ +---------------------+------------+-------------+
138
+
139
+ SE-Net
140
+ ~~~~~~
141
+
142
+ +-------------------------+------------+-------------+
143
+ | Encoder | Weights | Params, M |
144
+ +=========================+============+=============+
145
+ | senet154 | imagenet | 113M |
146
+ +-------------------------+------------+-------------+
147
+ | se\_resnet50 | imagenet | 26M |
148
+ +-------------------------+------------+-------------+
149
+ | se\_resnet101 | imagenet | 47M |
150
+ +-------------------------+------------+-------------+
151
+ | se\_resnet152 | imagenet | 64M |
152
+ +-------------------------+------------+-------------+
153
+ | se\_resnext50\_32x4d | imagenet | 25M |
154
+ +-------------------------+------------+-------------+
155
+ | se\_resnext101\_32x4d | imagenet | 46M |
156
+ +-------------------------+------------+-------------+
157
+
158
+ SK-ResNe(X)t
159
+ ~~~~~~~~~~~~
160
+
161
+ +---------------------------+------------+-------------+
162
+ | Encoder | Weights | Params, M |
163
+ +===========================+============+=============+
164
+ | timm-skresnet18 | imagenet | 11M |
165
+ +---------------------------+------------+-------------+
166
+ | timm-skresnet34 | imagenet | 21M |
167
+ +---------------------------+------------+-------------+
168
+ | timm-skresnext50\_32x4d | imagenet | 25M |
169
+ +---------------------------+------------+-------------+
170
+
171
+ DenseNet
172
+ ~~~~~~~~
173
+
174
+ +---------------+------------+-------------+
175
+ | Encoder | Weights | Params, M |
176
+ +===============+============+=============+
177
+ | densenet121 | imagenet | 6M |
178
+ +---------------+------------+-------------+
179
+ | densenet169 | imagenet | 12M |
180
+ +---------------+------------+-------------+
181
+ | densenet201 | imagenet | 18M |
182
+ +---------------+------------+-------------+
183
+ | densenet161 | imagenet | 26M |
184
+ +---------------+------------+-------------+
185
+
186
+ Inception
187
+ ~~~~~~~~~
188
+
189
+ +---------------------+----------------------------------+-------------+
190
+ | Encoder | Weights | Params, M |
191
+ +=====================+==================================+=============+
192
+ | inceptionresnetv2 | imagenet / imagenet+background | 54M |
193
+ +---------------------+----------------------------------+-------------+
194
+ | inceptionv4 | imagenet / imagenet+background | 41M |
195
+ +---------------------+----------------------------------+-------------+
196
+ | xception | imagenet | 22M |
197
+ +---------------------+----------------------------------+-------------+
198
+
199
+ EfficientNet
200
+ ~~~~~~~~~~~~
201
+
202
+ +------------------------+--------------------------------------+-------------+
203
+ | Encoder | Weights | Params, M |
204
+ +========================+======================================+=============+
205
+ | efficientnet-b0 | imagenet | 4M |
206
+ +------------------------+--------------------------------------+-------------+
207
+ | efficientnet-b1 | imagenet | 6M |
208
+ +------------------------+--------------------------------------+-------------+
209
+ | efficientnet-b2 | imagenet | 7M |
210
+ +------------------------+--------------------------------------+-------------+
211
+ | efficientnet-b3 | imagenet | 10M |
212
+ +------------------------+--------------------------------------+-------------+
213
+ | efficientnet-b4 | imagenet | 17M |
214
+ +------------------------+--------------------------------------+-------------+
215
+ | efficientnet-b5 | imagenet | 28M |
216
+ +------------------------+--------------------------------------+-------------+
217
+ | efficientnet-b6 | imagenet | 40M |
218
+ +------------------------+--------------------------------------+-------------+
219
+ | efficientnet-b7 | imagenet | 63M |
220
+ +------------------------+--------------------------------------+-------------+
221
+ | timm-efficientnet-b0 | imagenet / advprop / noisy-student | 4M |
222
+ +------------------------+--------------------------------------+-------------+
223
+ | timm-efficientnet-b1 | imagenet / advprop / noisy-student | 6M |
224
+ +------------------------+--------------------------------------+-------------+
225
+ | timm-efficientnet-b2 | imagenet / advprop / noisy-student | 7M |
226
+ +------------------------+--------------------------------------+-------------+
227
+ | timm-efficientnet-b3 | imagenet / advprop / noisy-student | 10M |
228
+ +------------------------+--------------------------------------+-------------+
229
+ | timm-efficientnet-b4 | imagenet / advprop / noisy-student | 17M |
230
+ +------------------------+--------------------------------------+-------------+
231
+ | timm-efficientnet-b5 | imagenet / advprop / noisy-student | 28M |
232
+ +------------------------+--------------------------------------+-------------+
233
+ | timm-efficientnet-b6 | imagenet / advprop / noisy-student | 40M |
234
+ +------------------------+--------------------------------------+-------------+
235
+ | timm-efficientnet-b7 | imagenet / advprop / noisy-student | 63M |
236
+ +------------------------+--------------------------------------+-------------+
237
+ | timm-efficientnet-b8 | imagenet / advprop | 84M |
238
+ +------------------------+--------------------------------------+-------------+
239
+ | timm-efficientnet-l2 | noisy-student | 474M |
240
+ +------------------------+--------------------------------------+-------------+
241
+ | timm-efficientnet-lite0| imagenet | 4M |
242
+ +------------------------+--------------------------------------+-------------+
243
+ | timm-efficientnet-lite1| imagenet | 4M |
244
+ +------------------------+--------------------------------------+-------------+
245
+ | timm-efficientnet-lite2| imagenet | 6M |
246
+ +------------------------+--------------------------------------+-------------+
247
+ | timm-efficientnet-lite3| imagenet | 8M |
248
+ +------------------------+--------------------------------------+-------------+
249
+ | timm-efficientnet-lite4| imagenet | 13M |
250
+ +------------------------+--------------------------------------+-------------+
251
+
252
+ MobileNet
253
+ ~~~~~~~~~
254
+
255
+ +-----------------+------------+-------------+
256
+ | Encoder | Weights | Params, M |
257
+ +=================+============+=============+
258
+ | mobilenet\_v2 | imagenet | 2M |
259
+ +-----------------+------------+-------------+
260
+
261
+ DPN
262
+ ~~~
263
+
264
+ +-----------+---------------+-------------+
265
+ | Encoder | Weights | Params, M |
266
+ +===========+===============+=============+
267
+ | dpn68 | imagenet | 11M |
268
+ +-----------+---------------+-------------+
269
+ | dpn68b | imagenet+5k | 11M |
270
+ +-----------+---------------+-------------+
271
+ | dpn92 | imagenet+5k | 34M |
272
+ +-----------+---------------+-------------+
273
+ | dpn98 | imagenet | 58M |
274
+ +-----------+---------------+-------------+
275
+ | dpn107 | imagenet+5k | 84M |
276
+ +-----------+---------------+-------------+
277
+ | dpn131 | imagenet | 76M |
278
+ +-----------+---------------+-------------+
279
+
280
+ VGG
281
+ ~~~
282
+
283
+ +-------------+------------+-------------+
284
+ | Encoder | Weights | Params, M |
285
+ +=============+============+=============+
286
+ | vgg11 | imagenet | 9M |
287
+ +-------------+------------+-------------+
288
+ | vgg11\_bn | imagenet | 9M |
289
+ +-------------+------------+-------------+
290
+ | vgg13 | imagenet | 9M |
291
+ +-------------+------------+-------------+
292
+ | vgg13\_bn | imagenet | 9M |
293
+ +-------------+------------+-------------+
294
+ | vgg16 | imagenet | 14M |
295
+ +-------------+------------+-------------+
296
+ | vgg16\_bn | imagenet | 14M |
297
+ +-------------+------------+-------------+
298
+ | vgg19 | imagenet | 20M |
299
+ +-------------+------------+-------------+
300
+ | vgg19\_bn | imagenet | 20M |
301
+ +-------------+------------+-------------+
segmentation_models_pytorch/docs/index.rst ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. Segmentation Models documentation master file, created by
2
+ sphinx-quickstart on Fri Nov 27 00:00:20 2020.
3
+ You can adapt this file completely to your liking, but it should at least
4
+ contain the root `toctree` directive.
5
+
6
+ Welcome to Segmentation Models's documentation!
7
+ ===============================================
8
+
9
+ .. toctree::
10
+ :maxdepth: 2
11
+ :caption: Contents:
12
+
13
+ install
14
+ quickstart
15
+ models
16
+ encoders
17
+ losses
18
+ insights
19
+
20
+
21
+ Indices and tables
22
+ ==================
23
+
24
+ * :ref:`genindex`
25
+ * :ref:`modindex`
26
+ * :ref:`search`
segmentation_models_pytorch/docs/insights.rst ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 🔧 Insights
2
+ ===========
3
+
4
+ 1. Models architecture
5
+ ~~~~~~~~~~~~~~~~~~~~~~
6
+
7
+ All segmentation models in SMP (this library short name) are made of:
8
+
9
+ - encoder (feature extractor, a.k.a backbone)
10
+ - decoder (features fusion block to create segmentation *mask*)
11
+ - segmentation head (final head to reduce number of channels from decoder and upsample mask to preserve input-output spatial resolution identity)
12
+ - classification head (optional head which build on top of deepest encoder features)
13
+
14
+
15
+ 2. Creating your own encoder
16
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
17
+
18
+ Encoder is a "classification model" which extract features from image and pass it to decoder.
19
+ Each encoder should have following attributes and methods and be inherited from `segmentation_models_pytorch.encoders._base.EncoderMixin`
20
+
21
+ .. code-block:: python
22
+
23
+ class MyEncoder(torch.nn.Module, EncoderMixin):
24
+
25
+ def __init__(self, **kwargs):
26
+ super().__init__()
27
+
28
+ # A number of channels for each encoder feature tensor, list of integers
29
+ self._out_channels: List[int] = [3, 16, 64, 128, 256, 512]
30
+
31
+ # A number of stages in decoder (in other words number of downsampling operations), integer
32
+ # use in in forward pass to reduce number of returning features
33
+ self._depth: int = 5
34
+
35
+ # Default number of input channels in first Conv2d layer for encoder (usually 3)
36
+ self._in_channels: int = 3
37
+
38
+ # Define encoder modules below
39
+ ...
40
+
41
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
42
+ """Produce list of features of different spatial resolutions, each feature is a 4D torch.tensor of
43
+ shape NCHW (features should be sorted in descending order according to spatial resolution, starting
44
+ with resolution same as input `x` tensor).
45
+
46
+ Input: `x` with shape (1, 3, 64, 64)
47
+ Output: [f0, f1, f2, f3, f4, f5] - features with corresponding shapes
48
+ [(1, 3, 64, 64), (1, 64, 32, 32), (1, 128, 16, 16), (1, 256, 8, 8),
49
+ (1, 512, 4, 4), (1, 1024, 2, 2)] (C - dim may differ)
50
+
51
+ also should support number of features according to specified depth, e.g. if depth = 5,
52
+ number of feature tensors = 6 (one with same resolution as input and 5 downsampled),
53
+ depth = 3 -> number of feature tensors = 4 (one with same resolution as input and 3 downsampled).
54
+ """
55
+
56
+ return [feat1, feat2, feat3, feat4, feat5, feat6]
57
+
58
+ When you write your own Encoder class register its build parameters
59
+
60
+ .. code-block:: python
61
+
62
+ smp.encoders.encoders["my_awesome_encoder"] = {
63
+ "encoder": MyEncoder, # encoder class here
64
+ "pretrained_settings": {
65
+ "imagenet": {
66
+ "mean": [0.485, 0.456, 0.406],
67
+ "std": [0.229, 0.224, 0.225],
68
+ "url": "https://some-url.com/my-model-weights",
69
+ "input_space": "RGB",
70
+ "input_range": [0, 1],
71
+ },
72
+ },
73
+ "params": {
74
+ # init params for encoder if any
75
+ },
76
+ },
77
+
78
+ Now you can use your encoder
79
+
80
+ .. code-block:: python
81
+
82
+ model = smp.Unet(encoder_name="my_awesome_encoder")
83
+
84
+ For better understanding see more examples of encoder in smp.encoders module.
85
+
86
+ .. note::
87
+
88
+ If it works fine, don`t forget to contribute your work and make a PR to SMP 😉
89
+
90
+ 3. Aux classification output
91
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
92
+
93
+ All models support ``aux_params`` parameter, which is default set to ``None``.
94
+ If ``aux_params = None`` than classification auxiliary output is not created, else
95
+ model produce not only ``mask``, but also ``label`` output with shape ``(N, C)``.
96
+
97
+ Classification head consist of following layers:
98
+
99
+ 1. GlobalPooling
100
+ 2. Dropout (optional)
101
+ 3. Linear
102
+ 4. Activation (optional)
103
+
104
+ Example:
105
+
106
+ .. code-block:: python
107
+
108
+ aux_params=dict(
109
+ pooling='avg', # one of 'avg', 'max'
110
+ dropout=0.5, # dropout ratio, default is None
111
+ activation='sigmoid', # activation function, default is None
112
+ classes=4, # define number of output labels
113
+ )
114
+
115
+ model = smp.Unet('resnet34', classes=4, aux_params=aux_params)
116
+ mask, label = model(x)
117
+
118
+ mask.shape, label.shape
119
+ # (N, 4, H, W), (N, 4)
segmentation_models_pytorch/docs/install.rst ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ 🛠 Installation
2
+ ===============
3
+
4
+ Latest version from source:
5
+
6
+ .. code-block:: bash
7
+
8
+ $ pip install -U git+https://github.com/jlcsilva/segmentation_models.pytorch
segmentation_models_pytorch/docs/losses.rst ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 📉 Losses
2
+ =========
3
+
4
+ Collection of popular semantic segmentation losses. Adapted from
5
+ an awesome repo with pytorch utils https://github.com/BloodAxe/pytorch-toolbelt
6
+
7
+ Constants
8
+ ~~~~~~~~~
9
+ .. automodule:: segmentation_models_pytorch.losses.constants
10
+ :members:
11
+
12
+ JaccardLoss
13
+ ~~~~~~~~~~~
14
+ .. autoclass:: segmentation_models_pytorch.losses.JaccardLoss
15
+
16
+ DiceLoss
17
+ ~~~~~~~~
18
+ .. autoclass:: segmentation_models_pytorch.losses.DiceLoss
19
+
20
+ FocalLoss
21
+ ~~~~~~~~~
22
+ .. autoclass:: segmentation_models_pytorch.losses.FocalLoss
23
+
24
+ LovaszLoss
25
+ ~~~~~~~~~~
26
+ .. autoclass:: segmentation_models_pytorch.losses.LovaszLoss
27
+
28
+ SoftBCEWithLogitsLoss
29
+ ~~~~~~~~~~~~~~~~~~~~~
30
+ .. autoclass:: segmentation_models_pytorch.losses.SoftBCEWithLogitsLoss
31
+
32
+ SoftCrossEntropyLoss
33
+ ~~~~~~~~~~~~~~~~~~~~
34
+ .. autoclass:: segmentation_models_pytorch.losses.SoftCrossEntropyLoss
segmentation_models_pytorch/docs/make.bat ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @ECHO OFF
2
+
3
+ pushd %~dp0
4
+
5
+ REM Command file for Sphinx documentation
6
+
7
+ if "%SPHINXBUILD%" == "" (
8
+ set SPHINXBUILD=sphinx-build
9
+ )
10
+ set SOURCEDIR=source
11
+ set BUILDDIR=build
12
+
13
+ if "%1" == "" goto help
14
+
15
+ %SPHINXBUILD% >NUL 2>NUL
16
+ if errorlevel 9009 (
17
+ echo.
18
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
19
+ echo.installed, then set the SPHINXBUILD environment variable to point
20
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
21
+ echo.may add the Sphinx directory to PATH.
22
+ echo.
23
+ echo.If you don't have Sphinx installed, grab it from
24
+ echo.http://sphinx-doc.org/
25
+ exit /b 1
26
+ )
27
+
28
+ %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
29
+ goto end
30
+
31
+ :help
32
+ %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
33
+
34
+ :end
35
+ popd
segmentation_models_pytorch/docs/models.rst ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 📦 Segmentation Models
2
+ ==============================
3
+
4
+ Unet
5
+ ~~~~
6
+ .. autoclass:: segmentation_models_pytorch.Unet
7
+
8
+ Unet++
9
+ ~~~~~~
10
+ .. autoclass:: segmentation_models_pytorch.UnetPlusPlus
11
+
12
+ EfficientUNet++
13
+ ~~~~~~~~~~~~~~~
14
+ .. autoclass:: segmentation_models_pytorch.EfficientUnetPlusPlus
15
+
16
+ ResUnet
17
+ ~~~~~~~
18
+ .. autoclass:: segmentation_models_pytorch.ResUnet
19
+
20
+ ResUnet++
21
+ ~~~~~~~~~
22
+ .. autoclass:: segmentation_models_pytorch.ResUnetPlusPlus
23
+
24
+ MAnet
25
+ ~~~~~~
26
+ .. autoclass:: segmentation_models_pytorch.MAnet
27
+
28
+ Linknet
29
+ ~~~~~~~
30
+ .. autoclass:: segmentation_models_pytorch.Linknet
31
+
32
+ FPN
33
+ ~~~
34
+ .. autoclass:: segmentation_models_pytorch.FPN
35
+
36
+ PSPNet
37
+ ~~~~~~
38
+ .. autoclass:: segmentation_models_pytorch.PSPNet
39
+
40
+ PAN
41
+ ~~~
42
+ .. autoclass:: segmentation_models_pytorch.PAN
43
+
44
+ DeepLabV3
45
+ ~~~~~~~~~
46
+ .. autoclass:: segmentation_models_pytorch.DeepLabV3
47
+
48
+ DeepLabV3+
49
+ ~~~~~~~~~~
50
+ .. autoclass:: segmentation_models_pytorch.DeepLabV3Plus
51
+
52
+
segmentation_models_pytorch/docs/quickstart.rst ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ⏳ Quick Start
2
+ ==============
3
+
4
+ **1. Create segmentation model**
5
+
6
+ Segmentation model is just a PyTorch nn.Module, which can be created as easy as:
7
+
8
+ .. code-block:: python
9
+
10
+ import segmentation_models_pytorch as smp
11
+
12
+ model = smp.Unet(
13
+ encoder_name="resnet34", # choose encoder, e.g. mobilenet_v2 or efficientnet-b7
14
+ encoder_weights="imagenet", # use `imagenet` pre-trained weights for encoder initialization
15
+ in_channels=1, # model input channels (1 for gray-scale images, 3 for RGB, etc.)
16
+ classes=3, # model output channels (number of classes in your dataset)
17
+ )
18
+
19
+ - see table with available model architectures
20
+ - see table with avaliable encoders and its corresponding weights
21
+
22
+ **2. Configure data preprocessing**
23
+
24
+ All encoders have pretrained weights. Preparing your data the same way as during weights pre-training may give your better results (higher metric score and faster convergence). But it is relevant only for 1-2-3-channels images and **not necessary** in case you train the whole model, not only decoder.
25
+
26
+ .. code-block:: python
27
+
28
+ from segmentation_models_pytorch.encoders import get_preprocessing_fn
29
+
30
+ preprocess_input = get_preprocessing_fn('resnet18', pretrained='imagenet')
31
+
32
+
33
+ **3. Congratulations!** 🎉
34
+
35
+
36
+ You are done! Now you can train your model with your favorite framework!
segmentation_models_pytorch/docs/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ faculty-sphinx-theme==0.2.2
2
+ six==1.15.0
segmentation_models_pytorch/examples/cars segmentation (camvid).ipynb ADDED
The diff for this file is too large to render. See raw diff
 
segmentation_models_pytorch/misc/generate_table.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import segmentation_models_pytorch as smp
2
+
3
+ encoders = smp.encoders.encoders
4
+
5
+
6
+ WIDTH = 32
7
+ COLUMNS = [
8
+ "Encoder",
9
+ "Weights",
10
+ "Params, M",
11
+ ]
12
+
13
+ def wrap_row(r):
14
+ return "|{}|".format(r)
15
+
16
+ header = "|".join([column.ljust(WIDTH, ' ') for column in COLUMNS])
17
+ separator = "|".join(["-" * WIDTH] + [":" + "-" * (WIDTH - 2) + ":"] * (len(COLUMNS) - 1))
18
+
19
+ print(wrap_row(header))
20
+ print(wrap_row(separator))
21
+
22
+ for encoder_name, encoder in encoders.items():
23
+ weights = "<br>".join(encoder["pretrained_settings"].keys())
24
+ encoder_name = encoder_name.ljust(WIDTH, " ")
25
+ weights = weights.ljust(WIDTH, " ")
26
+
27
+ model = encoder["encoder"](**encoder["params"], depth=5)
28
+ params = sum(p.numel() for p in model.parameters())
29
+ params = str(params // 1000000) + "M"
30
+ params = params.ljust(WIDTH, " ")
31
+
32
+ row = "|".join([encoder_name, weights, params])
33
+ print(wrap_row(row))
segmentation_models_pytorch/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torchvision>=0.3.0
2
+ pretrainedmodels==0.7.4
3
+ efficientnet-pytorch==0.6.3
4
+ timm==0.3.2
segmentation_models_pytorch/segmentation_models_pytorch/__init__.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .unet import Unet
2
+ from .unetplusplus import UnetPlusPlus
3
+ from .manet import MAnet
4
+ from .linknet import Linknet
5
+ from .fpn import FPN
6
+ from .pspnet import PSPNet
7
+ from .deeplabv3 import DeepLabV3, DeepLabV3Plus
8
+ from .pan import PAN
9
+ from .resunet import ResUnet
10
+ from .resunetplusplus import ResUnetPlusPlus
11
+ from .efficientunetplusplus import EfficientUnetPlusPlus
12
+
13
+ from . import encoders
14
+ from . import utils
15
+ from . import losses
16
+
17
+ from .__version__ import __version__
18
+
19
+ from typing import Optional
20
+ import torch
21
+
22
+
23
+ def create_model(
24
+ arch: str,
25
+ encoder_name: str = "resnet34",
26
+ encoder_weights: Optional[str] = "imagenet",
27
+ in_channels: int = 3,
28
+ classes: int = 1,
29
+ **kwargs,
30
+ ) -> torch.nn.Module:
31
+ """Models wrapper. Allows to create any model just with parametes
32
+
33
+ """
34
+
35
+ archs = [Unet, UnetPlusPlus, MAnet, Linknet, FPN, PSPNet, DeepLabV3, DeepLabV3Plus, PAN, ResUnet, EfficientUnetPlusPlus, ResUnetPlusPlus]
36
+ archs_dict = {a.__name__.lower(): a for a in archs}
37
+ try:
38
+ model_class = archs_dict[arch.lower()]
39
+ except KeyError:
40
+ raise KeyError("Wrong architecture type `{}`. Avalibale options are: {}".format(
41
+ arch, list(archs_dict.keys()),
42
+ ))
43
+ return model_class(
44
+ encoder_name=encoder_name,
45
+ encoder_weights=encoder_weights,
46
+ in_channels=in_channels,
47
+ classes=classes,
48
+ **kwargs,
49
+ )
segmentation_models_pytorch/segmentation_models_pytorch/__version__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ VERSION = (0, 1, 3)
2
+
3
+ __version__ = '.'.join(map(str, VERSION))
segmentation_models_pytorch/segmentation_models_pytorch/base/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .model import SegmentationModel
2
+
3
+ from .modules import (
4
+ PreActivatedConv2dReLU,
5
+ Conv2dReLU,
6
+ Attention,
7
+ )
8
+
9
+ from .heads import (
10
+ SegmentationHead,
11
+ ClassificationHead,
12
+ )
segmentation_models_pytorch/segmentation_models_pytorch/base/heads.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ from .modules import Flatten, Activation
3
+
4
+
5
+ class SegmentationHead(nn.Sequential):
6
+
7
+ def __init__(self, in_channels, out_channels, kernel_size=3, activation=None, upsampling=1):
8
+ conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=kernel_size // 2)
9
+ upsampling = nn.UpsamplingBilinear2d(scale_factor=upsampling) if upsampling > 1 else nn.Identity()
10
+ activation = Activation(activation)
11
+ super().__init__(conv2d, upsampling, activation)
12
+
13
+
14
+ class ClassificationHead(nn.Sequential):
15
+
16
+ def __init__(self, in_channels, classes, pooling="avg", dropout=0.2, activation=None):
17
+ if pooling not in ("max", "avg"):
18
+ raise ValueError("Pooling should be one of ('max', 'avg'), got {}.".format(pooling))
19
+ pool = nn.AdaptiveAvgPool2d(1) if pooling == 'avg' else nn.AdaptiveMaxPool2d(1)
20
+ flatten = Flatten()
21
+ dropout = nn.Dropout(p=dropout, inplace=True) if dropout else nn.Identity()
22
+ linear = nn.Linear(in_channels, classes, bias=True)
23
+ activation = Activation(activation)
24
+ super().__init__(pool, flatten, dropout, linear, activation)
segmentation_models_pytorch/segmentation_models_pytorch/base/initialization.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+
4
+ def initialize_decoder(module):
5
+ for m in module.modules():
6
+
7
+ if isinstance(m, nn.Conv2d):
8
+ nn.init.kaiming_uniform_(m.weight, mode="fan_in", nonlinearity="relu")
9
+ if m.bias is not None:
10
+ nn.init.constant_(m.bias, 0)
11
+
12
+ elif isinstance(m, nn.BatchNorm2d):
13
+ nn.init.constant_(m.weight, 1)
14
+ nn.init.constant_(m.bias, 0)
15
+
16
+ elif isinstance(m, nn.Linear):
17
+ nn.init.xavier_uniform_(m.weight)
18
+ if m.bias is not None:
19
+ nn.init.constant_(m.bias, 0)
20
+
21
+
22
+ def initialize_head(module):
23
+ for m in module.modules():
24
+ if isinstance(m, (nn.Linear, nn.Conv2d)):
25
+ nn.init.xavier_uniform_(m.weight)
26
+ if m.bias is not None:
27
+ nn.init.constant_(m.bias, 0)
segmentation_models_pytorch/segmentation_models_pytorch/base/model.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from . import initialization as init
3
+
4
+
5
+ class SegmentationModel(torch.nn.Module):
6
+
7
+ def initialize(self):
8
+ init.initialize_decoder(self.decoder)
9
+ init.initialize_head(self.segmentation_head)
10
+ if self.classification_head is not None:
11
+ init.initialize_head(self.classification_head)
12
+
13
+ def forward(self, x):
14
+ """Sequentially pass `x` trough model`s encoder, decoder and heads"""
15
+ features = self.encoder(x)
16
+ decoder_output = self.decoder(*features)
17
+
18
+ masks = self.segmentation_head(decoder_output)
19
+
20
+ if self.classification_head is not None:
21
+ labels = self.classification_head(features[-1])
22
+ return masks, labels
23
+
24
+ return masks
25
+
26
+ def predict(self, x):
27
+ """Inference method. Switch model to `eval` mode, call `.forward(x)` with `torch.no_grad()`
28
+
29
+ Args:
30
+ x: 4D torch tensor with shape (batch_size, channels, height, width)
31
+
32
+ Return:
33
+ prediction: 4D torch tensor with shape (batch_size, classes, height, width)
34
+
35
+ """
36
+ if self.training:
37
+ self.eval()
38
+
39
+ with torch.no_grad():
40
+ x = self.forward(x)
41
+
42
+ return x
segmentation_models_pytorch/segmentation_models_pytorch/base/modules.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ try:
5
+ from inplace_abn import InPlaceABN
6
+ except ImportError:
7
+ InPlaceABN = None
8
+
9
+ class PreActivatedConv2dReLU(nn.Sequential):
10
+ """
11
+ Pre-activated 2D convolution, as proposed in https://arxiv.org/pdf/1603.05027.pdf. Feature maps are processed by a normalization layer,
12
+ followed by a ReLU activation and a 3x3 convolution.
13
+ normalization
14
+ """
15
+ def __init__(
16
+ self,
17
+ in_channels,
18
+ out_channels,
19
+ kernel_size,
20
+ padding=0,
21
+ stride=1,
22
+ use_batchnorm=True,
23
+ ):
24
+
25
+ if use_batchnorm == "inplace" and InPlaceABN is None:
26
+ raise RuntimeError(
27
+ "In order to use `use_batchnorm='inplace'` inplace_abn package must be installed. "
28
+ + "To install see: https://github.com/mapillary/inplace_abn"
29
+ )
30
+ if use_batchnorm == "inplace":
31
+ bn = InPlaceABN(out_channels, activation="leaky_relu", activation_param=0.0)
32
+ relu = nn.Identity()
33
+ elif use_batchnorm and use_batchnorm != "inplace":
34
+ bn = nn.BatchNorm2d(out_channels)
35
+ else:
36
+ bn = nn.Identity()
37
+
38
+ relu = nn.ReLU(inplace=True)
39
+
40
+ conv = nn.Conv2d(
41
+ in_channels,
42
+ out_channels,
43
+ kernel_size,
44
+ stride=stride,
45
+ padding=padding,
46
+ bias=not (use_batchnorm),
47
+ )
48
+ super(PreActivatedConv2dReLU, self).__init__(conv, bn, relu)
49
+
50
+ class Conv2dReLU(nn.Sequential):
51
+ """
52
+ Block composed of a 3x3 convolution followed by a normalization layer and ReLU activation.
53
+ """
54
+ def __init__(
55
+ self,
56
+ in_channels,
57
+ out_channels,
58
+ kernel_size,
59
+ padding=0,
60
+ stride=1,
61
+ use_batchnorm=True,
62
+ ):
63
+
64
+ if use_batchnorm == "inplace" and InPlaceABN is None:
65
+ raise RuntimeError(
66
+ "In order to use `use_batchnorm='inplace'` inplace_abn package must be installed. "
67
+ + "To install see: https://github.com/mapillary/inplace_abn"
68
+ )
69
+
70
+ conv = nn.Conv2d(
71
+ in_channels,
72
+ out_channels,
73
+ kernel_size,
74
+ stride=stride,
75
+ padding=padding,
76
+ bias=not (use_batchnorm),
77
+ )
78
+ relu = nn.ReLU(inplace=True)
79
+
80
+ if use_batchnorm == "inplace":
81
+ bn = InPlaceABN(out_channels, activation="leaky_relu", activation_param=0.0)
82
+ relu = nn.Identity()
83
+ elif use_batchnorm and use_batchnorm != "inplace":
84
+ bn = nn.BatchNorm2d(out_channels)
85
+ else:
86
+ bn = nn.Identity()
87
+
88
+ super(Conv2dReLU, self).__init__(conv, bn, relu)
89
+
90
+ class DepthWiseConv2d(nn.Conv2d):
91
+ "Depth-wise convolution operation"
92
+ def __init__(self, channels, kernel_size=3, stride=1):
93
+ super().__init__(channels, channels, kernel_size, stride=stride, padding=kernel_size//2, groups=channels)
94
+
95
+ class PointWiseConv2d(nn.Conv2d):
96
+ "Point-wise (1x1) convolution operation"
97
+ def __init__(self, in_channels, out_channels):
98
+ super().__init__(in_channels, out_channels, kernel_size=1, stride=1)
99
+
100
+ class SEModule(nn.Module):
101
+ """
102
+ Spatial squeeze & channel excitation attention module, as proposed in https://arxiv.org/abs/1709.01507.
103
+ """
104
+ def __init__(self, in_channels, reduction=16):
105
+ super().__init__()
106
+ self.cSE = nn.Sequential(
107
+ nn.AdaptiveAvgPool2d(1),
108
+ nn.Conv2d(in_channels, in_channels // reduction, 1),
109
+ nn.ReLU(inplace=True),
110
+ nn.Conv2d(in_channels // reduction, in_channels, 1),
111
+ nn.Sigmoid(),
112
+ )
113
+
114
+ def forward(self, x):
115
+ return x * self.cSE(x)
116
+
117
+ class sSEModule(nn.Module):
118
+ """
119
+ Channel squeeze & spatial excitation attention module, as proposed in https://arxiv.org/abs/1808.08127.
120
+ """
121
+ def __init__(self, in_channels):
122
+ super().__init__()
123
+ self.sSE = nn.Sequential(nn.Conv2d(in_channels, 1, 1), nn.Sigmoid())
124
+
125
+ def forward(self, x):
126
+ return x * self.sSE(x)
127
+
128
+ class SCSEModule(nn.Module):
129
+ """
130
+ Concurrent spatial and channel squeeze & excitation attention module, as proposed in https://arxiv.org/pdf/1803.02579.pdf.
131
+ """
132
+ def __init__(self, in_channels, reduction=16):
133
+ super().__init__()
134
+ self.cSE = nn.Sequential(
135
+ nn.AdaptiveAvgPool2d(1),
136
+ nn.Conv2d(in_channels, in_channels // reduction, 1),
137
+ nn.ReLU(inplace=True),
138
+ nn.Conv2d(in_channels // reduction, in_channels, 1),
139
+ nn.Sigmoid(),
140
+ )
141
+ self.sSE = nn.Sequential(nn.Conv2d(in_channels, 1, 1), nn.Sigmoid())
142
+
143
+ def forward(self, x):
144
+ return x * self.cSE(x) + x * self.sSE(x)
145
+
146
+ class ArgMax(nn.Module):
147
+
148
+ def __init__(self, dim=None):
149
+ super().__init__()
150
+ self.dim = dim
151
+
152
+ def forward(self, x):
153
+ return torch.argmax(x, dim=self.dim)
154
+
155
+
156
+ class Activation(nn.Module):
157
+
158
+ def __init__(self, name, **params):
159
+
160
+ super().__init__()
161
+
162
+ if name is None or name == 'identity':
163
+ self.activation = nn.Identity(**params)
164
+ elif name == 'sigmoid':
165
+ self.activation = nn.Sigmoid()
166
+ elif name == 'softmax2d':
167
+ self.activation = nn.Softmax(dim=1, **params)
168
+ elif name == 'softmax':
169
+ self.activation = nn.Softmax(**params)
170
+ elif name == 'logsoftmax':
171
+ self.activation = nn.LogSoftmax(**params)
172
+ elif name == 'tanh':
173
+ self.activation = nn.Tanh()
174
+ elif name == 'argmax':
175
+ self.activation = ArgMax(**params)
176
+ elif name == 'argmax2d':
177
+ self.activation = ArgMax(dim=1, **params)
178
+ elif callable(name):
179
+ self.activation = name(**params)
180
+ else:
181
+ raise ValueError('Activation should be callable/sigmoid/softmax/logsoftmax/tanh/None; got {}'.format(name))
182
+
183
+ def forward(self, x):
184
+ return self.activation(x)
185
+
186
+
187
+ class Attention(nn.Module):
188
+
189
+ def __init__(self, name, **params):
190
+ super().__init__()
191
+
192
+ if name is None:
193
+ self.attention = nn.Identity(**params)
194
+ elif name == 'scse':
195
+ self.attention = SCSEModule(**params)
196
+ elif name == 'se':
197
+ self.attention = SEModule(**params)
198
+ else:
199
+ raise ValueError("Attention {} is not implemented".format(name))
200
+
201
+ def forward(self, x):
202
+ return self.attention(x)
203
+
204
+ class Flatten(nn.Module):
205
+ def forward(self, x):
206
+ return x.view(x.shape[0], -1)
segmentation_models_pytorch/segmentation_models_pytorch/deeplabv3/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .model import DeepLabV3, DeepLabV3Plus
segmentation_models_pytorch/segmentation_models_pytorch/deeplabv3/decoder.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ BSD 3-Clause License
3
+
4
+ Copyright (c) Soumith Chintala 2016,
5
+ All rights reserved.
6
+
7
+ Redistribution and use in source and binary forms, with or without
8
+ modification, are permitted provided that the following conditions are met:
9
+
10
+ * Redistributions of source code must retain the above copyright notice, this
11
+ list of conditions and the following disclaimer.
12
+
13
+ * Redistributions in binary form must reproduce the above copyright notice,
14
+ this list of conditions and the following disclaimer in the documentation
15
+ and/or other materials provided with the distribution.
16
+
17
+ * Neither the name of the copyright holder nor the names of its
18
+ contributors may be used to endorse or promote products derived from
19
+ this software without specific prior written permission.
20
+
21
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
25
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+ """
32
+
33
+ import torch
34
+ from torch import nn
35
+ from torch.nn import functional as F
36
+
37
+ __all__ = ["DeepLabV3Decoder"]
38
+
39
+
40
+ class DeepLabV3Decoder(nn.Sequential):
41
+ def __init__(self, in_channels, out_channels=256, atrous_rates=(12, 24, 36)):
42
+ super().__init__(
43
+ ASPP(in_channels, out_channels, atrous_rates),
44
+ nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False),
45
+ nn.BatchNorm2d(out_channels),
46
+ nn.ReLU(),
47
+ )
48
+ self.out_channels = out_channels
49
+
50
+ def forward(self, *features):
51
+ return super().forward(features[-1])
52
+
53
+
54
+ class DeepLabV3PlusDecoder(nn.Module):
55
+ def __init__(
56
+ self,
57
+ encoder_channels,
58
+ out_channels=256,
59
+ atrous_rates=(12, 24, 36),
60
+ output_stride=16,
61
+ ):
62
+ super().__init__()
63
+ if output_stride not in {8, 16}:
64
+ raise ValueError("Output stride should be 8 or 16, got {}.".format(output_stride))
65
+
66
+ self.out_channels = out_channels
67
+ self.output_stride = output_stride
68
+
69
+ self.aspp = nn.Sequential(
70
+ ASPP(encoder_channels[-1], out_channels, atrous_rates, separable=True),
71
+ SeparableConv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False),
72
+ nn.BatchNorm2d(out_channels),
73
+ nn.ReLU(),
74
+ )
75
+
76
+ scale_factor = 2 if output_stride == 8 else 4
77
+ self.up = nn.UpsamplingBilinear2d(scale_factor=scale_factor)
78
+
79
+ highres_in_channels = encoder_channels[-4]
80
+ highres_out_channels = 48 # proposed by authors of paper
81
+ self.block1 = nn.Sequential(
82
+ nn.Conv2d(highres_in_channels, highres_out_channels, kernel_size=1, bias=False),
83
+ nn.BatchNorm2d(highres_out_channels),
84
+ nn.ReLU(),
85
+ )
86
+ self.block2 = nn.Sequential(
87
+ SeparableConv2d(
88
+ highres_out_channels + out_channels,
89
+ out_channels,
90
+ kernel_size=3,
91
+ padding=1,
92
+ bias=False,
93
+ ),
94
+ nn.BatchNorm2d(out_channels),
95
+ nn.ReLU(),
96
+ )
97
+
98
+ def forward(self, *features):
99
+ aspp_features = self.aspp(features[-1])
100
+ aspp_features = self.up(aspp_features)
101
+ high_res_features = self.block1(features[-4])
102
+ concat_features = torch.cat([aspp_features, high_res_features], dim=1)
103
+ fused_features = self.block2(concat_features)
104
+ return fused_features
105
+
106
+
107
+ class ASPPConv(nn.Sequential):
108
+ def __init__(self, in_channels, out_channels, dilation):
109
+ super().__init__(
110
+ nn.Conv2d(
111
+ in_channels,
112
+ out_channels,
113
+ kernel_size=3,
114
+ padding=dilation,
115
+ dilation=dilation,
116
+ bias=False,
117
+ ),
118
+ nn.BatchNorm2d(out_channels),
119
+ nn.ReLU(),
120
+ )
121
+
122
+
123
+ class ASPPSeparableConv(nn.Sequential):
124
+ def __init__(self, in_channels, out_channels, dilation):
125
+ super().__init__(
126
+ SeparableConv2d(
127
+ in_channels,
128
+ out_channels,
129
+ kernel_size=3,
130
+ padding=dilation,
131
+ dilation=dilation,
132
+ bias=False,
133
+ ),
134
+ nn.BatchNorm2d(out_channels),
135
+ nn.ReLU(),
136
+ )
137
+
138
+
139
+ class ASPPPooling(nn.Sequential):
140
+ def __init__(self, in_channels, out_channels):
141
+ super().__init__(
142
+ nn.AdaptiveAvgPool2d(1),
143
+ nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
144
+ nn.BatchNorm2d(out_channels),
145
+ nn.ReLU(),
146
+ )
147
+
148
+ def forward(self, x):
149
+ size = x.shape[-2:]
150
+ for mod in self:
151
+ x = mod(x)
152
+ return F.interpolate(x, size=size, mode='bilinear', align_corners=False)
153
+
154
+
155
+ class ASPP(nn.Module):
156
+ def __init__(self, in_channels, out_channels, atrous_rates, separable=False):
157
+ super(ASPP, self).__init__()
158
+ modules = []
159
+ modules.append(
160
+ nn.Sequential(
161
+ nn.Conv2d(in_channels, out_channels, 1, bias=False),
162
+ nn.BatchNorm2d(out_channels),
163
+ nn.ReLU(),
164
+ )
165
+ )
166
+
167
+ rate1, rate2, rate3 = tuple(atrous_rates)
168
+ ASPPConvModule = ASPPConv if not separable else ASPPSeparableConv
169
+
170
+ modules.append(ASPPConvModule(in_channels, out_channels, rate1))
171
+ modules.append(ASPPConvModule(in_channels, out_channels, rate2))
172
+ modules.append(ASPPConvModule(in_channels, out_channels, rate3))
173
+ modules.append(ASPPPooling(in_channels, out_channels))
174
+
175
+ self.convs = nn.ModuleList(modules)
176
+
177
+ self.project = nn.Sequential(
178
+ nn.Conv2d(5 * out_channels, out_channels, kernel_size=1, bias=False),
179
+ nn.BatchNorm2d(out_channels),
180
+ nn.ReLU(),
181
+ nn.Dropout(0.5),
182
+ )
183
+
184
+ def forward(self, x):
185
+ res = []
186
+ for conv in self.convs:
187
+ res.append(conv(x))
188
+ res = torch.cat(res, dim=1)
189
+ return self.project(res)
190
+
191
+
192
+ class SeparableConv2d(nn.Sequential):
193
+
194
+ def __init__(
195
+ self,
196
+ in_channels,
197
+ out_channels,
198
+ kernel_size,
199
+ stride=1,
200
+ padding=0,
201
+ dilation=1,
202
+ bias=True,
203
+ ):
204
+ dephtwise_conv = nn.Conv2d(
205
+ in_channels,
206
+ in_channels,
207
+ kernel_size,
208
+ stride=stride,
209
+ padding=padding,
210
+ dilation=dilation,
211
+ groups=in_channels,
212
+ bias=False,
213
+ )
214
+ pointwise_conv = nn.Conv2d(
215
+ in_channels,
216
+ out_channels,
217
+ kernel_size=1,
218
+ bias=bias,
219
+ )
220
+ super().__init__(dephtwise_conv, pointwise_conv)
segmentation_models_pytorch/segmentation_models_pytorch/deeplabv3/model.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+ from typing import Optional
4
+ from .decoder import DeepLabV3Decoder, DeepLabV3PlusDecoder
5
+ from ..base import SegmentationModel, SegmentationHead, ClassificationHead
6
+ from ..encoders import get_encoder
7
+
8
+
9
+ class DeepLabV3(SegmentationModel):
10
+ """DeepLabV3_ implementation from "Rethinking Atrous Convolution for Semantic Image Segmentation"
11
+
12
+ Args:
13
+ encoder_name: Name of the classification model that will be used as an encoder (a.k.a backbone)
14
+ to extract features of different spatial resolution
15
+ encoder_depth: A number of stages used in encoder in range [3, 5]. Each stage generate features
16
+ two times smaller in spatial dimensions than previous one (e.g. for depth 0 we will have features
17
+ with shapes [(N, C, H, W),], for depth 1 - [(N, C, H, W), (N, C, H // 2, W // 2)] and so on).
18
+ Default is 5
19
+ encoder_weights: One of **None** (random initialization), **"imagenet"** (pre-training on ImageNet) and
20
+ other pretrained weights (see table with available weights for each encoder_name)
21
+ decoder_channels: A number of convolution filters in ASPP module. Default is 256
22
+ in_channels: A number of input channels for the model, default is 3 (RGB images)
23
+ classes: A number of classes for output mask (or you can think as a number of channels of output mask)
24
+ activation: An activation function to apply after the final convolution layer.
25
+ Available options are **"sigmoid"**, **"softmax"**, **"logsoftmax"**, **"tanh"**, **"identity"**, **callable** and **None**.
26
+ Default is **None**
27
+ upsampling: Final upsampling factor. Default is 8 to preserve input-output spatial shape identity
28
+ aux_params: Dictionary with parameters of the auxiliary output (classification head). Auxiliary output is build
29
+ on top of encoder if **aux_params** is not **None** (default). Supported params:
30
+ - classes (int): A number of classes
31
+ - pooling (str): One of "max", "avg". Default is "avg"
32
+ - dropout (float): Dropout factor in [0, 1)
33
+ - activation (str): An activation function to apply "sigmoid"/"softmax" (could be **None** to return logits)
34
+ Returns:
35
+ ``torch.nn.Module``: **DeepLabV3**
36
+
37
+ .. _DeepLabV3:
38
+ https://arxiv.org/abs/1706.05587
39
+
40
+ Reference:
41
+ https://arxiv.org/abs/1706.05587
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ encoder_name: str = "resnet34",
47
+ encoder_depth: int = 5,
48
+ encoder_weights: Optional[str] = "imagenet",
49
+ decoder_channels: int = 256,
50
+ in_channels: int = 3,
51
+ classes: int = 1,
52
+ activation: Optional[str] = None,
53
+ upsampling: int = 8,
54
+ aux_params: Optional[dict] = None,
55
+ ):
56
+ super().__init__()
57
+
58
+ self.encoder = get_encoder(
59
+ encoder_name,
60
+ in_channels=in_channels,
61
+ depth=encoder_depth,
62
+ weights=encoder_weights,
63
+ )
64
+ self.encoder.make_dilated(
65
+ stage_list=[4, 5],
66
+ dilation_list=[2, 4]
67
+ )
68
+
69
+ self.decoder = DeepLabV3Decoder(
70
+ in_channels=self.encoder.out_channels[-1],
71
+ out_channels=decoder_channels,
72
+ )
73
+
74
+ self.segmentation_head = SegmentationHead(
75
+ in_channels=self.decoder.out_channels,
76
+ out_channels=classes,
77
+ activation=activation,
78
+ kernel_size=1,
79
+ upsampling=upsampling,
80
+ )
81
+
82
+ if aux_params is not None:
83
+ self.classification_head = ClassificationHead(
84
+ in_channels=self.encoder.out_channels[-1], **aux_params
85
+ )
86
+ else:
87
+ self.classification_head = None
88
+
89
+
90
+ class DeepLabV3Plus(SegmentationModel):
91
+ """DeepLabV3+ implementation from "Encoder-Decoder with Atrous Separable
92
+ Convolution for Semantic Image Segmentation"
93
+
94
+ Args:
95
+ encoder_name: Name of the classification model that will be used as an encoder (a.k.a backbone)
96
+ to extract features of different spatial resolution
97
+ encoder_depth: A number of stages used in encoder in range [3, 5]. Each stage generate features
98
+ two times smaller in spatial dimensions than previous one (e.g. for depth 0 we will have features
99
+ with shapes [(N, C, H, W),], for depth 1 - [(N, C, H, W), (N, C, H // 2, W // 2)] and so on).
100
+ Default is 5
101
+ encoder_weights: One of **None** (random initialization), **"imagenet"** (pre-training on ImageNet) and
102
+ other pretrained weights (see table with available weights for each encoder_name)
103
+ encoder_output_stride: Downsampling factor for last encoder features (see original paper for explanation)
104
+ decoder_atrous_rates: Dilation rates for ASPP module (should be a tuple of 3 integer values)
105
+ decoder_channels: A number of convolution filters in ASPP module. Default is 256
106
+ in_channels: A number of input channels for the model, default is 3 (RGB images)
107
+ classes: A number of classes for output mask (or you can think as a number of channels of output mask)
108
+ activation: An activation function to apply after the final convolution layer.
109
+ Available options are **"sigmoid"**, **"softmax"**, **"logsoftmax"**, **"tanh"**, **"identity"**, **callable** and **None**.
110
+ Default is **None**
111
+ upsampling: Final upsampling factor. Default is 4 to preserve input-output spatial shape identity
112
+ aux_params: Dictionary with parameters of the auxiliary output (classification head). Auxiliary output is build
113
+ on top of encoder if **aux_params** is not **None** (default). Supported params:
114
+ - classes (int): A number of classes
115
+ - pooling (str): One of "max", "avg". Default is "avg"
116
+ - dropout (float): Dropout factor in [0, 1)
117
+ - activation (str): An activation function to apply "sigmoid"/"softmax" (could be **None** to return logits)
118
+ Returns:
119
+ ``torch.nn.Module``: **DeepLabV3Plus**
120
+
121
+ Reference:
122
+ https://arxiv.org/abs/1802.02611v3
123
+ """
124
+ def __init__(
125
+ self,
126
+ encoder_name: str = "resnet34",
127
+ encoder_depth: int = 5,
128
+ encoder_weights: Optional[str] = "imagenet",
129
+ encoder_output_stride: int = 16,
130
+ decoder_channels: int = 256,
131
+ decoder_atrous_rates: tuple = (12, 24, 36),
132
+ in_channels: int = 3,
133
+ classes: int = 1,
134
+ activation: Optional[str] = None,
135
+ upsampling: int = 4,
136
+ aux_params: Optional[dict] = None,
137
+ ):
138
+ super().__init__()
139
+
140
+ self.encoder = get_encoder(
141
+ encoder_name,
142
+ in_channels=in_channels,
143
+ depth=encoder_depth,
144
+ weights=encoder_weights,
145
+ )
146
+
147
+ if encoder_output_stride == 8:
148
+ self.encoder.make_dilated(
149
+ stage_list=[4, 5],
150
+ dilation_list=[2, 4]
151
+ )
152
+
153
+ elif encoder_output_stride == 16:
154
+ self.encoder.make_dilated(
155
+ stage_list=[5],
156
+ dilation_list=[2]
157
+ )
158
+ else:
159
+ raise ValueError(
160
+ "Encoder output stride should be 8 or 16, got {}".format(encoder_output_stride)
161
+ )
162
+
163
+ self.decoder = DeepLabV3PlusDecoder(
164
+ encoder_channels=self.encoder.out_channels,
165
+ out_channels=decoder_channels,
166
+ atrous_rates=decoder_atrous_rates,
167
+ output_stride=encoder_output_stride,
168
+ )
169
+
170
+ self.segmentation_head = SegmentationHead(
171
+ in_channels=self.decoder.out_channels,
172
+ out_channels=classes,
173
+ activation=activation,
174
+ kernel_size=1,
175
+ upsampling=upsampling,
176
+ )
177
+
178
+ if aux_params is not None:
179
+ self.classification_head = ClassificationHead(
180
+ in_channels=self.encoder.out_channels[-1], **aux_params
181
+ )
182
+ else:
183
+ self.classification_head = None
segmentation_models_pytorch/segmentation_models_pytorch/efficientunetplusplus/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .model import EfficientUnetPlusPlus
segmentation_models_pytorch/segmentation_models_pytorch/efficientunetplusplus/decoder.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.functional import norm
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+ from ..base import modules as md
7
+
8
+ class InvertedResidual(nn.Module):
9
+ """
10
+ Inverted bottleneck residual block with an scSE block embedded into the residual layer, after the
11
+ depthwise convolution. By default, uses batch normalization and Hardswish activation.
12
+ """
13
+ def __init__(self, in_channels, out_channels, kernel_size = 3, stride = 1, expansion_ratio = 1, squeeze_ratio = 1, \
14
+ activation = nn.Hardswish(True), normalization = nn.BatchNorm2d):
15
+ super().__init__()
16
+ self.same_shape = in_channels == out_channels
17
+ self.mid_channels = expansion_ratio*in_channels
18
+ self.block = nn.Sequential(
19
+ md.PointWiseConv2d(in_channels, self.mid_channels),
20
+ normalization(self.mid_channels),
21
+ activation,
22
+ md.DepthWiseConv2d(self.mid_channels, kernel_size=kernel_size, stride=stride),
23
+ normalization(self.mid_channels),
24
+ activation,
25
+ #md.sSEModule(self.mid_channels),
26
+ md.SCSEModule(self.mid_channels, reduction = squeeze_ratio),
27
+ #md.SEModule(self.mid_channels, reduction = squeeze_ratio),
28
+ md.PointWiseConv2d(self.mid_channels, out_channels),
29
+ normalization(out_channels)
30
+ )
31
+
32
+ if not self.same_shape:
33
+ # 1x1 convolution used to match the number of channels in the skip feature maps with that
34
+ # of the residual feature maps
35
+ self.skip_conv = nn.Sequential(
36
+ nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1),
37
+ normalization(out_channels)
38
+ )
39
+
40
+ def forward(self, x):
41
+ residual = self.block(x)
42
+
43
+ if not self.same_shape:
44
+ x = self.skip_conv(x)
45
+ return x + residual
46
+
47
+ class DecoderBlock(nn.Module):
48
+ def __init__(
49
+ self,
50
+ in_channels,
51
+ skip_channels,
52
+ out_channels,
53
+ squeeze_ratio=1,
54
+ expansion_ratio=1
55
+ ):
56
+ super().__init__()
57
+
58
+ # Inverted Residual block convolutions
59
+ self.conv1 = InvertedResidual(
60
+ in_channels=in_channels+skip_channels,
61
+ out_channels=out_channels,
62
+ kernel_size=3,
63
+ stride=1,
64
+ expansion_ratio=expansion_ratio,
65
+ squeeze_ratio=squeeze_ratio
66
+ )
67
+ self.conv2 = InvertedResidual(
68
+ in_channels=out_channels,
69
+ out_channels=out_channels,
70
+ kernel_size=3,
71
+ stride=1,
72
+ expansion_ratio=expansion_ratio,
73
+ squeeze_ratio=squeeze_ratio
74
+ )
75
+
76
+ def forward(self, x, skip=None):
77
+ x = F.interpolate(x, scale_factor=2, mode="nearest")
78
+
79
+ if skip is not None:
80
+ x = torch.cat([x, skip], dim=1)
81
+ x = self.conv1(x)
82
+ x = self.conv2(x)
83
+ return x
84
+
85
+ class EfficientUnetPlusPlusDecoder(nn.Module):
86
+ def __init__(
87
+ self,
88
+ encoder_channels,
89
+ decoder_channels,
90
+ n_blocks=5,
91
+ squeeze_ratio=1,
92
+ expansion_ratio=1
93
+ ):
94
+ super().__init__()
95
+ if n_blocks != len(decoder_channels):
96
+ raise ValueError(
97
+ "Model depth is {}, but you provide `decoder_channels` for {} blocks.".format(
98
+ n_blocks, len(decoder_channels)
99
+ )
100
+ )
101
+
102
+ encoder_channels = encoder_channels[1:] # remove first skip with same spatial resolution
103
+ encoder_channels = encoder_channels[::-1] # reverse channels to start from head of encoder
104
+ # computing blocks input and output channels
105
+ head_channels = encoder_channels[0]
106
+ self.in_channels = [head_channels] + list(decoder_channels[:-1])
107
+ self.skip_channels = list(encoder_channels[1:]) + [0]
108
+ self.out_channels = decoder_channels
109
+
110
+ # combine decoder keyword arguments
111
+ kwargs = dict(squeeze_ratio=squeeze_ratio, expansion_ratio=expansion_ratio)
112
+
113
+ blocks = {}
114
+ for layer_idx in range(len(self.in_channels) - 1):
115
+ for depth_idx in range(layer_idx+1):
116
+ if depth_idx == 0:
117
+ in_ch = self.in_channels[layer_idx]
118
+ skip_ch = self.skip_channels[layer_idx] * (layer_idx+1)
119
+ out_ch = self.out_channels[layer_idx]
120
+ else:
121
+ out_ch = self.skip_channels[layer_idx]
122
+ skip_ch = self.skip_channels[layer_idx] * (layer_idx+1-depth_idx)
123
+ in_ch = self.skip_channels[layer_idx - 1]
124
+ blocks[f'x_{depth_idx}_{layer_idx}'] = DecoderBlock(in_ch, skip_ch, out_ch, **kwargs)
125
+ blocks[f'x_{0}_{len(self.in_channels)-1}'] =\
126
+ DecoderBlock(self.in_channels[-1], 0, self.out_channels[-1], **kwargs)
127
+ self.blocks = nn.ModuleDict(blocks)
128
+ self.depth = len(self.in_channels) - 1
129
+
130
+ def forward(self, *features):
131
+
132
+ features = features[1:] # remove first skip with same spatial resolution
133
+ features = features[::-1] # reverse channels to start from head of encoder
134
+ # start building dense connections
135
+ dense_x = {}
136
+ for layer_idx in range(len(self.in_channels)-1):
137
+ for depth_idx in range(self.depth-layer_idx):
138
+ if layer_idx == 0:
139
+ output = self.blocks[f'x_{depth_idx}_{depth_idx}'](features[depth_idx], features[depth_idx+1])
140
+ dense_x[f'x_{depth_idx}_{depth_idx}'] = output
141
+ else:
142
+ dense_l_i = depth_idx + layer_idx
143
+ cat_features = [dense_x[f'x_{idx}_{dense_l_i}'] for idx in range(depth_idx+1, dense_l_i+1)]
144
+ cat_features = torch.cat(cat_features + [features[dense_l_i+1]], dim=1)
145
+ dense_x[f'x_{depth_idx}_{dense_l_i}'] =\
146
+ self.blocks[f'x_{depth_idx}_{dense_l_i}'](dense_x[f'x_{depth_idx}_{dense_l_i-1}'], cat_features)
147
+ dense_x[f'x_{0}_{self.depth}'] = self.blocks[f'x_{0}_{self.depth}'](dense_x[f'x_{0}_{self.depth-1}'])
148
+ return dense_x[f'x_{0}_{self.depth}']
segmentation_models_pytorch/segmentation_models_pytorch/efficientunetplusplus/model.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union, List
2
+ from .decoder import EfficientUnetPlusPlusDecoder
3
+ from ..encoders import get_encoder
4
+ from ..base import SegmentationModel
5
+ from ..base import SegmentationHead, ClassificationHead
6
+ from torchvision import transforms
7
+
8
+ class EfficientUnetPlusPlus(SegmentationModel):
9
+ """The EfficientUNet++ is a fully convolutional neural network for ordinary and medical image semantic segmentation.
10
+ Consists of an *encoder* and a *decoder*, connected by *skip connections*. The encoder extracts features of
11
+ different spatial resolutions, which are fed to the decoder through skip connections. The decoder combines its
12
+ own feature maps with the ones from skip connections to produce accurate segmentations masks. The EfficientUNet++
13
+ decoder architecture is based on the UNet++, a model composed of nested U-Net-like decoder sub-networks. To
14
+ increase performance and computational efficiency, the EfficientUNet++ replaces the UNet++'s blocks with
15
+ inverted residual blocks with depthwise convolutions and embedded spatial and channel attention mechanisms.
16
+ Synergizes well with EfficientNet encoders. Due to their efficient visual representations (i.e., using few channels
17
+ to represent extracted features), EfficientNet encoders require few computation from the decoder.
18
+
19
+ Args:
20
+ encoder_name: Name of the classification model that will be used as an encoder (a.k.a backbone) to extract features
21
+ encoder_depth: Number of stages of the encoder, in range [3 ,5]. Each stage generate features two times smaller,
22
+ in spatial dimensions, than the previous one (e.g., for depth=0 features will haves shapes [(N, C, H, W)]),
23
+ for depth 1 features will have shapes [(N, C, H, W), (N, C, H // 2, W // 2)] and so on).
24
+ Default is 5
25
+ encoder_weights: One of **None** (random initialization), **"imagenet"** (pre-training on ImageNet) and
26
+ other pretrained weights (see table with available weights for each encoder_name)
27
+ decoder_channels: List of integers which specify **in_channels** parameter for convolutions used in the decoder.
28
+ Length of the list should be the same as **encoder_depth**
29
+ in_channels: The number of input channels of the model, default is 3 (RGB images)
30
+ classes: The number of classes of the output mask. Can be thought of as the number of channels of the mask
31
+ activation: An activation function to apply after the final convolution layer.
32
+ Available options are **"sigmoid"**, **"softmax"**, **"logsoftmax"**, **"tanh"**, **"identity"**, **callable** and **None**.
33
+ Default is **None**
34
+ aux_params: Dictionary with parameters of the auxiliary output (classification head). Auxiliary output is built
35
+ on top of encoder if **aux_params** is not **None** (default). Supported params:
36
+ - classes (int): A number of classes
37
+ - pooling (str): One of "max", "avg". Default is "avg"
38
+ - dropout (float): Dropout factor in [0, 1)
39
+ - activation (str): An activation function to apply "sigmoid"/"softmax" (could be **None** to return logits)
40
+ Returns:
41
+ ``torch.nn.Module``: **EfficientUnet++**
42
+
43
+ Reference:
44
+ https://arxiv.org/abs/2106.11447
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ encoder_name: str = "timm-efficientnet-b5",
50
+ encoder_depth: int = 5,
51
+ encoder_weights: Optional[str] = "imagenet",
52
+ decoder_channels: List[int] = (256, 128, 64, 32, 16),
53
+ squeeze_ratio: int = 1,
54
+ expansion_ratio: int = 1,
55
+ in_channels: int = 3,
56
+ classes: int = 1,
57
+ activation: Optional[Union[str, callable]] = None,
58
+ aux_params: Optional[dict] = None,
59
+ ):
60
+ super().__init__()
61
+ self.classes = classes
62
+ self.encoder = get_encoder(
63
+ encoder_name,
64
+ in_channels=in_channels,
65
+ depth=encoder_depth,
66
+ weights=encoder_weights,
67
+ )
68
+
69
+ self.decoder = EfficientUnetPlusPlusDecoder(
70
+ encoder_channels=self.encoder.out_channels,
71
+ decoder_channels=decoder_channels,
72
+ n_blocks=encoder_depth,
73
+ squeeze_ratio=squeeze_ratio,
74
+ expansion_ratio=expansion_ratio
75
+ )
76
+
77
+ self.segmentation_head = SegmentationHead(
78
+ in_channels=decoder_channels[-1],
79
+ out_channels=classes,
80
+ activation=activation,
81
+ kernel_size=3,
82
+ )
83
+
84
+ if aux_params is not None:
85
+ self.classification_head = ClassificationHead(
86
+ in_channels=self.encoder.out_channels[-1], **aux_params
87
+ )
88
+ else:
89
+ self.classification_head = None
90
+
91
+ self.name = "EfficientUNet++-{}".format(encoder_name)
92
+ self.initialize()
93
+
94
+ def predict(self, x):
95
+ """Inference method. Switch model to `eval` mode, call `.forward(x)` with `torch.no_grad()`
96
+
97
+ Args:
98
+ x: 4D torch tensor with shape (batch_size, channels, height, width)
99
+
100
+ Return:
101
+ prediction: 4D torch tensor with shape (batch_size, classes, height, width)
102
+
103
+ """
104
+ if self.training:
105
+ self.eval()
106
+
107
+ with torch.no_grad():
108
+ output = self.forward(x)
109
+
110
+ if self.classes > 1:
111
+ probs = torch.softmax(output, dim=1)
112
+ else:
113
+ probs = torch.sigmoid(output)
114
+
115
+ probs = probs.squeeze(0)
116
+ tf = transforms.Compose(
117
+ [
118
+ transforms.ToPILImage(),
119
+ transforms.Resize(x.size[1]),
120
+ transforms.ToTensor()
121
+ ]
122
+ )
123
+ full_mask = tf(probs.cpu())
124
+
125
+ return full_mask
segmentation_models_pytorch/segmentation_models_pytorch/encoders/__init__.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import torch.utils.model_zoo as model_zoo
3
+
4
+ from .resnet import resnet_encoders
5
+ from .dpn import dpn_encoders
6
+ from .vgg import vgg_encoders
7
+ from .senet import senet_encoders
8
+ from .densenet import densenet_encoders
9
+ from .inceptionresnetv2 import inceptionresnetv2_encoders
10
+ from .inceptionv4 import inceptionv4_encoders
11
+ from .efficientnet import efficient_net_encoders
12
+ from .mobilenet import mobilenet_encoders
13
+ from .xception import xception_encoders
14
+ # from .timm_efficientnet import timm_efficientnet_encoders
15
+ from .timm_resnest import timm_resnest_encoders
16
+ from .timm_res2net import timm_res2net_encoders
17
+ from .timm_regnet import timm_regnet_encoders
18
+ from .timm_sknet import timm_sknet_encoders
19
+ from ._preprocessing import preprocess_input
20
+
21
+ encoders = {}
22
+ encoders.update(resnet_encoders)
23
+ encoders.update(dpn_encoders)
24
+ encoders.update(vgg_encoders)
25
+ encoders.update(senet_encoders)
26
+ encoders.update(densenet_encoders)
27
+ encoders.update(inceptionresnetv2_encoders)
28
+ encoders.update(inceptionv4_encoders)
29
+ encoders.update(efficient_net_encoders)
30
+ encoders.update(mobilenet_encoders)
31
+ encoders.update(xception_encoders)
32
+ # encoders.update(timm_efficientnet_encoders)
33
+ encoders.update(timm_resnest_encoders)
34
+ encoders.update(timm_res2net_encoders)
35
+ encoders.update(timm_regnet_encoders)
36
+ encoders.update(timm_sknet_encoders)
37
+
38
+
39
+ def get_encoder(name, in_channels=3, depth=5, weights=None):
40
+
41
+ try:
42
+ Encoder = encoders[name]["encoder"]
43
+ except KeyError:
44
+ raise KeyError("Wrong encoder name `{}`, supported encoders: {}".format(name, list(encoders.keys())))
45
+
46
+ params = encoders[name]["params"]
47
+ params.update(depth=depth)
48
+ encoder = Encoder(**params)
49
+
50
+ if weights is not None:
51
+ try:
52
+ settings = encoders[name]["pretrained_settings"][weights]
53
+ except KeyError:
54
+ raise KeyError("Wrong pretrained weights `{}` for encoder `{}`. Available options are: {}".format(
55
+ weights, name, list(encoders[name]["pretrained_settings"].keys()),
56
+ ))
57
+ encoder.load_state_dict(model_zoo.load_url(settings["url"]))
58
+
59
+ encoder.set_in_channels(in_channels)
60
+
61
+ return encoder
62
+
63
+
64
+ def get_encoder_names():
65
+ return list(encoders.keys())
66
+
67
+
68
+ def get_preprocessing_params(encoder_name, pretrained="imagenet"):
69
+ settings = encoders[encoder_name]["pretrained_settings"]
70
+
71
+ if pretrained not in settings.keys():
72
+ raise ValueError("Available pretrained options {}".format(settings.keys()))
73
+
74
+ formatted_settings = {}
75
+ formatted_settings["input_space"] = settings[pretrained].get("input_space")
76
+ formatted_settings["input_range"] = settings[pretrained].get("input_range")
77
+ formatted_settings["mean"] = settings[pretrained].get("mean")
78
+ formatted_settings["std"] = settings[pretrained].get("std")
79
+ return formatted_settings
80
+
81
+
82
+ def get_preprocessing_fn(encoder_name, pretrained="imagenet"):
83
+ params = get_preprocessing_params(encoder_name, pretrained=pretrained)
84
+ return functools.partial(preprocess_input, **params)
segmentation_models_pytorch/segmentation_models_pytorch/encoders/_base.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from typing import List
4
+ from collections import OrderedDict
5
+
6
+ from . import _utils as utils
7
+
8
+
9
+ class EncoderMixin:
10
+ """Add encoder functionality such as:
11
+ - output channels specification of feature tensors (produced by encoder)
12
+ - patching first convolution for arbitrary input channels
13
+ """
14
+
15
+ @property
16
+ def out_channels(self):
17
+ """Return channels dimensions for each tensor of forward output of encoder"""
18
+ return self._out_channels[: self._depth + 1]
19
+
20
+ def set_in_channels(self, in_channels):
21
+ """Change first convolution channels"""
22
+ if in_channels == 3:
23
+ return
24
+
25
+ self._in_channels = in_channels
26
+ if self._out_channels[0] == 3:
27
+ self._out_channels = tuple([in_channels] + list(self._out_channels)[1:])
28
+
29
+ utils.patch_first_conv(model=self, in_channels=in_channels)
30
+
31
+ def get_stages(self):
32
+ """Method should be overridden in encoder"""
33
+ raise NotImplementedError
34
+
35
+ def make_dilated(self, stage_list, dilation_list):
36
+ stages = self.get_stages()
37
+ for stage_indx, dilation_rate in zip(stage_list, dilation_list):
38
+ utils.replace_strides_with_dilation(
39
+ module=stages[stage_indx],
40
+ dilation_rate=dilation_rate,
41
+ )
segmentation_models_pytorch/segmentation_models_pytorch/encoders/_preprocessing.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ def preprocess_input(
5
+ x, mean=None, std=None, input_space="RGB", input_range=None, **kwargs
6
+ ):
7
+
8
+ if input_space == "BGR":
9
+ x = x[..., ::-1].copy()
10
+
11
+ if input_range is not None:
12
+ if x.max() > 1 and input_range[1] == 1:
13
+ x = x / 255.0
14
+
15
+ if mean is not None:
16
+ mean = np.array(mean)
17
+ x = x - mean
18
+
19
+ if std is not None:
20
+ std = np.array(std)
21
+ x = x / std
22
+
23
+ return x
segmentation_models_pytorch/segmentation_models_pytorch/encoders/_utils.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ def patch_first_conv(model, in_channels):
6
+ """Change first convolution layer input channels.
7
+ In case:
8
+ in_channels == 1 or in_channels == 2 -> reuse original weights
9
+ in_channels > 3 -> make random kaiming normal initialization
10
+ """
11
+
12
+ # get first conv
13
+ for module in model.modules():
14
+ if isinstance(module, nn.Conv2d):
15
+ break
16
+
17
+ # change input channels for first conv
18
+ module.in_channels = in_channels
19
+ weight = module.weight.detach()
20
+ reset = False
21
+
22
+ if in_channels == 1:
23
+ weight = weight.sum(1, keepdim=True)
24
+ elif in_channels == 2:
25
+ weight = weight[:, :2] * (3.0 / 2.0)
26
+ else:
27
+ reset = True
28
+ weight = torch.Tensor(
29
+ module.out_channels,
30
+ module.in_channels // module.groups,
31
+ *module.kernel_size
32
+ )
33
+
34
+ module.weight = nn.parameter.Parameter(weight)
35
+ if reset:
36
+ module.reset_parameters()
37
+
38
+
39
+ def replace_strides_with_dilation(module, dilation_rate):
40
+ """Patch Conv2d modules replacing strides with dilation"""
41
+ for mod in module.modules():
42
+ if isinstance(mod, nn.Conv2d):
43
+ mod.stride = (1, 1)
44
+ mod.dilation = (dilation_rate, dilation_rate)
45
+ kh, kw = mod.kernel_size
46
+ mod.padding = ((kh // 2) * dilation_rate, (kh // 2) * dilation_rate)
47
+
48
+ # Kostyl for EfficientNet
49
+ if hasattr(mod, "static_padding"):
50
+ mod.static_padding = nn.Identity()
segmentation_models_pytorch/segmentation_models_pytorch/encoders/densenet.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
2
+
3
+ Attributes:
4
+
5
+ _out_channels (list of int): specify number of channels for each encoder feature tensor
6
+ _depth (int): specify number of stages in decoder (in other words number of downsampling operations)
7
+ _in_channels (int): default number of input channels in first Conv2d layer for encoder (usually 3)
8
+
9
+ Methods:
10
+
11
+ forward(self, x: torch.Tensor)
12
+ produce list of features of different spatial resolutions, each feature is a 4D torch.tensor of
13
+ shape NCHW (features should be sorted in descending order according to spatial resolution, starting
14
+ with resolution same as input `x` tensor).
15
+
16
+ Input: `x` with shape (1, 3, 64, 64)
17
+ Output: [f0, f1, f2, f3, f4, f5] - features with corresponding shapes
18
+ [(1, 3, 64, 64), (1, 64, 32, 32), (1, 128, 16, 16), (1, 256, 8, 8),
19
+ (1, 512, 4, 4), (1, 1024, 2, 2)] (C - dim may differ)
20
+
21
+ also should support number of features according to specified depth, e.g. if depth = 5,
22
+ number of feature tensors = 6 (one with same resolution as input and 5 downsampled),
23
+ depth = 3 -> number of feature tensors = 4 (one with same resolution as input and 3 downsampled).
24
+ """
25
+
26
+ import re
27
+ import torch.nn as nn
28
+
29
+ from pretrainedmodels.models.torchvision_models import pretrained_settings
30
+ from torchvision.models.densenet import DenseNet
31
+
32
+ from ._base import EncoderMixin
33
+
34
+
35
+ class TransitionWithSkip(nn.Module):
36
+
37
+ def __init__(self, module):
38
+ super().__init__()
39
+ self.module = module
40
+
41
+ def forward(self, x):
42
+ for module in self.module:
43
+ x = module(x)
44
+ if isinstance(module, nn.ReLU):
45
+ skip = x
46
+ return x, skip
47
+
48
+
49
+ class DenseNetEncoder(DenseNet, EncoderMixin):
50
+ def __init__(self, out_channels, depth=5, **kwargs):
51
+ super().__init__(**kwargs)
52
+ self._out_channels = out_channels
53
+ self._depth = depth
54
+ self._in_channels = 3
55
+ del self.classifier
56
+
57
+ def make_dilated(self, stage_list, dilation_list):
58
+ raise ValueError("DenseNet encoders do not support dilated mode "
59
+ "due to pooling operation for downsampling!")
60
+
61
+ def get_stages(self):
62
+ return [
63
+ nn.Identity(),
64
+ nn.Sequential(self.features.conv0, self.features.norm0, self.features.relu0),
65
+ nn.Sequential(self.features.pool0, self.features.denseblock1,
66
+ TransitionWithSkip(self.features.transition1)),
67
+ nn.Sequential(self.features.denseblock2, TransitionWithSkip(self.features.transition2)),
68
+ nn.Sequential(self.features.denseblock3, TransitionWithSkip(self.features.transition3)),
69
+ nn.Sequential(self.features.denseblock4, self.features.norm5)
70
+ ]
71
+
72
+ def forward(self, x):
73
+
74
+ stages = self.get_stages()
75
+
76
+ features = []
77
+ for i in range(self._depth + 1):
78
+ x = stages[i](x)
79
+ if isinstance(x, (list, tuple)):
80
+ x, skip = x
81
+ features.append(skip)
82
+ else:
83
+ features.append(x)
84
+
85
+ return features
86
+
87
+ def load_state_dict(self, state_dict):
88
+ pattern = re.compile(
89
+ r"^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$"
90
+ )
91
+ for key in list(state_dict.keys()):
92
+ res = pattern.match(key)
93
+ if res:
94
+ new_key = res.group(1) + res.group(2)
95
+ state_dict[new_key] = state_dict[key]
96
+ del state_dict[key]
97
+
98
+ # remove linear
99
+ state_dict.pop("classifier.bias")
100
+ state_dict.pop("classifier.weight")
101
+
102
+ super().load_state_dict(state_dict)
103
+
104
+
105
+ densenet_encoders = {
106
+ "densenet121": {
107
+ "encoder": DenseNetEncoder,
108
+ "pretrained_settings": pretrained_settings["densenet121"],
109
+ "params": {
110
+ "out_channels": (3, 64, 256, 512, 1024, 1024),
111
+ "num_init_features": 64,
112
+ "growth_rate": 32,
113
+ "block_config": (6, 12, 24, 16),
114
+ },
115
+ },
116
+ "densenet169": {
117
+ "encoder": DenseNetEncoder,
118
+ "pretrained_settings": pretrained_settings["densenet169"],
119
+ "params": {
120
+ "out_channels": (3, 64, 256, 512, 1280, 1664),
121
+ "num_init_features": 64,
122
+ "growth_rate": 32,
123
+ "block_config": (6, 12, 32, 32),
124
+ },
125
+ },
126
+ "densenet201": {
127
+ "encoder": DenseNetEncoder,
128
+ "pretrained_settings": pretrained_settings["densenet201"],
129
+ "params": {
130
+ "out_channels": (3, 64, 256, 512, 1792, 1920),
131
+ "num_init_features": 64,
132
+ "growth_rate": 32,
133
+ "block_config": (6, 12, 48, 32),
134
+ },
135
+ },
136
+ "densenet161": {
137
+ "encoder": DenseNetEncoder,
138
+ "pretrained_settings": pretrained_settings["densenet161"],
139
+ "params": {
140
+ "out_channels": (3, 96, 384, 768, 2112, 2208),
141
+ "num_init_features": 96,
142
+ "growth_rate": 48,
143
+ "block_config": (6, 12, 36, 24),
144
+ },
145
+ },
146
+ }