├── assets
├── GT_01.png
├── GT_02.png
├── GT_03.png
├── GT_10.png
├── GT_17.png
├── GT_45.png
├── IDRiD_01.jpg
├── IDRiD_02.jpg
├── IDRiD_03.jpg
├── IDRiD_10.jpg
├── IDRiD_17.jpg
└── IDRiD_45.jpg
├── README.md
├── LICENSE
└── IDRiDseg.ipynb
/assets/GT_01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/GT_01.png
--------------------------------------------------------------------------------
/assets/GT_02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/GT_02.png
--------------------------------------------------------------------------------
/assets/GT_03.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/GT_03.png
--------------------------------------------------------------------------------
/assets/GT_10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/GT_10.png
--------------------------------------------------------------------------------
/assets/GT_17.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/GT_17.png
--------------------------------------------------------------------------------
/assets/GT_45.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/GT_45.png
--------------------------------------------------------------------------------
/assets/IDRiD_01.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/IDRiD_01.jpg
--------------------------------------------------------------------------------
/assets/IDRiD_02.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/IDRiD_02.jpg
--------------------------------------------------------------------------------
/assets/IDRiD_03.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/IDRiD_03.jpg
--------------------------------------------------------------------------------
/assets/IDRiD_10.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/IDRiD_10.jpg
--------------------------------------------------------------------------------
/assets/IDRiD_17.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/IDRiD_17.jpg
--------------------------------------------------------------------------------
/assets/IDRiD_45.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HimanshuAgarwal022/IDRiDSegmentation/HEAD/assets/IDRiD_45.jpg
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # IDRiDSegmentation
2 |
3 | Code for Segmentation of retinal lesions associated with diabetic retinopathy as microaneurysms, hemorrhages, hard exudates, and soft exudates.
4 |
5 | It's distributed under the GNU General Public License v3 (or any later
6 | version) - see the accompanying LICENSE file for more details.
7 |
8 | ## Requirements
9 |
10 | You need to have the following python packages installed (may be incomplete):
11 |
12 | - tensorflow 1.X
13 | - opencv
14 | - numpy
15 | - scipy
16 | - sklearn
17 | - matplotlib
18 | - PIL
19 | - pandas
20 | - You need to have downloaded at least the IDRiD training dataset.
21 |
22 | ## Samples
23 |
24 | | Ground Truth(HE) | Predicted |
25 | | :-------------------: | :----------------------: |
26 | |  |  |
27 | |  |  |
28 | |  |  |
29 | |  |  |
30 | |  |  |
31 | |  |  |
32 | ***
33 |
34 | ## Contributors
35 |
36 | - **[Himanshu Agarwal](https://github.com/HimanshuAgarwal022)**
37 |
38 | - **[Jayesh Narayan](https://github.com/jayesh1narayan)**
39 |
40 | ***
41 |
42 | ## Citations
43 |
44 | **[IDRiD Challenge](https://idrid.grand-challenge.org/)**
45 | ***
46 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
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 |
635 | Copyright (C)
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 .
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 | Copyright (C)
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 | .
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 | .
675 |
--------------------------------------------------------------------------------
/IDRiDseg.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "name": "IDRiDseg.ipynb",
7 | "provenance": [],
8 | "collapsed_sections": [
9 | "AcSma7_RfLnk",
10 | "EeZa_92kuQag",
11 | "_Na2DjTeexJd",
12 | "yrfnYhrjuYYQ",
13 | "BklkTaFzut95",
14 | "cHjVOXKMfXSa",
15 | "EqLtpXRru2kh",
16 | "p2JGpoMrtNx3",
17 | "ByIpNhUk-xQr",
18 | "CM2NY0sRHysI",
19 | "rnNDIjEh_iD3",
20 | "mjewf0kzHheN",
21 | "8hwL8cLfH89I"
22 | ],
23 | "toc_visible": true,
24 | "include_colab_link": true
25 | },
26 | "kernelspec": {
27 | "name": "python3",
28 | "display_name": "Python 3"
29 | },
30 | "accelerator": "GPU"
31 | },
32 | "cells": [
33 | {
34 | "cell_type": "markdown",
35 | "metadata": {
36 | "id": "view-in-github",
37 | "colab_type": "text"
38 | },
39 | "source": [
40 | "
"
41 | ]
42 | },
43 | {
44 | "cell_type": "markdown",
45 | "metadata": {
46 | "id": "PM9UH-6K18L8"
47 | },
48 | "source": [
49 | "# Diabetic Retinopathy Lesion Segmentation.\n",
50 | "---\n",
51 | "\n",
52 | " GNU GENERAL PUBLIC LICENSE\n",
53 | "\n",
54 | " Version 3, 29 June 2007\n",
55 | "\n",
56 | " Copyright (c) [2020] [Himanshu Agarwal]\n",
57 | "\n",
58 | "\n",
59 | "---\n",
60 | "\n"
61 | ]
62 | },
63 | {
64 | "cell_type": "markdown",
65 | "metadata": {
66 | "id": "AcSma7_RfLnk"
67 | },
68 | "source": [
69 | "### load drive"
70 | ]
71 | },
72 | {
73 | "cell_type": "code",
74 | "metadata": {
75 | "id": "Hf1EOC0CtWWC",
76 | "colab": {
77 | "base_uri": "https://localhost:8080/",
78 | "height": 122
79 | },
80 | "outputId": "9e20fb59-1936-4b7c-9a3c-3981b8edd276"
81 | },
82 | "source": [
83 | "from google.colab import drive\n",
84 | "drive.mount('/content/drive')"
85 | ],
86 | "execution_count": null,
87 | "outputs": [
88 | {
89 | "output_type": "stream",
90 | "text": [
91 | "Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n",
92 | "\n",
93 | "Enter your authorization code:\n",
94 | "··········\n",
95 | "Mounted at /content/drive\n"
96 | ],
97 | "name": "stdout"
98 | }
99 | ]
100 | },
101 | {
102 | "cell_type": "markdown",
103 | "metadata": {
104 | "id": "EeZa_92kuQag"
105 | },
106 | "source": [
107 | "### convert ground truths to binary"
108 | ]
109 | },
110 | {
111 | "cell_type": "code",
112 | "metadata": {
113 | "id": "Oi6Fax6vuOoL"
114 | },
115 | "source": [
116 | "from PIL import Image\n",
117 | "#from resizeimage import resizeimage\n",
118 | "import os, sys\n",
119 | "\n",
120 | "def cmp(a, b):\n",
121 | " return (a > b) - (a < b) \n",
122 | "\n",
123 | "def resizeImage(infile,file, output_dir, size=(4288,2848)):\n",
124 | " outfile = os.path.splitext(file)[0]\n",
125 | " extension = os.path.splitext(file)[1]\n",
126 | " #print(outfile)\n",
127 | " #print(extension)\n",
128 | " #print(infile)\n",
129 | " #if (cmp(extension, \".jpg\")):\n",
130 | " #print(\"dsd\")\n",
131 | " #return\n",
132 | "\n",
133 | " if infile != outfile:\n",
134 | " try :\n",
135 | " im = Image.open(infile)\n",
136 | " gray = im.convert('L')\n",
137 | " bw = gray.point(lambda x: 0 if x<50 else 255, '1')\n",
138 | " # im = resizeimage.resize_cover(im, [960, 640])\n",
139 | " bw.save(output_dir+outfile[:-3]+extension,\"TIFF\",quality=100)\n",
140 | " #print(\"sucess\")\n",
141 | " #except IOError:\n",
142 | " # print (\"cannot reduce image for \", infile)\n",
143 | " except e:\n",
144 | " print (e)\n",
145 | " \n",
146 | "\n",
147 | "\n",
148 | "output_dir = \"drive/My Drive/data/output/annotations/\"\n",
149 | "annot_dir = \"drive/My Drive/data/annotations/\"\n",
150 | "dir = os.getcwd()\n",
151 | "\n",
152 | "if not os.path.exists(os.path.join(dir,output_dir)):\n",
153 | " os.mkdir(output_dir)\n",
154 | "annot = os.path.join(dir,annot_dir)\n",
155 | "for file in os.listdir(annot):\n",
156 | " #print(file)\n",
157 | " resizeImage(os.path.join(annot,file),file,output_dir)"
158 | ],
159 | "execution_count": null,
160 | "outputs": []
161 | },
162 | {
163 | "cell_type": "markdown",
164 | "metadata": {
165 | "id": "_Na2DjTeexJd"
166 | },
167 | "source": [
168 | "### CLAHE on input images"
169 | ]
170 | },
171 | {
172 | "cell_type": "code",
173 | "metadata": {
174 | "id": "uIIONbM_e4Jz"
175 | },
176 | "source": [
177 | "import os, sys\n",
178 | "import numpy as np\n",
179 | "import cv2\n",
180 | "from matplotlib import pyplot as plt\n",
181 | "\n",
182 | "dir = os.getcwd()\n",
183 | "dir_data = os.path.join(dir,\"drive/My Drive/data/output/preimages/\")\n",
184 | "output_dir_data = os.path.join(dir,\"drive/My Drive/data/output/images/\")\n",
185 | "if not os.path.exists(os.path.join(dir,output_dir_data)):\n",
186 | " os.mkdir(output_dir_data)\n",
187 | "\n",
188 | "gridsize = 8\n",
189 | "for file in os.listdir(dir_data):\n",
190 | " bgr = cv2.imread(os.path.join(dir_data,file))\n",
191 | " lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)\n",
192 | " lab_planes = cv2.split(lab)\n",
193 | " clahe = cv2.createCLAHE(clipLimit=2.0,tileGridSize=(gridsize,gridsize))\n",
194 | " lab_planes[0] = clahe.apply(lab_planes[0])\n",
195 | " lab = cv2.merge(lab_planes)\n",
196 | " bgr = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)\n",
197 | " #if random.uniform(0, 1.0) > 0.75:\n",
198 | " # bgr = cv2.bitwise_not(bgr)\n",
199 | " # plt.imshow(bgr)\n",
200 | " # plt.show()\n",
201 | " cv2.imwrite(os.path.join(output_dir_data,file),bgr)"
202 | ],
203 | "execution_count": null,
204 | "outputs": []
205 | },
206 | {
207 | "cell_type": "code",
208 | "metadata": {
209 | "id": "GL-rKiA5hn_T"
210 | },
211 | "source": [
212 | "#output_dir_data = os.path.join(dir,\"drive/My Drive/data/output/images/\")\n",
213 | "#for file in os.listdir(output_dir_data):\n",
214 | "# bgr = cv2.imread(os.path.join(output_dir_data,file))\n",
215 | "# rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)\n",
216 | "# plt.imshow(rgb)\n",
217 | "# plt.show()\n",
218 | "# bgr = cv2.bitwise_not(bgr)\n",
219 | "# plt.imshow(bgr)\n",
220 | "# plt.show()"
221 | ],
222 | "execution_count": null,
223 | "outputs": []
224 | },
225 | {
226 | "cell_type": "markdown",
227 | "metadata": {
228 | "id": "yrfnYhrjuYYQ"
229 | },
230 | "source": [
231 | "### extract patches"
232 | ]
233 | },
234 | {
235 | "cell_type": "code",
236 | "metadata": {
237 | "id": "0BhM3OxTuiWu"
238 | },
239 | "source": [
240 | "from PIL import Image\n",
241 | "#from resizeimage import resizeimage\n",
242 | "import os, sys\n",
243 | "import numpy as np\n",
244 | "import cv2\n",
245 | "from matplotlib import pyplot as plt\n",
246 | "\n",
247 | "dir = os.getcwd()\n",
248 | "output_dir_data = \"drive/My Drive/data/output/patches/\"\n",
249 | "output_dir_mask = \"drive/My Drive/data/output/labels/\"\n",
250 | "if not os.path.exists(os.path.join(dir,output_dir_data)):\n",
251 | " os.mkdir(output_dir_data)\n",
252 | "if not os.path.exists(os.path.join(dir,output_dir_mask)):\n",
253 | " os.mkdir(output_dir_mask)\n",
254 | "\n",
255 | "dir_data = os.path.join(dir,\"drive/My Drive/data/output/images/\")\n",
256 | "dir_mask = os.path.join(dir,\"drive/My Drive/data/output/annotations/\")\n",
257 | "\n",
258 | "# im = Image.open(os.path.join(dir_mask,\"IDRiD_06.tif\"))\n",
259 | "# im_crop = im.crop((2000,0,2000+512,0+256))\n",
260 | "# im_crop.show()\n",
261 | "# image_np = np.array(im_crop)\n",
262 | "# print np.sum(image_np)\n",
263 | "\n",
264 | "negative_patches = []\n",
265 | "positive_count = 0\n",
266 | "\n",
267 | "for file in os.listdir(dir_mask):\n",
268 | " outfile = os.path.splitext(file)[0]\n",
269 | " extension = os.path.splitext(file)[1]\n",
270 | " #if (cmp(extension, \".jpg\")):\n",
271 | " # continue\n",
272 | " img = outfile + \".jpg\"\n",
273 | " im = Image.open(os.path.join(dir_mask,file))\n",
274 | " imd = Image.open(os.path.join(dir_data,img))\n",
275 | " # image_np = np.array(im)\n",
276 | " # print np.sum([True, True])\n",
277 | " # im_crop = im.crop((1900,0,1900+512,0+512))\n",
278 | " patch_id = 0\n",
279 | " for i in range(10): #10 6\n",
280 | " \tfor j in range(16): #16 9\n",
281 | " top_y = i*256 #256 512\n",
282 | " if (i==9): #9 5\n",
283 | " top_y = 2336\n",
284 | " top_x = j*256 #256 512\n",
285 | " if (j==15): #15 8\n",
286 | " top_x = 3776\n",
287 | "\n",
288 | " im_crop = im.crop((top_x,top_y,top_x+512,top_y+512))\n",
289 | " imd_crop = imd.crop((top_x,top_y,top_x+512,top_y+512))\n",
290 | " im_crop.save(output_dir_mask+outfile+\"_p\"+str(patch_id)+extension,\"JPEG\",quality=100)\n",
291 | " imd_crop.save(output_dir_data+outfile+\"_p\"+str(patch_id)+extension,\"JPEG\",quality=100)\n",
292 | " if (np.sum(np.array(im_crop)) < 100):\n",
293 | " negative_patches.append(output_dir_mask+outfile+\"_p\"+str(patch_id)+extension)\n",
294 | " else:\n",
295 | " positive_count += 1\n",
296 | "\n",
297 | " patch_id += 1\n",
298 | "\n",
299 | "negative_patches = np.array(negative_patches)\n",
300 | "# np.savetxt(\"negative.csv\", negative_patches, delimiter=\",\", fmt=\"%s\")\n",
301 | "\n",
302 | "negative_count = negative_patches.size\n",
303 | "delete_count = negative_count - 4*positive_count\n",
304 | "np.random.shuffle(negative_patches)\n",
305 | "split_idx = delete_count\n",
306 | "delete_patches = negative_patches[:split_idx]\n",
307 | "\n",
308 | "for idx in range(delete_patches.size):\n",
309 | " os.remove(delete_patches[idx])\n",
310 | " os.remove(os.path.join(output_dir_data,delete_patches[idx][34:]))"
311 | ],
312 | "execution_count": null,
313 | "outputs": []
314 | },
315 | {
316 | "cell_type": "markdown",
317 | "metadata": {
318 | "id": "BklkTaFzut95"
319 | },
320 | "source": [
321 | "### split in train and test sets"
322 | ]
323 | },
324 | {
325 | "cell_type": "code",
326 | "metadata": {
327 | "id": "Krh5Z4OHuvBu",
328 | "colab": {
329 | "base_uri": "https://localhost:8080/",
330 | "height": 51
331 | },
332 | "outputId": "72c55ae1-8c28-446d-eade-1335338daa7e"
333 | },
334 | "source": [
335 | "import numpy as np\n",
336 | "import matplotlib.pyplot as plt\n",
337 | "import pandas as pd\n",
338 | "import os\n",
339 | "\n",
340 | "dir = \"drive/My Drive/data/output/patches/\"\n",
341 | "#dir = \"drive/My Drive/data/output/images/\"\n",
342 | "image_paths = os.listdir(dir)\n",
343 | "\n",
344 | "length = len(image_paths)\n",
345 | "img_paths = np.empty(length, dtype=object)\n",
346 | "\n",
347 | "i=0\n",
348 | "for file in image_paths:\n",
349 | "\timg_paths[i] = \"drive/My Drive/data/output/patches/\" + file\n",
350 | "\t#img_paths[i] = \"drive/My Drive/data/output/images/\" + file\n",
351 | "\t#print (img_paths[i])\n",
352 | "\ti+=1\n",
353 | "\n",
354 | "# print (img_paths)\n",
355 | "np.random.shuffle(img_paths)\n",
356 | "#split_idx = int(img_paths.shape[0] * 1)\n",
357 | "split_idx = 11534\n",
358 | "train_paths = img_paths[:split_idx]\n",
359 | "test_paths = img_paths[split_idx:]\n",
360 | "\n",
361 | "train_paths_ = np.copy(train_paths)\n",
362 | "test_paths_ = np.copy(test_paths)\n",
363 | "print(\"train set: \",train_paths.size)\n",
364 | "print(\"test set: \",test_paths.size)\n",
365 | "for i in range(train_paths.size):\n",
366 | "\ttrain_paths_[i] = train_paths[i][35:]\n",
367 | "\t#train_paths_[i] = train_paths[i][34:]\n",
368 | "\ttrain_paths_[i] = \"drive/My Drive/data/output/labels/\" + train_paths_[i]\n",
369 | "\t#train_paths_[i] = \"drive/My Drive/data/output/annotations/\" + train_paths_[i]\n",
370 | "\t#print (train_paths_[i])\n",
371 | "\n",
372 | "#print (\"split\")\n",
373 | "\n",
374 | "for i in range(test_paths.size):\n",
375 | "\ttest_paths_[i] = test_paths[i][35:]\n",
376 | "\t#test_paths_[i] = test_paths[i][34:]\n",
377 | "\ttest_paths_[i] = \"drive/My Drive/data/output/labels/\" + test_paths_[i]\n",
378 | "\t#test_paths_[i] = \"drive/My Drive/data/output/annotations/\" + test_paths_[i]\n",
379 | "\t#print (test_paths_[i])\n",
380 | "\n",
381 | "train_csv = np.stack((train_paths,train_paths_), axis=1)\n",
382 | "test_csv = np.stack((test_paths,test_paths_), axis=1)\n",
383 | "\n",
384 | "np.savetxt(\"train.csv\", train_csv, delimiter=\",\", fmt=\"%s\")\n",
385 | "np.savetxt(\"test.csv\", test_csv, delimiter=\",\", fmt=\"%s\")"
386 | ],
387 | "execution_count": null,
388 | "outputs": [
389 | {
390 | "output_type": "stream",
391 | "text": [
392 | "train set: 11534\n",
393 | "test set: 8\n"
394 | ],
395 | "name": "stdout"
396 | }
397 | ]
398 | },
399 | {
400 | "cell_type": "markdown",
401 | "metadata": {
402 | "id": "cHjVOXKMfXSa"
403 | },
404 | "source": [
405 | "### load tensorflow"
406 | ]
407 | },
408 | {
409 | "cell_type": "code",
410 | "metadata": {
411 | "id": "-YpGHNnLuAt9",
412 | "colab": {
413 | "base_uri": "https://localhost:8080/",
414 | "height": 68
415 | },
416 | "outputId": "dcd8132f-f5ae-45f0-fcdd-fe89f1910423"
417 | },
418 | "source": [
419 | "#import os\n",
420 | "#os.getcwd()\n",
421 | "#os.listdir()\n",
422 | "#os.path.exists('drive/My Drive/')\n",
423 | "#for roots,dirs,files in os.walk('drive/My Drive'): \n",
424 | "# print(roots,dirs,files)\n",
425 | "%tensorflow_version 1.x\n",
426 | "import tensorflow as tf\n",
427 | "device_name = tf.test.gpu_device_name()\n",
428 | "print('TensorFlow Version: {}'.format(tf.__version__))\n",
429 | "if device_name != '/device:GPU:0':\n",
430 | " raise SystemError('GPU device not found')\n",
431 | "print('Found GPU at: {}'.format(device_name))"
432 | ],
433 | "execution_count": null,
434 | "outputs": [
435 | {
436 | "output_type": "stream",
437 | "text": [
438 | "TensorFlow 1.x selected.\n",
439 | "TensorFlow Version: 1.15.2\n",
440 | "Found GPU at: /device:GPU:0\n"
441 | ],
442 | "name": "stdout"
443 | }
444 | ]
445 | },
446 | {
447 | "cell_type": "code",
448 | "metadata": {
449 | "id": "sdVEq0W1we7T"
450 | },
451 | "source": [
452 | "from tensorflow.python.client import device_lib\n",
453 | "device_lib.list_local_devices()"
454 | ],
455 | "execution_count": null,
456 | "outputs": []
457 | },
458 | {
459 | "cell_type": "code",
460 | "metadata": {
461 | "id": "iJis0dgqxwGB",
462 | "colab": {
463 | "base_uri": "https://localhost:8080/",
464 | "height": 258
465 | },
466 | "outputId": "2005613f-bf1e-44c7-c8b0-0c61609123f7"
467 | },
468 | "source": [
469 | "# memory footprint support libraries/code\n",
470 | "!ln -sf /opt/bin/nvidia-smi /usr/bin/nvidia-smi\n",
471 | "!pip install gputil\n",
472 | "!pip install psutil\n",
473 | "!pip install humanize\n",
474 | "import psutil\n",
475 | "import humanize\n",
476 | "import os\n",
477 | "import GPUtil as GPU\n",
478 | "GPUs = GPU.getGPUs()\n",
479 | "# XXX: only one GPU on Colab and isn’t guaranteed\n",
480 | "gpu = GPUs[0]\n",
481 | "def printm():\n",
482 | " process = psutil.Process(os.getpid())\n",
483 | " print(\"Gen RAM Free: \" + humanize.naturalsize( psutil.virtual_memory().available ), \" | Proc size: \" + humanize.naturalsize( process.memory_info().rss))\n",
484 | " print(\"GPU RAM Free: {0:.0f}MB | Used: {1:.0f}MB | Util {2:3.0f}% | Total {3:.0f}MB\".format(gpu.memoryFree, gpu.memoryUsed, gpu.memoryUtil*100, gpu.memoryTotal))\n",
485 | "printm() "
486 | ],
487 | "execution_count": null,
488 | "outputs": [
489 | {
490 | "output_type": "stream",
491 | "text": [
492 | "Collecting gputil\n",
493 | " Downloading https://files.pythonhosted.org/packages/ed/0e/5c61eedde9f6c87713e89d794f01e378cfd9565847d4576fa627d758c554/GPUtil-1.4.0.tar.gz\n",
494 | "Building wheels for collected packages: gputil\n",
495 | " Building wheel for gputil (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
496 | " Created wheel for gputil: filename=GPUtil-1.4.0-cp36-none-any.whl size=7413 sha256=ee2b3d234e82bb1c13f028526f9f680f5971df1f7db91a5bc6c48c72b186221a\n",
497 | " Stored in directory: /root/.cache/pip/wheels/3d/77/07/80562de4bb0786e5ea186911a2c831fdd0018bda69beab71fd\n",
498 | "Successfully built gputil\n",
499 | "Installing collected packages: gputil\n",
500 | "Successfully installed gputil-1.4.0\n",
501 | "Requirement already satisfied: psutil in /usr/local/lib/python3.6/dist-packages (5.4.8)\n",
502 | "Requirement already satisfied: humanize in /usr/local/lib/python3.6/dist-packages (0.5.1)\n",
503 | "Gen RAM Free: 12.4 GB | Proc size: 557.2 MB\n",
504 | "GPU RAM Free: 16015MB | Used: 265MB | Util 2% | Total 16280MB\n"
505 | ],
506 | "name": "stdout"
507 | }
508 | ]
509 | },
510 | {
511 | "cell_type": "markdown",
512 | "metadata": {
513 | "id": "EqLtpXRru2kh"
514 | },
515 | "source": [
516 | "### Train"
517 | ]
518 | },
519 | {
520 | "cell_type": "code",
521 | "metadata": {
522 | "id": "SIVvZ3JxsepC"
523 | },
524 | "source": [
525 | "#!rm 'drive/My Drive/data/models' -rf\n",
526 | "#!rm 'drive/My Drive/data/logs' -rf"
527 | ],
528 | "execution_count": null,
529 | "outputs": []
530 | },
531 | {
532 | "cell_type": "code",
533 | "metadata": {
534 | "id": "9jHwMuhTxgBi",
535 | "colab": {
536 | "base_uri": "https://localhost:8080/",
537 | "height": 272
538 | },
539 | "outputId": "43824013-f102-4ad3-9f4f-c9d73270042e"
540 | },
541 | "source": [
542 | "import time\n",
543 | "import os\n",
544 | "import pandas as pd\n",
545 | "import tensorflow as tf\n",
546 | "\n",
547 | "\n",
548 | "def image_augmentation(image, mask):\n",
549 | " \"\"\"Returns (maybe) augmented images\n",
550 | " (1) Random flip (left <--> right)\n",
551 | " (2) Random flip (up <--> down)\n",
552 | " (3) Random brightness\n",
553 | " (4) Random hue\n",
554 | " Args:\n",
555 | " image (3-D Tensor): Image tensor of (H, W, C)\n",
556 | " mask (3-D Tensor): Mask image tensor of (H, W, 1)\n",
557 | " Returns:\n",
558 | " image: Maybe augmented image (same shape as input `image`)\n",
559 | " mask: Maybe augmented mask (same shape as input `mask`)\n",
560 | " \"\"\"\n",
561 | " concat_image = tf.concat([image, mask], axis=-1)\n",
562 | "\n",
563 | " maybe_flipped = tf.image.random_flip_left_right(concat_image)\n",
564 | " maybe_flipped = tf.image.random_flip_up_down(concat_image)\n",
565 | "\n",
566 | " image = maybe_flipped[:, :, :-1]\n",
567 | " mask = maybe_flipped[:, :, -1:]\n",
568 | "\n",
569 | " image = tf.image.random_brightness(image, 0.7)\n",
570 | " image = tf.image.random_hue(image, 0.3)\n",
571 | "\n",
572 | " return image, mask\n",
573 | "\n",
574 | "\n",
575 | "def get_image_mask(queue, augmentation=True):\n",
576 | " \"\"\"Returns `image` and `mask`\n",
577 | " Input pipeline:\n",
578 | " Queue -> CSV -> FileRead -> Decode JPEG\n",
579 | " (1) Queue contains a CSV filename\n",
580 | " (2) Text Reader opens the CSV\n",
581 | " CSV file contains two columns\n",
582 | " [\"path/to/image.jpg\", \"path/to/mask.jpg\"]\n",
583 | " (3) File Reader opens both files\n",
584 | " (4) Decode JPEG to tensors\n",
585 | " Notes:\n",
586 | " height, width = 640, 960\n",
587 | " Returns\n",
588 | " image (3-D Tensor): (640, 960, 3)\n",
589 | " mask (3-D Tensor): (640, 960, 1)\n",
590 | " \"\"\"\n",
591 | " text_reader = tf.TextLineReader(skip_header_lines=1)\n",
592 | " _, csv_content = text_reader.read(queue)\n",
593 | "\n",
594 | " image_path, mask_path = tf.decode_csv(\n",
595 | " csv_content, record_defaults=[[\"\"], [\"\"]])\n",
596 | "\n",
597 | " image_file = tf.read_file(image_path)\n",
598 | " mask_file = tf.read_file(mask_path)\n",
599 | "\n",
600 | " image = tf.image.decode_jpeg(image_file, channels=3)\n",
601 | " image.set_shape([512, 512, 3])\n",
602 | " image = tf.cast(image, tf.float32)\n",
603 | "\n",
604 | " mask = tf.image.decode_jpeg(mask_file, channels=1)\n",
605 | " mask.set_shape([512, 512, 1])\n",
606 | " mask = tf.cast(mask, tf.float32)\n",
607 | " mask = mask / (tf.reduce_max(mask) + 1e-7)\n",
608 | "\n",
609 | " if augmentation:\n",
610 | " image, mask = image_augmentation(image, mask)\n",
611 | "\n",
612 | " return image, mask\n",
613 | "\n",
614 | "\n",
615 | "def conv_conv_pool(input_,\n",
616 | " n_filters,\n",
617 | " training,\n",
618 | " flags,\n",
619 | " name,\n",
620 | " pool=True,\n",
621 | " activation=tf.nn.relu):\n",
622 | " \"\"\"{Conv -> BN -> RELU}x2 -> {Pool, optional}\n",
623 | " Args:\n",
624 | " input_ (4-D Tensor): (batch_size, H, W, C)\n",
625 | " n_filters (list): number of filters [int, int]\n",
626 | " training (1-D Tensor): Boolean Tensor\n",
627 | " name (str): name postfix\n",
628 | " pool (bool): If True, MaxPool2D\n",
629 | " activation: Activaion functions\n",
630 | " Returns:\n",
631 | " net: output of the Convolution operations\n",
632 | " pool (optional): output of the max pooling operations\n",
633 | " \"\"\"\n",
634 | " net = input_\n",
635 | "\n",
636 | " with tf.variable_scope(\"layer{}\".format(name)):\n",
637 | " for i, F in enumerate(n_filters):\n",
638 | " net = tf.layers.conv2d(\n",
639 | " net,\n",
640 | " F, (3, 3),\n",
641 | " activation=None,\n",
642 | " padding='same',\n",
643 | " kernel_regularizer=tf.contrib.layers.l2_regularizer(flags.reg),\n",
644 | " name=\"conv_{}\".format(i + 1))\n",
645 | " net = tf.layers.batch_normalization(\n",
646 | " net, training=training, name=\"bn_{}\".format(i + 1))\n",
647 | " net = activation(net, name=\"relu{}_{}\".format(name, i + 1))\n",
648 | "\n",
649 | " if pool is False:\n",
650 | " return net\n",
651 | "\n",
652 | " pool = tf.layers.max_pooling2d(\n",
653 | " net, (2, 2), strides=(2, 2), name=\"pool_{}\".format(name))\n",
654 | "\n",
655 | " return net, pool\n",
656 | "\n",
657 | "\n",
658 | "def upconv_concat(inputA, input_B, n_filter, flags, name):\n",
659 | " \"\"\"Upsample `inputA` and concat with `input_B`\n",
660 | " Args:\n",
661 | " input_A (4-D Tensor): (N, H, W, C)\n",
662 | " input_B (4-D Tensor): (N, 2*H, 2*H, C2)\n",
663 | " name (str): name of the concat operation\n",
664 | " Returns:\n",
665 | " output (4-D Tensor): (N, 2*H, 2*W, C + C2)\n",
666 | " \"\"\"\n",
667 | " up_conv = upconv_2D(inputA, n_filter, flags, name)\n",
668 | "\n",
669 | " return tf.concat(\n",
670 | " [up_conv, input_B], axis=-1, name=\"concat_{}\".format(name))\n",
671 | "\n",
672 | "\n",
673 | "def upconv_2D(tensor, n_filter, flags, name):\n",
674 | " \"\"\"Up Convolution `tensor` by 2 times\n",
675 | " Args:\n",
676 | " tensor (4-D Tensor): (N, H, W, C)\n",
677 | " n_filter (int): Filter Size\n",
678 | " name (str): name of upsampling operations\n",
679 | " Returns:\n",
680 | " output (4-D Tensor): (N, 2 * H, 2 * W, C)\n",
681 | " \"\"\"\n",
682 | "\n",
683 | " return tf.layers.conv2d_transpose(\n",
684 | " tensor,\n",
685 | " filters=n_filter,\n",
686 | " kernel_size=2,\n",
687 | " strides=2,\n",
688 | " kernel_regularizer=tf.contrib.layers.l2_regularizer(flags.reg),\n",
689 | " name=\"upsample_{}\".format(name))\n",
690 | "\n",
691 | "\n",
692 | "def make_unet(X, training, flags=None):\n",
693 | " \"\"\"Build a U-Net architecture\n",
694 | " Args:\n",
695 | " X (4-D Tensor): (N, H, W, C)\n",
696 | " training (1-D Tensor): Boolean Tensor is required for batchnormalization layers\n",
697 | " Returns:\n",
698 | " output (4-D Tensor): (N, H, W, C)\n",
699 | " Same shape as the `input` tensor\n",
700 | " Notes:\n",
701 | " U-Net: Convolutional Networks for Biomedical Image Segmentation\n",
702 | " https://arxiv.org/abs/1505.04597\n",
703 | " \"\"\"\n",
704 | " net = X / 127.5 - 1\n",
705 | " conv1, pool1 = conv_conv_pool(net, [16, 16], training, flags, name=1)\n",
706 | " conv2, pool2 = conv_conv_pool(pool1, [32, 32], training, flags, name=2)\n",
707 | " conv3, pool3 = conv_conv_pool(pool2, [64, 64], training, flags, name=3)\n",
708 | " conv4, pool4 = conv_conv_pool(pool3, [128, 128], training, flags, name=4)\n",
709 | " conv5, pool5 = conv_conv_pool(pool4, [256, 256], training, flags, name=5)\n",
710 | " conv6, pool6 = conv_conv_pool(pool5, [512, 512], training, flags, name=6)\n",
711 | " conv7 = conv_conv_pool(\n",
712 | " pool6, [1024, 1024], training, flags, name=7, pool=False)\n",
713 | "\n",
714 | " up8 = upconv_concat(conv7, conv6, 512, flags, name=8)\n",
715 | " conv8 = conv_conv_pool(up8, [512, 512], training, flags, name=8, pool=False)\n",
716 | "\n",
717 | " up9 = upconv_concat(conv8, conv5, 256, flags, name=9)\n",
718 | " conv9 = conv_conv_pool(up9, [256, 256], training, flags, name=9, pool=False)\n",
719 | "\n",
720 | " up10 = upconv_concat(conv9, conv4, 128, flags, name=10)\n",
721 | " conv10 = conv_conv_pool(up10, [128, 128], training, flags, name=10, pool=False)\n",
722 | "\n",
723 | " up11 = upconv_concat(conv10, conv3, 64, flags, name=11)\n",
724 | " conv11 = conv_conv_pool(up11, [64, 64], training, flags, name=11, pool=False)\n",
725 | "\n",
726 | " up12 = upconv_concat(conv11, conv2, 32, flags, name=12)\n",
727 | " conv12 = conv_conv_pool(up12, [32, 32], training, flags, name=12, pool=False)\n",
728 | "\n",
729 | " up13 = upconv_concat(conv12, conv1, 16, flags, name=13)\n",
730 | " conv13 = conv_conv_pool(up13, [16, 16], training, flags, name=13, pool=False)\n",
731 | "\n",
732 | " # return tf.layers.conv2d(\n",
733 | " # conv13,\n",
734 | " # 1, (1, 1),\n",
735 | " # name='final',\n",
736 | " # activation=tf.nn.sigmoid,\n",
737 | " # padding='same')\n",
738 | " return tf.layers.conv2d(conv13,1, (1, 1),name='final',activation=None,padding='same')\n",
739 | "\n",
740 | "def BCE_(y_pred, y_true):\n",
741 | " # weight ratio = 9:1\n",
742 | " # 9-1=8\n",
743 | " class_weights = tf.constant([8],dtype=tf.float32)\n",
744 | " tensor_one = tf.constant([1],dtype=tf.float32)\n",
745 | "\n",
746 | " pred_flat = tf.reshape(y_pred, [-1, 1])\n",
747 | " true_flat = tf.reshape(y_true, [-1, 1])\n",
748 | "\n",
749 | " weight_map = tf.multiply(true_flat, class_weights)\n",
750 | " weight_map = tf.add(weight_map, tensor_one)\n",
751 | "\n",
752 | " loss_map = tf.nn.sigmoid_cross_entropy_with_logits(logits=pred_flat, labels=true_flat)\n",
753 | " loss_map = tf.multiply(loss_map, weight_map)\n",
754 | " loss = tf.reduce_mean(loss_map)\n",
755 | " return loss\n",
756 | "\n",
757 | "def IOU_(y_pred, y_true):\n",
758 | " \"\"\"Returns a (approx) IOU score\n",
759 | " intesection = y_pred.flatten() * y_true.flatten()\n",
760 | " Then, IOU = 2 * intersection / (y_pred.sum() + y_true.sum() + 1e-7) + 1e-7\n",
761 | " Args:\n",
762 | " y_pred (4-D array): (N, H, W, 1)\n",
763 | " y_true (4-D array): (N, H, W, 1)\n",
764 | " Returns:\n",
765 | " float: IOU score\n",
766 | " \"\"\"\n",
767 | " H, W, _ = y_pred.get_shape().as_list()[1:]\n",
768 | " threshold = 0.7\n",
769 | " pred_flat = tf.reshape(y_pred, [-1, H * W])\n",
770 | " true_flat = tf.reshape(y_true, [-1, H * W])\n",
771 | " pred = tf.cast(pred_flat > threshold, dtype=tf.float32)\n",
772 | " true = tf.cast(true_flat > threshold, dtype=tf.float32)\n",
773 | " intersection = tf.reduce_sum(pred * true, axis=1) + 1e-7\n",
774 | " denominator = tf.reduce_sum(pred, axis=1) + tf.reduce_sum(true, axis=1) + 1e-7\n",
775 | "\n",
776 | " return tf.reduce_mean(intersection / denominator)\n",
777 | "\n",
778 | "\n",
779 | "def make_train_op(y_pred, y_true):\n",
780 | " \"\"\"Returns a training operation\n",
781 | " Args:\n",
782 | " y_pred (4-D Tensor): (N, H, W, 1)\n",
783 | " y_true (4-D Tensor): (N, H, W, 1)\n",
784 | " Returns:\n",
785 | " train_op: minimize operation\n",
786 | " \"\"\"\n",
787 | " # loss = -IOU_(y_pred, y_true)\n",
788 | " loss = BCE_(y_pred, y_true)\n",
789 | "\n",
790 | " global_step = tf.train.get_or_create_global_step()\n",
791 | "\n",
792 | " # optim = tf.train.AdamOptimizer()\n",
793 | " optim = tf.train.AdamOptimizer(1e-4)\n",
794 | " return optim.minimize(loss, global_step=global_step)\n",
795 | "class flags:\n",
796 | " epochs = 100\n",
797 | " batch_size = 8\n",
798 | " logdir = \"drive/My Drive/data/logs/\"\n",
799 | " reg = 0.1\n",
800 | " ckdir = \"drive/My Drive/data/models/\"\n",
801 | "\n",
802 | "\n",
803 | "'''def read_flags():\n",
804 | " \"\"\"Returns flags\"\"\"\n",
805 | "\n",
806 | " import argparse\n",
807 | "\n",
808 | " parser = argparse.ArgumentParser(\n",
809 | " formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n",
810 | " parser.add_argument(\n",
811 | " \"--epochs\", default=1, type=int, help=\"Number of epochs\")\n",
812 | "\n",
813 | " parser.add_argument(\"--batch-size\", default=8, type=int, help=\"Batch size\")\n",
814 | "\n",
815 | " parser.add_argument(\n",
816 | " \"--logdir\", default=\"logdir\", help=\"Tensorboard log directory\")\n",
817 | "\n",
818 | " parser.add_argument(\n",
819 | " \"--reg\", type=float, default=0.1, help=\"L2 Regularizer Term\")\n",
820 | "\n",
821 | " parser.add_argument(\n",
822 | " \"--ckdir\", default=\"models\", help=\"Checkpoint directory\")\n",
823 | "\n",
824 | " flags = parser.parse_args()\n",
825 | " return flags'''\n",
826 | "\n",
827 | "\n",
828 | "def main():\n",
829 | " train = pd.read_csv(\"./train.csv\")\n",
830 | " n_train = train.shape[0]\n",
831 | "\n",
832 | " test = pd.read_csv(\"./test.csv\")\n",
833 | " n_test = test.shape[0]\n",
834 | "\n",
835 | " current_time = time.strftime(\"%m/%d/%H/%M/%S\")\n",
836 | " train_logdir = os.path.join(flags.logdir, \"train\", current_time)\n",
837 | " test_logdir = os.path.join(flags.logdir, \"test\", current_time)\n",
838 | "\n",
839 | " tf.reset_default_graph()\n",
840 | " X = tf.placeholder(tf.float32, shape=[None, 512, 512, 3], name=\"X\")\n",
841 | " y = tf.placeholder(tf.float32, shape=[None, 512, 512, 1], name=\"y\")\n",
842 | " mode = tf.placeholder(tf.bool, name=\"mode\")\n",
843 | "\n",
844 | " pred = make_unet(X, mode, flags)\n",
845 | "\n",
846 | " tf.add_to_collection(\"inputs\", X)\n",
847 | " tf.add_to_collection(\"inputs\", mode)\n",
848 | " tf.add_to_collection(\"outputs\", pred)\n",
849 | "\n",
850 | " tf.summary.histogram(\"Predicted Mask\", pred)\n",
851 | " tf.summary.image(\"Predicted Mask\", pred)\n",
852 | "\n",
853 | " update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n",
854 | "\n",
855 | " with tf.control_dependencies(update_ops):\n",
856 | " train_op = make_train_op(pred, y)\n",
857 | "\n",
858 | " IOU_op = IOU_(pred, y)\n",
859 | " IOU_op = tf.Print(IOU_op, [IOU_op])\n",
860 | " tf.summary.scalar(\"IOU\", IOU_op)\n",
861 | "\n",
862 | " train_csv = tf.train.string_input_producer(['train.csv'])\n",
863 | " test_csv = tf.train.string_input_producer(['test.csv'])\n",
864 | " train_image, train_mask = get_image_mask(train_csv)\n",
865 | " test_image, test_mask = get_image_mask(test_csv, augmentation=False)\n",
866 | "\n",
867 | " X_batch_op, y_batch_op = tf.train.shuffle_batch(\n",
868 | " [train_image, train_mask],\n",
869 | " batch_size=flags.batch_size,\n",
870 | " capacity=flags.batch_size * 5,\n",
871 | " min_after_dequeue=flags.batch_size * 2,\n",
872 | " allow_smaller_final_batch=True)\n",
873 | "\n",
874 | " X_test_op, y_test_op = tf.train.batch(\n",
875 | " [test_image, test_mask],\n",
876 | " batch_size=flags.batch_size,\n",
877 | " capacity=flags.batch_size * 2,\n",
878 | " allow_smaller_final_batch=True)\n",
879 | "\n",
880 | " summary_op = tf.summary.merge_all()\n",
881 | "\n",
882 | " with tf.Session() as sess:\n",
883 | " train_summary_writer = tf.summary.FileWriter(train_logdir, sess.graph)\n",
884 | " test_summary_writer = tf.summary.FileWriter(test_logdir)\n",
885 | "\n",
886 | " init = tf.global_variables_initializer()\n",
887 | " sess.run(init)\n",
888 | "\n",
889 | " saver = tf.train.Saver()\n",
890 | " if os.path.exists(flags.ckdir):\n",
891 | " latest_check_point = tf.train.latest_checkpoint(flags.ckdir)\n",
892 | " saver.restore(sess, latest_check_point)\n",
893 | " print('model restored!')\n",
894 | "\n",
895 | " else:\n",
896 | " #try:\n",
897 | " # os.rmdir(flags.ckdir)\n",
898 | " #except IOError:\n",
899 | " # pass\n",
900 | " os.mkdir(flags.ckdir)\n",
901 | "\n",
902 | " try:\n",
903 | " global_step = tf.train.get_global_step(sess.graph)\n",
904 | "\n",
905 | " coord = tf.train.Coordinator()\n",
906 | " threads = tf.train.start_queue_runners(coord=coord)\n",
907 | " start = time.time()\n",
908 | " for epoch in range(90,flags.epochs):\n",
909 | " print('%d epochs in %fs' % (epoch, 62539+time.time()-start))\n",
910 | " for step in range(0, n_train, flags.batch_size):\n",
911 | " #print(\"%d train steps in %fs\" %(step, time.time()-start))\n",
912 | " X_batch, y_batch = sess.run([X_batch_op, y_batch_op])\n",
913 | "\n",
914 | " _, step_iou, step_summary, global_step_value = sess.run(\n",
915 | " [train_op, IOU_op, summary_op, global_step],\n",
916 | " feed_dict={X: X_batch,\n",
917 | " y: y_batch,\n",
918 | " mode: True})\n",
919 | "\n",
920 | " train_summary_writer.add_summary(step_summary,\n",
921 | " global_step_value)\n",
922 | "\n",
923 | " total_iou = 0\n",
924 | " for step in range(0, n_test, flags.batch_size):\n",
925 | " #print(\"%d test steps in %fs\" %(step, time.time()-start))\n",
926 | " X_test, y_test = sess.run([X_test_op, y_test_op])\n",
927 | " step_iou, step_summary = sess.run(\n",
928 | " [IOU_op, summary_op],\n",
929 | " feed_dict={X: X_test,\n",
930 | " y: y_test,\n",
931 | " mode: False})\n",
932 | "\n",
933 | " total_iou += step_iou * X_test.shape[0]\n",
934 | "\n",
935 | " test_summary_writer.add_summary(step_summary,(epoch + 1) * (step + 1))\n",
936 | "\n",
937 | " #saver.save(sess, \"{}/model.ckpt\".format(flags.ckdir))\n",
938 | " #print('the %d epoch in %fs, saved successfully' % (epoch, time.time()-start))\n",
939 | "\n",
940 | " finally:\n",
941 | " coord.request_stop()\n",
942 | " coord.join(threads)\n",
943 | " saver.save(sess, \"{}/model.ckpt\".format(flags.ckdir))\n",
944 | " print('model saved successfully')\n",
945 | "\n",
946 | "\n",
947 | "\n",
948 | "if __name__ == '__main__':\n",
949 | " #flags = read_flags()\n",
950 | " main()"
951 | ],
952 | "execution_count": null,
953 | "outputs": [
954 | {
955 | "output_type": "stream",
956 | "text": [
957 | "INFO:tensorflow:Summary name Predicted Mask is illegal; using Predicted_Mask instead.\n",
958 | "INFO:tensorflow:Summary name Predicted Mask is illegal; using Predicted_Mask instead.\n",
959 | "INFO:tensorflow:Restoring parameters from drive/My Drive/data/models/model.ckpt\n",
960 | "model restored!\n",
961 | "90 epochs in 62539.000005s\n",
962 | "91 epochs in 63012.843219s\n",
963 | "92 epochs in 63480.010369s\n",
964 | "93 epochs in 63947.371985s\n",
965 | "94 epochs in 64414.004312s\n",
966 | "95 epochs in 64883.230457s\n",
967 | "96 epochs in 65350.314995s\n",
968 | "97 epochs in 65820.104939s\n",
969 | "98 epochs in 66288.175114s\n",
970 | "99 epochs in 66757.795235s\n",
971 | "model saved successfully\n"
972 | ],
973 | "name": "stdout"
974 | }
975 | ]
976 | },
977 | {
978 | "cell_type": "code",
979 | "metadata": {
980 | "id": "TQOF55DOjN_B"
981 | },
982 | "source": [
983 | "%load_ext tensorboard\n",
984 | "%tensorboard --logdir 'drive/My Drive/data/logs'\n",
985 | "#%reload_ext tensorboard"
986 | ],
987 | "execution_count": null,
988 | "outputs": []
989 | },
990 | {
991 | "cell_type": "markdown",
992 | "metadata": {
993 | "id": "p2JGpoMrtNx3"
994 | },
995 | "source": [
996 | "### Test on a single image"
997 | ]
998 | },
999 | {
1000 | "cell_type": "code",
1001 | "metadata": {
1002 | "id": "AXJmE8wYtUJ2",
1003 | "colab": {
1004 | "base_uri": "https://localhost:8080/",
1005 | "height": 139
1006 | },
1007 | "outputId": "b50675a1-3018-42ed-a51c-9d2e17fd8f4a"
1008 | },
1009 | "source": [
1010 | "import tensorflow as tf\n",
1011 | "import cv2\n",
1012 | "import pandas as pd\n",
1013 | "import matplotlib.pyplot as plt\n",
1014 | "import numpy as np\n",
1015 | "from scipy.ndimage.measurements import label\n",
1016 | "from PIL import Image\n",
1017 | "from scipy.special import expit\n",
1018 | "\n",
1019 | "saver = tf.train.import_meta_graph(\"drive/My Drive/data/models/model.ckpt.meta\")\n",
1020 | "sess = tf.InteractiveSession()\n",
1021 | "saver.restore(sess, \"drive/My Drive/data/models/model.ckpt\")\n",
1022 | "X, mode = tf.get_collection(\"inputs\")[:2]\n",
1023 | "pred = tf.get_collection(\"outputs\")[0]\n",
1024 | "\n",
1025 | "def read_image(image_path, gray=False):\n",
1026 | " \"\"\"Returns an image array\n",
1027 | " Args:\n",
1028 | " image_path (str): Path to image.jpg\n",
1029 | " Returns:\n",
1030 | " 3-D array: RGB numpy image array\n",
1031 | " \"\"\"\n",
1032 | " if gray:\n",
1033 | " return cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n",
1034 | " \n",
1035 | " image = cv2.imread(image_path) \n",
1036 | " return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
1037 | "\n",
1038 | "def pipeline(image, threshold=0.5, image_WH=(512, 512)):\n",
1039 | " image = np.copy(image)\n",
1040 | " H, W, C = image.shape\n",
1041 | " \n",
1042 | " if (W, H) != image_WH:\n",
1043 | " image = cv2.resize(image, image_WH)\n",
1044 | " \n",
1045 | " mask_pred = sess.run(pred, feed_dict={X: np.expand_dims(image, 0),\n",
1046 | " mode: False})\n",
1047 | " \n",
1048 | " mask_pred = np.squeeze(mask_pred)\n",
1049 | " mask_pred = expit(mask_pred)\n",
1050 | " # mask_pred = mask_pred > threshold\n",
1051 | " return mask_pred\n",
1052 | "\n",
1053 | "image_path = \"drive/My Drive/data/output/images/IDRiD_17.jpg\"\n",
1054 | "image = read_image(image_path)\n",
1055 | "predicted_image = np.zeros((2848, 4288), dtype=float)\n",
1056 | "\n",
1057 | "for i in range(10): #10 6\n",
1058 | " for j in range(16): #16 9\n",
1059 | " top_y = i*256 #256 512\n",
1060 | " if (i==9): #9 5\n",
1061 | " top_y = 2336\n",
1062 | " top_x = j*256 #256 512\n",
1063 | " if (j==15): #15 8\n",
1064 | " top_x = 3776\n",
1065 | "\n",
1066 | " image_crop = image[top_y:top_y+512, top_x:top_x+512]\n",
1067 | " predicted_crop = pipeline(image_crop)\n",
1068 | " predicted_image[top_y:top_y+512, top_x:top_x+512] = np.maximum(predicted_image[top_y:top_y+512, top_x:top_x+512], predicted_crop)\n",
1069 | "\n",
1070 | "threshold = 0.7\n",
1071 | "predicted_image = predicted_image > threshold\n",
1072 | "(unique, counts) = np.unique(predicted_image.astype('uint8')*255, return_counts=True)\n",
1073 | "frequencies = np.asarray((unique, counts)).T\n",
1074 | "print(frequencies)\n",
1075 | "\n",
1076 | "predicted_save = Image.fromarray((predicted_image.astype('uint8'))*255)\n",
1077 | "predicted_save.save(\"test_predicted.jpg\", \"JPEG\")"
1078 | ],
1079 | "execution_count": null,
1080 | "outputs": [
1081 | {
1082 | "output_type": "stream",
1083 | "text": [
1084 | "WARNING:tensorflow:From /tensorflow-1.15.2/python3.6/tensorflow_core/python/training/queue_runner_impl.py:391: QueueRunner.__init__ (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version.\n",
1085 | "Instructions for updating:\n",
1086 | "To construct input pipelines, use the `tf.data` module.\n",
1087 | "INFO:tensorflow:Restoring parameters from drive/My Drive/data/models/model.ckpt\n",
1088 | "[[ 0 10224722]\n",
1089 | " [ 255 1987502]]\n"
1090 | ],
1091 | "name": "stdout"
1092 | }
1093 | ]
1094 | },
1095 | {
1096 | "cell_type": "markdown",
1097 | "metadata": {
1098 | "id": "ByIpNhUk-xQr"
1099 | },
1100 | "source": [
1101 | "### Generate probability maps for the dataset using the trained model"
1102 | ]
1103 | },
1104 | {
1105 | "cell_type": "code",
1106 | "metadata": {
1107 | "id": "1zed1ERU_FyF",
1108 | "colab": {
1109 | "base_uri": "https://localhost:8080/",
1110 | "height": 88
1111 | },
1112 | "outputId": "67f45da6-6b60-459b-c072-9d364ff20b58"
1113 | },
1114 | "source": [
1115 | "import tensorflow as tf\n",
1116 | "import cv2\n",
1117 | "import pandas as pd\n",
1118 | "import matplotlib.pyplot as plt\n",
1119 | "import numpy as np\n",
1120 | "from scipy.ndimage.measurements import label\n",
1121 | "from PIL import Image\n",
1122 | "from scipy.special import expit\n",
1123 | "import os, sys\n",
1124 | "\n",
1125 | "saver = tf.train.import_meta_graph(\"drive/My Drive/data/models/model.ckpt.meta\")\n",
1126 | "sess = tf.InteractiveSession()\n",
1127 | "saver.restore(sess, \"drive/My Drive/data/models/model.ckpt\")\n",
1128 | "X, mode = tf.get_collection(\"inputs\")[:2]\n",
1129 | "pred = tf.get_collection(\"outputs\")[0]\n",
1130 | "\n",
1131 | "def read_image(image_path, gray=False):\n",
1132 | " \"\"\"Returns an image array\n",
1133 | " Args:\n",
1134 | " image_path (str): Path to image.jpg\n",
1135 | " Returns:\n",
1136 | " 3-D array: RGB numpy image array\n",
1137 | " \"\"\"\n",
1138 | " if gray:\n",
1139 | " return cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n",
1140 | " \n",
1141 | " image = cv2.imread(image_path) \n",
1142 | " return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
1143 | "\n",
1144 | "def pipeline(image, image_WH=(512, 512)):\n",
1145 | " image = np.copy(image)\n",
1146 | " H, W, C = image.shape\n",
1147 | " \n",
1148 | " if (W, H) != image_WH:\n",
1149 | " image = cv2.resize(image, image_WH)\n",
1150 | " \n",
1151 | " mask_pred = sess.run(pred, feed_dict={X: np.expand_dims(image, 0),\n",
1152 | " mode: False})\n",
1153 | " \n",
1154 | " mask_pred = np.squeeze(mask_pred)\n",
1155 | " mask_pred = expit(mask_pred)\n",
1156 | " # mask_pred = mask_pred > threshold\n",
1157 | " return mask_pred\n",
1158 | "\n",
1159 | "output_dir = \"drive/My Drive/data/output/prob/\"\n",
1160 | "dir = os.getcwd()\n",
1161 | "\n",
1162 | "if not os.path.exists(os.path.join(dir,output_dir)):\n",
1163 | " os.mkdir(output_dir)\n",
1164 | "\n",
1165 | "for image_path in os.listdir(os.path.join(dir,\"drive/My Drive/data/output/images/\")):\n",
1166 | " image = read_image(\"drive/My Drive/data/output/images/\"+image_path)\n",
1167 | " predicted_image = np.zeros((2848, 4288), dtype=float)\n",
1168 | "\n",
1169 | " for i in range(10): #10 6\n",
1170 | " for j in range(16): #16 9\n",
1171 | " top_y = i*256 #256 512\n",
1172 | " if (i==9): #9 5\n",
1173 | " top_y = 2336\n",
1174 | " top_x = j*256 #256 512\n",
1175 | " if (j==15): #15 8\n",
1176 | " top_x = 3776\n",
1177 | "\n",
1178 | " image_crop = image[top_y:top_y+512, top_x:top_x+512]\n",
1179 | " predicted_crop = pipeline(image_crop)\n",
1180 | " predicted_image[top_y:top_y+512, top_x:top_x+512] = np.maximum(predicted_image[top_y:top_y+512, top_x:top_x+512], predicted_crop)\n",
1181 | "\n",
1182 | " # threshold = 0.5\n",
1183 | " # predicted_image = predicted_image > threshold\n",
1184 | " #(unique, counts) = np.unique((predicted_image*255).astype('uint8'), return_counts=True)\n",
1185 | " #frequencies = np.asarray((unique, counts)).T\n",
1186 | " #print(frequencies)\n",
1187 | " predicted_save = Image.fromarray((predicted_image*255).astype('uint8'))\n",
1188 | " predicted_save.save(output_dir+image_path, \"JPEG\", quality=100)"
1189 | ],
1190 | "execution_count": null,
1191 | "outputs": [
1192 | {
1193 | "output_type": "stream",
1194 | "text": [
1195 | "INFO:tensorflow:Restoring parameters from drive/My Drive/data/models/model.ckpt\n"
1196 | ],
1197 | "name": "stdout"
1198 | },
1199 | {
1200 | "output_type": "stream",
1201 | "text": [
1202 | "/tensorflow-1.15.2/python3.6/tensorflow_core/python/client/session.py:1750: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).\n",
1203 | " warnings.warn('An interactive session is already active. This can '\n"
1204 | ],
1205 | "name": "stderr"
1206 | }
1207 | ]
1208 | },
1209 | {
1210 | "cell_type": "markdown",
1211 | "metadata": {
1212 | "id": "CM2NY0sRHysI"
1213 | },
1214 | "source": [
1215 | "### plot FROC curve"
1216 | ]
1217 | },
1218 | {
1219 | "cell_type": "code",
1220 | "metadata": {
1221 | "id": "Aq8hygaTHxv-",
1222 | "colab": {
1223 | "base_uri": "https://localhost:8080/",
1224 | "height": 986
1225 | },
1226 | "outputId": "fc83bffd-4f6e-4a40-9828-ebd1dbb384b0"
1227 | },
1228 | "source": [
1229 | "from PIL import Image\n",
1230 | "import numpy as np\n",
1231 | "import os, sys\n",
1232 | "import matplotlib\n",
1233 | "matplotlib.use('Agg')\n",
1234 | "import matplotlib.pyplot as plt\n",
1235 | "\n",
1236 | "training_size=81\n",
1237 | "gt_dir = \"drive/My Drive/data/output/annotations/\"\n",
1238 | "prob_dir = \"drive/My Drive/data/output/prob/\"\n",
1239 | "true_p=0\n",
1240 | "actual_p=0\n",
1241 | "pred_p=0\n",
1242 | "false_p=0\n",
1243 | "\n",
1244 | "thresh_list = [0, 0.00001, 0.0001, 0.001, 0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.99, 0.999, 0.9999, 0.99999, 1]\n",
1245 | "\n",
1246 | "dir = os.getcwd()\n",
1247 | "thresh_size = len(thresh_list)\n",
1248 | "sn = np.empty(thresh_size, dtype=float)\n",
1249 | "fppi = np.empty(thresh_size, dtype=float)\n",
1250 | "thresh_array = np.array(thresh_list)\n",
1251 | "\n",
1252 | "for th in range(thresh_size):\n",
1253 | "\tthreshold = thresh_array[th]\n",
1254 | "\tprint (threshold)\n",
1255 | "\ttrue_p=0\n",
1256 | "\tactual_p=0\n",
1257 | "\tpred_p=0\n",
1258 | "\tfalse_p=0\n",
1259 | "\n",
1260 | "\tfor image_path in os.listdir(os.path.join(dir,gt_dir)):\n",
1261 | "\t\t# print image_path\n",
1262 | "\t\tim_gt = Image.open(gt_dir+image_path)\n",
1263 | "\t\timg = os.path.splitext(image_path)[0] + \".jpg\"\n",
1264 | "\t\tim_prob = Image.open(prob_dir+img)\n",
1265 | "\t\tarr_gt = np.array(im_gt)\n",
1266 | "\t\t#(unique, counts) = np.unique(arr_gt, return_counts=True)\n",
1267 | "\t\t#frequencies = np.asarray((unique, counts)).T\n",
1268 | "\t\t#print(\"arr_gt: \",frequencies)\n",
1269 | "\t\tarr_prob = (np.array(im_prob)).astype(float)/255\n",
1270 | "\t\t#(unique, counts) = np.unique(arr_prob, return_counts=True)\n",
1271 | "\t\t#frequencies = np.asarray((unique, counts)).T\n",
1272 | "\t\t#print(\"arr_prob: \",frequencies)\n",
1273 | "\t\tarr_pred = (arr_prob > threshold).astype('uint8')\n",
1274 | "\t\t#(unique, counts) = np.unique(arr_pred, return_counts=True)\n",
1275 | "\t\t#frequencies = np.asarray((unique, counts)).T\n",
1276 | "\t\t#print(\"arr_pred: \",frequencies)\n",
1277 | "\t\ttp = np.sum(np.logical_and(arr_gt, arr_pred))\n",
1278 | "\t\tap = np.sum(arr_gt)\n",
1279 | "\t\tpp = np.sum(arr_pred)\n",
1280 | "\t\ttrue_p += tp\n",
1281 | "\t\tactual_p += ap\n",
1282 | "\t\tpred_p += pp\n",
1283 | "\t\tfalse_p += (pp-tp)\n",
1284 | "\n",
1285 | "\tsn[th] = float(true_p)/float(actual_p)\n",
1286 | "\tprint (\"sn: \", sn[th])\n",
1287 | "\tfppi[th] = float(false_p)/float(training_size)\n",
1288 | "\tprint (\"fppi: \", fppi[th])\n",
1289 | "\n",
1290 | "plt.plot(fppi, sn)\n",
1291 | "plt.ylabel('SN')\n",
1292 | "plt.xlabel('FPs per image')\n",
1293 | "plt.savefig('drive/My Drive/data/froc.png')"
1294 | ],
1295 | "execution_count": null,
1296 | "outputs": [
1297 | {
1298 | "output_type": "stream",
1299 | "text": [
1300 | "0.0\n",
1301 | "sn: 0.9997918539315748\n",
1302 | "fppi: 433847.8024691358\n",
1303 | "1e-05\n",
1304 | "sn: 0.9997918539315748\n",
1305 | "fppi: 433847.8024691358\n",
1306 | "0.0001\n",
1307 | "sn: 0.9997918539315748\n",
1308 | "fppi: 433847.8024691358\n",
1309 | "0.001\n",
1310 | "sn: 0.9997918539315748\n",
1311 | "fppi: 433847.8024691358\n",
1312 | "0.01\n",
1313 | "sn: 0.9994911652226554\n",
1314 | "fppi: 298734.4567901235\n",
1315 | "0.1\n",
1316 | "sn: 0.9943516045316544\n",
1317 | "fppi: 163824.34567901236\n",
1318 | "0.2\n",
1319 | "sn: 0.9918498585006056\n",
1320 | "fppi: 133057.64197530865\n",
1321 | "0.3\n",
1322 | "sn: 0.9889898217071691\n",
1323 | "fppi: 113391.08641975309\n",
1324 | "0.4\n",
1325 | "sn: 0.985346916103857\n",
1326 | "fppi: 97763.20987654322\n",
1327 | "0.5\n",
1328 | "sn: 0.9808762180787789\n",
1329 | "fppi: 85151.83950617284\n",
1330 | "0.6\n",
1331 | "sn: 0.9739881305827571\n",
1332 | "fppi: 72394.50617283951\n",
1333 | "0.7\n",
1334 | "sn: 0.9626368323303055\n",
1335 | "fppi: 59131.567901234564\n",
1336 | "0.8\n",
1337 | "sn: 0.9414782104509493\n",
1338 | "fppi: 44431.61728395062\n",
1339 | "0.9\n",
1340 | "sn: 0.892350447299412\n",
1341 | "fppi: 26864.46913580247\n",
1342 | "0.99\n",
1343 | "sn: 0.5611847614316616\n",
1344 | "fppi: 2681.543209876543\n",
1345 | "0.999\n",
1346 | "sn: 0.001640410645737987\n",
1347 | "fppi: 13.061728395061728\n",
1348 | "0.9999\n",
1349 | "sn: 0.001640410645737987\n",
1350 | "fppi: 13.061728395061728\n",
1351 | "0.99999\n",
1352 | "sn: 0.001640410645737987\n",
1353 | "fppi: 13.061728395061728\n",
1354 | "1.0\n",
1355 | "sn: 0.0\n",
1356 | "fppi: 0.0\n"
1357 | ],
1358 | "name": "stdout"
1359 | }
1360 | ]
1361 | },
1362 | {
1363 | "cell_type": "markdown",
1364 | "metadata": {
1365 | "id": "rnNDIjEh_iD3"
1366 | },
1367 | "source": [
1368 | "### Generate segmented output masks from the probability maps"
1369 | ]
1370 | },
1371 | {
1372 | "cell_type": "code",
1373 | "metadata": {
1374 | "id": "37-KEnaJ_lxg",
1375 | "colab": {
1376 | "base_uri": "https://localhost:8080/",
1377 | "height": 88
1378 | },
1379 | "outputId": "4cb1dd97-c2dd-4144-f29e-5576fc42da3a"
1380 | },
1381 | "source": [
1382 | "import tensorflow as tf\n",
1383 | "import cv2\n",
1384 | "import pandas as pd\n",
1385 | "import matplotlib.pyplot as plt\n",
1386 | "import numpy as np\n",
1387 | "from scipy.ndimage.measurements import label\n",
1388 | "from PIL import Image\n",
1389 | "from scipy.special import expit\n",
1390 | "import os, sys\n",
1391 | "\n",
1392 | "saver = tf.train.import_meta_graph(\"drive/My Drive/data/models/model.ckpt.meta\")\n",
1393 | "sess = tf.InteractiveSession()\n",
1394 | "saver.restore(sess, \"drive/My Drive/data/models/model.ckpt\")\n",
1395 | "X, mode = tf.get_collection(\"inputs\")[:2]\n",
1396 | "pred = tf.get_collection(\"outputs\")[0]\n",
1397 | "\n",
1398 | "def read_image(image_path, gray=False):\n",
1399 | " \"\"\"Returns an image array\n",
1400 | " Args:\n",
1401 | " image_path (str): Path to image.jpg\n",
1402 | " Returns:\n",
1403 | " 3-D array: RGB numpy image array\n",
1404 | " \"\"\"\n",
1405 | " if gray:\n",
1406 | " return cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n",
1407 | " \n",
1408 | " image = cv2.imread(image_path) \n",
1409 | " return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
1410 | "\n",
1411 | "def pipeline(image, image_WH=(512, 512)):\n",
1412 | " image = np.copy(image)\n",
1413 | " H, W, C = image.shape\n",
1414 | " \n",
1415 | " if (W, H) != image_WH:\n",
1416 | " image = cv2.resize(image, image_WH)\n",
1417 | " \n",
1418 | " mask_pred = sess.run(pred, feed_dict={X: np.expand_dims(image, 0),\n",
1419 | " mode: False})\n",
1420 | " \n",
1421 | " mask_pred = np.squeeze(mask_pred)\n",
1422 | " mask_pred = expit(mask_pred)\n",
1423 | " # mask_pred = mask_pred > threshold\n",
1424 | " return mask_pred\n",
1425 | "\n",
1426 | "output_dir = \"drive/My Drive/data/output/predicted/\"\n",
1427 | "dir = os.getcwd()\n",
1428 | "\n",
1429 | "if not os.path.exists(os.path.join(dir,output_dir)):\n",
1430 | " os.mkdir(output_dir)\n",
1431 | "\n",
1432 | "for image_path in os.listdir(os.path.join(dir,\"drive/My Drive/data/output/prob/\")):\n",
1433 | " im_prob = Image.open(\"drive/My Drive/data/output/prob/\"+image_path)\n",
1434 | " arr_prob = (np.array(im_prob)).astype(float)/255\n",
1435 | " threshold = 0.8\n",
1436 | " arr_pred = (arr_prob > threshold).astype('uint8')\n",
1437 | " # image = read_image(\"test_data/\"+image_path)\n",
1438 | " # predicted_image = np.zeros((2848, 4288), dtype=float)\n",
1439 | "\n",
1440 | " # for i in range(10):\n",
1441 | " # for j in range(16):\n",
1442 | " # top_y = i*256\n",
1443 | " # if (i==9):\n",
1444 | " # top_y = 2336\n",
1445 | " # top_x = j*256\n",
1446 | " # if (j==15):\n",
1447 | " # top_x = 3776\n",
1448 | "\n",
1449 | " # image_crop = image[top_y:top_y+512, top_x:top_x+512]\n",
1450 | " # predicted_crop = pipeline(image_crop)\n",
1451 | " # predicted_image[top_y:top_y+512, top_x:top_x+512] = np.maximum(predicted_image[top_y:top_y+512, top_x:top_x+512], predicted_crop)\n",
1452 | " #(unique, counts) = np.unique(arr_pred*255, return_counts=True)\n",
1453 | " #frequencies = np.asarray((unique, counts)).T\n",
1454 | " #print(frequencies)\n",
1455 | " predicted_save = Image.fromarray(arr_pred*255)\n",
1456 | " predicted_save.save(output_dir+image_path, \"JPEG\", quality=100)"
1457 | ],
1458 | "execution_count": null,
1459 | "outputs": [
1460 | {
1461 | "output_type": "stream",
1462 | "text": [
1463 | "INFO:tensorflow:Restoring parameters from drive/My Drive/data/models/model.ckpt\n"
1464 | ],
1465 | "name": "stdout"
1466 | },
1467 | {
1468 | "output_type": "stream",
1469 | "text": [
1470 | "/tensorflow-1.15.2/python3.6/tensorflow_core/python/client/session.py:1750: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).\n",
1471 | " warnings.warn('An interactive session is already active. This can '\n"
1472 | ],
1473 | "name": "stderr"
1474 | }
1475 | ]
1476 | },
1477 | {
1478 | "cell_type": "markdown",
1479 | "metadata": {
1480 | "id": "mjewf0kzHheN"
1481 | },
1482 | "source": [
1483 | "### Calculate sensitivity and precison values for individual images"
1484 | ]
1485 | },
1486 | {
1487 | "cell_type": "code",
1488 | "metadata": {
1489 | "id": "UfPnyrHXHm4D"
1490 | },
1491 | "source": [
1492 | "from PIL import Image\n",
1493 | "import numpy as np\n",
1494 | "import os, sys\n",
1495 | "\n",
1496 | "training_size=80\n",
1497 | "gt_dir = \"drive/My Drive/data/output/annotations/\"\n",
1498 | "pred_dir = \"drive/My Drive/data/output/predicted/\"\n",
1499 | "sn = np.empty(training_size, dtype=float)\n",
1500 | "ppv = np.empty(training_size, dtype=float)\n",
1501 | "sp = np.empty(training_size, dtype=float)\n",
1502 | "image_paths = np.empty(training_size, dtype=object)\n",
1503 | "\n",
1504 | "dir = os.getcwd()\n",
1505 | "i=0\n",
1506 | "for image_path in os.listdir(os.path.join(dir,gt_dir)):\n",
1507 | "\timage_paths[i] = image_path\n",
1508 | "\tim_gt = Image.open(gt_dir+image_path)\n",
1509 | "\timg = os.path.splitext(image_path)[0] + \".jpg\"\n",
1510 | "\tim_pred = Image.open(pred_dir+img)\n",
1511 | "\tarr_gt = np.array(im_gt)\n",
1512 | "\tarr_pred = np.array(im_pred)\n",
1513 | "\tarr_pred = arr_pred > 0\n",
1514 | "\t#(unique, counts) = np.unique(arr_gt, return_counts=True)\n",
1515 | "\t#frequencies = np.asarray((unique, counts)).T\n",
1516 | "\t#print(\"arr_gt: \",frequencies)\n",
1517 | "\t#(unique, counts) = np.unique(arr_pred, return_counts=True)\n",
1518 | "\t#frequencies = np.asarray((unique, counts)).T\n",
1519 | "\t#print(\"arr_pred: \",frequencies)\n",
1520 | "\ttrue_p = np.sum(np.logical_and(arr_gt, arr_pred))\n",
1521 | "\tactual_p = np.sum(arr_gt)\n",
1522 | "\tpred_p = np.sum(arr_pred)\n",
1523 | "\t\n",
1524 | "\tfalse_p = pred_p - true_p\n",
1525 | "\tactual_n = 4288*2848 - actual_p\n",
1526 | "\ttrue_n = actual_n - false_p\n",
1527 | "\t#print (\"True pos: \", true_p)\n",
1528 | "\t#print (\"Actual pos: \", actual_p)\n",
1529 | "\t#print (\"Pred pos: \", pred_p)\n",
1530 | "\tif actual_p == 0:\n",
1531 | "\t\tsn[i] = 1\n",
1532 | "\telse:\n",
1533 | "\t\tsn[i] = float(true_p)/float(actual_p)\n",
1534 | "\tif pred_p == 0:\n",
1535 | "\t\tppv[i] = 1\n",
1536 | "\telse:\n",
1537 | "\t\tppv[i] = float(true_p)/float(pred_p)\n",
1538 | "\t#print (i)\n",
1539 | "\tif actual_n == 0:\n",
1540 | "\t\tsp[i] = 1\n",
1541 | "\telse:\n",
1542 | "\t\tsp[i] = float(true_n)/float(actual_n)\n",
1543 | "\ti+=1\n",
1544 | "\n",
1545 | "sn_csv = np.stack((image_paths,sn), axis=1)\n",
1546 | "ppv_csv = np.stack((image_paths,ppv), axis=1)\n",
1547 | "sp_csv = np.stack((image_paths,sp), axis=1)\n",
1548 | "\n",
1549 | "np.savetxt(\"drive/My Drive/data/sn.csv\", sn_csv, delimiter=\",\", fmt=\"%s\")\n",
1550 | "np.savetxt(\"drive/My Drive/data/ppv.csv\", ppv_csv, delimiter=\",\", fmt=\"%s\")\n",
1551 | "np.savetxt(\"drive/My Drive/data/sp.csv\", sp_csv, delimiter=\",\", fmt=\"%s\")"
1552 | ],
1553 | "execution_count": null,
1554 | "outputs": []
1555 | },
1556 | {
1557 | "cell_type": "markdown",
1558 | "metadata": {
1559 | "id": "8hwL8cLfH89I"
1560 | },
1561 | "source": [
1562 | "### compute average statistics"
1563 | ]
1564 | },
1565 | {
1566 | "cell_type": "code",
1567 | "metadata": {
1568 | "id": "GJaPdfF89P7x",
1569 | "colab": {
1570 | "base_uri": "https://localhost:8080/",
1571 | "height": 119
1572 | },
1573 | "outputId": "3cca101e-3813-4268-caea-a2efd1bdca76"
1574 | },
1575 | "source": [
1576 | "from PIL import Image\n",
1577 | "import numpy as np\n",
1578 | "import os, sys\n",
1579 | "import matplotlib\n",
1580 | "matplotlib.use('Agg')\n",
1581 | "import matplotlib.pyplot as plt\n",
1582 | "#np.set_printoptions(threshold=sys.maxsize)\n",
1583 | "\n",
1584 | "gt_dir = \"drive/My Drive/data/output/annotations/\"\n",
1585 | "pred_dir = \"drive/My Drive/data/output/predicted/\"\n",
1586 | "true_p=0\n",
1587 | "actual_p=0\n",
1588 | "pred_p=0\n",
1589 | "false_p=0\n",
1590 | "false_n=0\n",
1591 | "actual_n=0\n",
1592 | "true_n=0\n",
1593 | "pred_n=0\n",
1594 | "\n",
1595 | "dir = os.getcwd()\n",
1596 | "\n",
1597 | "for image_path in os.listdir(os.path.join(dir,gt_dir)):\n",
1598 | " im_gt = Image.open(gt_dir+image_path)\n",
1599 | " img = os.path.splitext(image_path)[0] + \".jpg\"\n",
1600 | " im_pred = Image.open(pred_dir+img)\n",
1601 | " arr_gt = np.array(im_gt)\n",
1602 | " arr_pred = np.array(im_pred)\n",
1603 | " arr_pred = arr_pred > 0\n",
1604 | " #(unique, counts) = np.unique(arr_pred, return_counts=True)\n",
1605 | " #frequencies = np.asarray((unique, counts)).T\n",
1606 | " #print(\"arr_pred: \",frequencies)\n",
1607 | "\n",
1608 | " tp = np.sum(np.logical_and(arr_gt, arr_pred))\n",
1609 | " #print(\"tp: \",tp)\n",
1610 | " ap = np.sum(arr_gt)\n",
1611 | " #print(\"ap: \",ap)\n",
1612 | " pp = np.sum(arr_pred)\n",
1613 | "\n",
1614 | " fp = pp - tp\n",
1615 | " an = 4288*2848 - ap\n",
1616 | " pn = 4288*2848 - pp\n",
1617 | " tn = an - fp\n",
1618 | " fn = pn - tn\n",
1619 | "\n",
1620 | " true_p += tp\n",
1621 | " actual_p += ap\n",
1622 | " pred_p += pp\n",
1623 | " pred_n += pn\n",
1624 | " false_p += fp\n",
1625 | " actual_n += an\n",
1626 | " true_n += tn\n",
1627 | " false_n +=fn\n",
1628 | "\n",
1629 | "\n",
1630 | "sn = float(true_p)/float(actual_p)\n",
1631 | "ppv = float(true_p)/float(pred_p)\n",
1632 | "sp = float(true_n)/float(actual_n)\n",
1633 | "npv = float(true_n)/float(pred_n)\n",
1634 | "acc = float(true_p + true_n)/float(actual_p + actual_n)\n",
1635 | "f1 = float(2*true_p)/float((2*true_p)+false_p+false_n)\n",
1636 | "\n",
1637 | "print (\"Sensitivity/Recall/True Positive Rate(TPR)(TP/P): \", sn)\n",
1638 | "print (\"Precision/Positive Predictive Value(PPV)(TP/TP+FP): \", ppv)\n",
1639 | "print (\"Specificity/Selectivity/True Negative Rate(TNR)(TN/N): \", sp)\n",
1640 | "print (\"Negative Predictive Value(NPV)(TN/TN+FN): \", npv)\n",
1641 | "print (\"Accuracy(TP+TN/P+N)\",acc)\n",
1642 | "print (\"F1 Score(2TP/2TP+FP+FN)\",f1)"
1643 | ],
1644 | "execution_count": null,
1645 | "outputs": [
1646 | {
1647 | "output_type": "stream",
1648 | "text": [
1649 | "Sensitivity/Recall/True Positive Rate(TPR)(TP/P): 0.9425759438650518\n",
1650 | "Precision/Positive Predictive Value(PPV)(TP/TP+FP): 0.7188802057557396\n",
1651 | "Specificity/Selectivity/True Negative Rate(TNR)(TN/N): 0.9961816109225247\n",
1652 | "Negative Predictive Value(NPV)(TN/TN+FN): 0.9994032052285645\n",
1653 | "Accuracy(TP+TN/P+N) 0.9956319893084176\n",
1654 | "F1 Score(2TP/2TP+FP+FN) 0.8156690606860414\n"
1655 | ],
1656 | "name": "stdout"
1657 | }
1658 | ]
1659 | },
1660 | {
1661 | "cell_type": "markdown",
1662 | "metadata": {
1663 | "id": "r9LjYv56IQ7Q"
1664 | },
1665 | "source": [
1666 | "### precision score"
1667 | ]
1668 | },
1669 | {
1670 | "cell_type": "code",
1671 | "metadata": {
1672 | "id": "Ott8N-YVISa9",
1673 | "colab": {
1674 | "base_uri": "https://localhost:8080/",
1675 | "height": 34
1676 | },
1677 | "outputId": "6ae66a0c-f6bc-439a-8aea-3faa125b7c53"
1678 | },
1679 | "source": [
1680 | "from PIL import Image\n",
1681 | "import numpy as np\n",
1682 | "import os, sys\n",
1683 | "from sklearn.metrics import average_precision_score\n",
1684 | "\n",
1685 | "training_size=80\n",
1686 | "gt_dir = \"drive/My Drive/data/output/annotations/\"\n",
1687 | "prob_dir = \"drive/My Drive/data/output/prob/\"\n",
1688 | "\n",
1689 | "dir = os.getcwd()\n",
1690 | "\n",
1691 | "i=0\n",
1692 | "sum_pav=0\n",
1693 | "for image_path in os.listdir(os.path.join(dir,gt_dir)):\n",
1694 | "\t# print image_path\n",
1695 | "\tim_gt = Image.open(gt_dir+image_path)\n",
1696 | "\timg = os.path.splitext(image_path)[0] + \".jpg\"\n",
1697 | "\tim_prob = Image.open(prob_dir+img)\n",
1698 | "\tarr_gt = (np.array(im_gt)).astype(bool)\n",
1699 | "\tarr_prob = (np.array(im_prob)).astype(float)/255\n",
1700 | "\t#(unique, counts) = np.unique(arr_gt, return_counts=True)\n",
1701 | "\t#frequencies = np.asarray((unique, counts)).T\n",
1702 | "\t#print(\"arr_prob: \",frequencies)\n",
1703 | "\tpav = average_precision_score(arr_gt.reshape((-1)),arr_prob.reshape((-1)))\n",
1704 | "\tsum_pav = sum_pav+pav\n",
1705 | "\ti = i+1\n",
1706 | "\n",
1707 | "mpav = sum_pav/i\n",
1708 | "print(mpav)"
1709 | ],
1710 | "execution_count": null,
1711 | "outputs": [
1712 | {
1713 | "output_type": "stream",
1714 | "text": [
1715 | "0.7908225819055167\n"
1716 | ],
1717 | "name": "stdout"
1718 | }
1719 | ]
1720 | }
1721 | ]
1722 | }
--------------------------------------------------------------------------------