II11ll commited on
Commit
ac8579b
·
0 Parent(s):
.gitattributes ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ *.onnx filter=lfs diff=lfs merge=lfs -text
2
+ *.jpg filter=lfs diff=lfs merge=lfs -text
3
+ *.ttc filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.pt
2
+ *.zip
3
+ *.7z
4
+ *.rar
5
+ *.ckpt
6
+ *.onnx
7
+ *.tar
8
+ *.jpg
9
+ *.ttc
10
+
11
+ wandb
12
+ data/backup
13
+ data/dataset
14
+ data/fonts
15
+ data/font_statics*
16
+ data/examples/annotations/*
17
+ __pycache__
18
+ .vscode
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This repository contains training scripts to train a text detector based on [manga-image-translator](https://github.com/zyddnys/manga-image-translator) which can extract bounding-boxes, text lines and segmentation of text from manga or comics to help further comics translation procedures such as text-removal, recognition, lettering, etc.
2
+
3
+ There are some awesome projects such as manga-image-translator, [manga_ocr](https://github.com/kha-white/manga_ocr), [SickZil-Machine](https://github.com/KUR-creative/SickZil-Machine) offer DL models to automize the remaining work, <s>we are working on a computer-aided comic/manga translation software which would (hopefully) put them together.</s> see [BallonsTranslator](https://github.com/dmMaze/BallonsTranslator)[WIP]
4
+
5
+ Download the text detection model from https://github.com/zyddnys/manga-image-translator/releases/tag/beta-0.2.1 or [Google Drive](https://drive.google.com/drive/folders/1cTsXP5NYTCjhPVxwScdhxqJleHuIOyXG?usp=sharing).
6
+
7
+ # Examples
8
+
9
+ ![AisazuNihaIrarenai-003](data/doc/AisazuNihaIrarenai-003.jpg)
10
+ <sup>(source: [manga109](http://www.manga109.org/en/), © Yoshi Masako)</sup>
11
+
12
+ ![AisazuNihaIrarenai-003-mask](data/doc/AisazuNihaIrarenai-003-mask.png)
13
+
14
+ ![AisazuNihaIrarenai-003-bboxes](data/doc/AisazuNihaIrarenai-003-bboxes.jpg)
15
+
16
+ # Training Details
17
+
18
+ Our current model can be summarized as below.
19
+
20
+ <img src='data/doc/model.jpg'>
21
+
22
+ All models were trained on around 13 thousand anime & comic style images, 1/3 from Manga109-s, 1/3 from [DCM](https://digitalcomicmuseum.com/), and 1/3 are synthetic data in a weak supervision manner due to the lack of available high-quality annotations.
23
+
24
+ We used text detection model of manga-image-translator to generate text lines annotations for manga, and [Manga-Text-Segmentation](https://github.com/juvian/Manga-Text-Segmentation) with some post-processing to generate masks for both manga and comics. Synthetic data were generated using around 4k text-free anime-girls pictures from https://t.me/SugarPic, text-rendering, Unet and DBNet training scripts can be found in this repo. Text block detector was trained using [yolov5 official repository](https://github.com/ultralytics/yolov5)
25
+
26
+ We would not (don't have the right) share training sets or fonts publicly, 2/3 of the training set is not so clean anyway, so the training is reproducible only if you have enough images and fonts, you can use the models this repo provided to generate labels for comics/manga, and the comic style text rendering script to generate synthetic data, please refer to [examples.ipynb](examples.ipynb) for more details.
27
+
28
+ ## Acknowledgements
29
+
30
+ * [https://github.com/zyddnys/manga-image-translator](https://github.com/zyddnys/manga-image-translator)
31
+ * [https://github.com/juvian/Manga-Text-Segmentation](https://github.com/juvian/Manga-Text-Segmentation)
32
+ * [https://github.com/ultralytics/yolov5](https://github.com/ultralytics/yolov5)
33
+ * [https://github.com/WenmuZhou/DBNet.pytorch](https://github.com/WenmuZhou/DBNet.pytorch)
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from inference import model2annotations,traverse_by_dict, init_model
2
+ import os
3
+ import shutil
4
+ import zipfile
5
+ import datetime
6
+ import gradio as gr
7
+ import PIL.Image
8
+
9
+ DESCRIPTION = "# [comic-text-detector](https://github.com/dmMaze/comic-text-detector)"
10
+ INPUT_DIR = "./input"
11
+ OUTPUT_DIR = "./output"
12
+ TEMP_DIR = "./temp"
13
+
14
+ os.makedirs(INPUT_DIR, exist_ok=True)
15
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
16
+ os.makedirs(TEMP_DIR, exist_ok=True)
17
+
18
+ def inference(model):
19
+ #model_path = f'{current_directory}/data/comictextdetector.pt'
20
+
21
+ img_dir = './input'
22
+ save_dir = './output'
23
+ model2annotations(img_dir, save_dir, save_json=True, model=model)
24
+ return traverse_by_dict(img_dir, save_dir)
25
+ current_directory = os.path.dirname(os.path.abspath(__file__))
26
+ model_path = './data/comictextdetector.pt.onnx'
27
+ model = init_model(model_path, device = 'cpu')
28
+
29
+ def process_image_and_generate_zip(image_file: PIL.Image.Image) -> str:
30
+ if image_file is None:
31
+ return None, "请上传一张图片!"
32
+
33
+ # 1. 清空 ./input 文件夹
34
+ print(f"清空 {INPUT_DIR} 文件夹...")
35
+ for filename in os.listdir(INPUT_DIR):
36
+ file_path = os.path.join(INPUT_DIR, filename)
37
+ try:
38
+ if os.path.isfile(file_path) or os.path.islink(file_path):
39
+ os.unlink(file_path)
40
+ elif os.path.isdir(file_path):
41
+ shutil.rmtree(file_path)
42
+ except Exception as e:
43
+ print(f"无法删除 {file_path}. 原因: {e}")
44
+ print(f"{INPUT_DIR} 文件夹清空完成。")
45
+
46
+ # 2. 清空 ./output 文件夹 (通常在每次运行时也清空输出)
47
+ print(f"清空 {OUTPUT_DIR} 文件夹...")
48
+ for filename in os.listdir(OUTPUT_DIR):
49
+ file_path = os.path.join(OUTPUT_DIR, filename)
50
+ try:
51
+ if os.path.isfile(file_path) or os.path.islink(file_path):
52
+ os.unlink(file_path)
53
+ elif os.path.isdir(file_path):
54
+ shutil.rmtree(file_path)
55
+ except Exception as e:
56
+ print(f"无法删除 {file_path}. 原因: {e}")
57
+ print(f"{OUTPUT_DIR} 文件夹清空完成。")
58
+
59
+
60
+ # 3. 保存输入图片到 ./input 文件夹
61
+ input_image_path = os.path.join(INPUT_DIR, os.path.basename(image_file.name))
62
+ shutil.copyfile(image_file.name, input_image_path)
63
+ print(f"输入图片已保存到: {input_image_path}")
64
+
65
+ # 4. 调用模型
66
+ print("调用模型...")
67
+ inference(model)
68
+
69
+ # 5. 将 ./output 文件夹打包为zip文件
70
+ print("正在打包输出文件...")
71
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
72
+ zip_filename = f"output_results_{timestamp}.zip"
73
+ zip_filepath = os.path.join(TEMP_DIR, zip_filename)
74
+
75
+ with zipfile.ZipFile(zip_filepath, 'w', zipfile.ZIP_DEFLATED) as zipf:
76
+ for root, _, files in os.walk(OUTPUT_DIR):
77
+ for file in files:
78
+ file_path = os.path.join(root, file)
79
+ # 计算在zip文件中的相对路径
80
+ arcname = os.path.relpath(file_path, OUTPUT_DIR)
81
+ zipf.write(file_path, arcname)
82
+ print(f"输出文件已打包到: {zip_filepath}")
83
+
84
+ return zip_filepath, "处理完成!请下载结果。"
85
+
86
+ with gr.Blocks() as demo:
87
+ gr.Markdown("# 图像处理与结果下载")
88
+ gr.Markdown("上传一张图片,模型将对其进行处理,并将结果打包为ZIP文件供下载。")
89
+
90
+ with gr.Row():
91
+ image_input = gr.Image(type="filepath", label="上传图片")
92
+ # 直接显示处理后的图片,可选
93
+ # processed_image_output = gr.Image(label="处理后的图片")
94
+
95
+ run_button = gr.Button("运行模型并打包")
96
+ zip_output = gr.File(label="下载处理结果ZIP文件")
97
+ message_output = gr.Textbox(label="状态信息", interactive=False)
98
+
99
+ run_button.click(
100
+ fn=process_image_and_generate_zip,
101
+ inputs=image_input,
102
+ outputs=[zip_output, message_output] # 如果你想显示处理后的图片,这里可以添加 processed_image_output
103
+ )
104
+
105
+ # 启动 Gradio 应用
106
+ if __name__ == "__main__":
107
+ demo.launch()
basemodel.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from utils.general import CUDA, DEVICE
3
+ from models.yolov5.yolo import Model
4
+ import torch
5
+ import cv2
6
+ import numpy as np
7
+ from models.yolov5.yolo import load_yolov5_ckpt
8
+ from utils.yolov5_utils import fuse_conv_and_bn
9
+ import glob
10
+ import torch.nn as nn
11
+ from utils.weight_init import init_weights
12
+ from models.yolov5.common import C3, Conv
13
+ from torchsummary import summary
14
+ import torch.nn.functional as F
15
+ import copy
16
+
17
+ TEXTDET_MASK = 0
18
+ TEXTDET_DET = 1
19
+ TEXTDET_INFERENCE = 2
20
+
21
+ class double_conv_up_c3(nn.Module):
22
+ def __init__(self, in_ch, mid_ch, out_ch, act=True):
23
+ super(double_conv_up_c3, self).__init__()
24
+ self.conv = nn.Sequential(
25
+ C3(in_ch+mid_ch, mid_ch, act=act),
26
+ nn.ConvTranspose2d(mid_ch, out_ch, kernel_size=4, stride = 2, padding=1, bias=False),
27
+ nn.BatchNorm2d(out_ch),
28
+ nn.ReLU(inplace=True),
29
+ )
30
+
31
+ def forward(self, x):
32
+ return self.conv(x)
33
+
34
+ class double_conv_c3(nn.Module):
35
+ def __init__(self, in_ch, out_ch, stride=1, act=True):
36
+ super(double_conv_c3, self).__init__()
37
+ if stride > 1 :
38
+ self.down = nn.AvgPool2d(2,stride=2) if stride > 1 else None
39
+ self.conv = C3(in_ch, out_ch, act=act)
40
+
41
+ def forward(self, x):
42
+ if self.down is not None :
43
+ x = self.down(x)
44
+ x = self.conv(x)
45
+ return x
46
+
47
+ class UnetHead(nn.Module):
48
+ def __init__(self, act=True) -> None:
49
+
50
+ super(UnetHead, self).__init__()
51
+ self.down_conv1 = double_conv_c3(512, 512, 2, act=act)
52
+ self.upconv0 = double_conv_up_c3(0, 512, 256, act=act)
53
+ self.upconv2 = double_conv_up_c3(256, 512, 256, act=act)
54
+ self.upconv3 = double_conv_up_c3(0, 512, 256, act=act)
55
+ self.upconv4 = double_conv_up_c3(128, 256, 128, act=act)
56
+ self.upconv5 = double_conv_up_c3(64, 128, 64, act=act)
57
+ self.upconv6 = nn.Sequential(
58
+ nn.ConvTranspose2d(64, 1, kernel_size=4, stride = 2, padding=1, bias=False),
59
+ nn.Sigmoid()
60
+ )
61
+
62
+ def forward(self, f160, f80, f40, f20, f3, forward_mode=TEXTDET_MASK):
63
+ # input: 640@3
64
+ d10 = self.down_conv1(f3) # 512@10
65
+ u20 = self.upconv0(d10) # 256@10
66
+ u40 = self.upconv2(torch.cat([f20, u20], dim = 1)) # 256@40
67
+
68
+ if forward_mode == TEXTDET_DET:
69
+ return f80, f40, u40
70
+ else:
71
+ u80 = self.upconv3(torch.cat([f40, u40], dim = 1)) # 256@80
72
+ u160 = self.upconv4(torch.cat([f80, u80], dim = 1)) # 128@160
73
+ u320 = self.upconv5(torch.cat([f160, u160], dim = 1)) # 64@320
74
+ mask = self.upconv6(u320)
75
+ if forward_mode == TEXTDET_MASK:
76
+ return mask
77
+ else:
78
+ return mask, [f80, f40, u40]
79
+
80
+ def init_weight(self, init_func):
81
+ self.apply(init_func)
82
+
83
+ class DBHead(nn.Module):
84
+ def __init__(self, in_channels, k = 50, shrink_with_sigmoid=True, act=True):
85
+ super().__init__()
86
+ self.k = k
87
+ self.shrink_with_sigmoid = shrink_with_sigmoid
88
+ self.upconv3 = double_conv_up_c3(0, 512, 256, act=act)
89
+ self.upconv4 = double_conv_up_c3(128, 256, 128, act=act)
90
+ self.conv = nn.Sequential(
91
+ nn.Conv2d(128, in_channels, 1),
92
+ nn.BatchNorm2d(in_channels),
93
+ nn.ReLU(inplace=True)
94
+ )
95
+ self.binarize = nn.Sequential(
96
+ nn.Conv2d(in_channels, in_channels // 4, 3, padding=1),
97
+ nn.BatchNorm2d(in_channels // 4),
98
+ nn.ReLU(inplace=True),
99
+ nn.ConvTranspose2d(in_channels // 4, in_channels // 4, 2, 2),
100
+ nn.BatchNorm2d(in_channels // 4),
101
+ nn.ReLU(inplace=True),
102
+ nn.ConvTranspose2d(in_channels // 4, 1, 2, 2)
103
+ )
104
+ self.thresh = self._init_thresh(in_channels)
105
+
106
+ def forward(self, f80, f40, u40, shrink_with_sigmoid=True, step_eval=False):
107
+ shrink_with_sigmoid = self.shrink_with_sigmoid
108
+ u80 = self.upconv3(torch.cat([f40, u40], dim = 1)) # 256@80
109
+ x = self.upconv4(torch.cat([f80, u80], dim = 1)) # 128@160
110
+ x = self.conv(x)
111
+ threshold_maps = self.thresh(x)
112
+ x = self.binarize(x)
113
+ shrink_maps = torch.sigmoid(x)
114
+
115
+ if self.training:
116
+ binary_maps = self.step_function(shrink_maps, threshold_maps)
117
+ if shrink_with_sigmoid:
118
+ return torch.cat((shrink_maps, threshold_maps, binary_maps), dim=1)
119
+ else:
120
+ return torch.cat((shrink_maps, threshold_maps, binary_maps, x), dim=1)
121
+ else:
122
+ if step_eval:
123
+ return self.step_function(shrink_maps, threshold_maps)
124
+ else:
125
+ return torch.cat((shrink_maps, threshold_maps), dim=1)
126
+
127
+ def init_weight(self, init_func):
128
+ self.apply(init_func)
129
+
130
+ def _init_thresh(self, inner_channels, serial=False, smooth=False, bias=False):
131
+ in_channels = inner_channels
132
+ if serial:
133
+ in_channels += 1
134
+ self.thresh = nn.Sequential(
135
+ nn.Conv2d(in_channels, inner_channels // 4, 3, padding=1, bias=bias),
136
+ nn.BatchNorm2d(inner_channels // 4),
137
+ nn.ReLU(inplace=True),
138
+ self._init_upsample(inner_channels // 4, inner_channels // 4, smooth=smooth, bias=bias),
139
+ nn.BatchNorm2d(inner_channels // 4),
140
+ nn.ReLU(inplace=True),
141
+ self._init_upsample(inner_channels // 4, 1, smooth=smooth, bias=bias),
142
+ nn.Sigmoid())
143
+ return self.thresh
144
+
145
+ def _init_upsample(self, in_channels, out_channels, smooth=False, bias=False):
146
+ if smooth:
147
+ inter_out_channels = out_channels
148
+ if out_channels == 1:
149
+ inter_out_channels = in_channels
150
+ module_list = [
151
+ nn.Upsample(scale_factor=2, mode='nearest'),
152
+ nn.Conv2d(in_channels, inter_out_channels, 3, 1, 1, bias=bias)]
153
+ if out_channels == 1:
154
+ module_list.append(nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=1, bias=True))
155
+ return nn.Sequential(module_list)
156
+ else:
157
+ return nn.ConvTranspose2d(in_channels, out_channels, 2, 2)
158
+
159
+ def step_function(self, x, y):
160
+ return torch.reciprocal(1 + torch.exp(-self.k * (x - y)))
161
+
162
+ class TextDetector(nn.Module):
163
+ def __init__(self, weights, map_location='cpu', forward_mode=TEXTDET_MASK, act=True):
164
+ super(TextDetector, self).__init__()
165
+
166
+ yolov5s_backbone = load_yolov5_ckpt(weights=weights, map_location=map_location)
167
+ yolov5s_backbone.eval()
168
+ out_indices = [1, 3, 5, 7, 9]
169
+ yolov5s_backbone.out_indices = out_indices
170
+ yolov5s_backbone.model = yolov5s_backbone.model[:max(out_indices)+1]
171
+ self.act = act
172
+ self.seg_net = UnetHead(act=act)
173
+ self.backbone = yolov5s_backbone
174
+ self.dbnet = None
175
+ self.forward_mode = forward_mode
176
+
177
+ def train_mask(self):
178
+ self.forward_mode = TEXTDET_MASK
179
+ self.backbone.eval()
180
+ self.seg_net.train()
181
+
182
+ def initialize_db(self, unet_weights):
183
+ self.dbnet = DBHead(64, act=self.act)
184
+ self.seg_net.load_state_dict(torch.load(unet_weights, map_location='cpu')['weights'])
185
+ self.dbnet.init_weight(init_weights)
186
+ self.dbnet.upconv3 = copy.deepcopy(self.seg_net.upconv3)
187
+ self.dbnet.upconv4 = copy.deepcopy(self.seg_net.upconv4)
188
+ del self.seg_net.upconv3
189
+ del self.seg_net.upconv4
190
+ del self.seg_net.upconv5
191
+ del self.seg_net.upconv6
192
+ # del self.seg_net.conv_mask
193
+
194
+ def train_db(self):
195
+ self.forward_mode = TEXTDET_DET
196
+ self.backbone.eval()
197
+ self.seg_net.eval()
198
+ self.dbnet.train()
199
+
200
+ def forward(self, x):
201
+ forward_mode = self.forward_mode
202
+ with torch.no_grad():
203
+ outs = self.backbone(x)
204
+ if forward_mode == TEXTDET_MASK:
205
+ return self.seg_net(*outs, forward_mode=forward_mode)
206
+ elif forward_mode == TEXTDET_DET:
207
+ with torch.no_grad():
208
+ outs = self.seg_net(*outs, forward_mode=forward_mode)
209
+ return self.dbnet(*outs)
210
+
211
+ def get_base_det_models(model_path, device='cpu', half=False, act='leaky'):
212
+ textdetector_dict = torch.load(model_path, map_location=device)
213
+ blk_det = load_yolov5_ckpt(textdetector_dict['blk_det'], map_location=device)
214
+ text_seg = UnetHead(act=act)
215
+ text_seg.load_state_dict(textdetector_dict['text_seg'])
216
+ text_det = DBHead(64, act=act)
217
+ text_det.load_state_dict(textdetector_dict['text_det'])
218
+ if half:
219
+ return blk_det.eval().half(), text_seg.eval().half(), text_det.eval().half()
220
+ return blk_det.eval().to(device), text_seg.eval().to(device), text_det.eval().to(device)
221
+
222
+ class TextDetBase(nn.Module):
223
+ def __init__(self, model_path, device='cpu', half=False, fuse=False, act='leaky'):
224
+ super(TextDetBase, self).__init__()
225
+ self.blk_det, self.text_seg, self.text_det = get_base_det_models(model_path, device, half, act=act)
226
+ if fuse:
227
+ self.fuse()
228
+
229
+ def fuse(self):
230
+ def _fuse(model):
231
+ for m in model.modules():
232
+ if isinstance(m, (Conv)) and hasattr(m, 'bn'):
233
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
234
+ delattr(m, 'bn') # remove batchnorm
235
+ m.forward = m.forward_fuse # update forward
236
+ return model
237
+ self.text_seg = _fuse(self.text_seg)
238
+ self.text_det = _fuse(self.text_det)
239
+
240
+ def forward(self, features):
241
+ blks, features = self.blk_det(features, detect=True)
242
+ mask, features = self.text_seg(*features, forward_mode=TEXTDET_INFERENCE)
243
+ lines = self.text_det(*features, step_eval=False)
244
+ return blks[0], mask, lines
245
+
246
+ class TextDetBaseDNN:
247
+ def __init__(self, input_size, model_path):
248
+ self.input_size = input_size
249
+ self.model = cv2.dnn.readNetFromONNX(model_path)
250
+ self.uoln = self.model.getUnconnectedOutLayersNames()
251
+
252
+ def __call__(self, im_in):
253
+ blob = cv2.dnn.blobFromImage(im_in, scalefactor=1 / 255.0, size=(self.input_size, self.input_size))
254
+ self.model.setInput(blob)
255
+ blks, mask, lines_map = self.model.forward(self.uoln)
256
+ return blks, mask, lines_map
257
+
258
+ if __name__ == '__main__':
259
+ device = 'cuda'
260
+ weights = r'data/yolov5sblk.ckpt'
261
+
262
+ # yolov5s_backbone = load_yolov5_ckpt(weights=weights, map_location='cpu')
263
+
264
+ model = TextDetector(weights, map_location=DEVICE)
265
+ model.to(DEVICE)
266
+ model.train_mask()
267
+ summary(model, (3, 640, 640), device=DEVICE)
268
+
269
+ # model.initialize_db(unet_weights='data/unet_head.pt')
270
+ # model.train_db()
271
+ # summary(model, (3, 640, 640), device=DEVICE)
272
+
273
+
data/doc/AisazuNihaIrarenai-003-mask.png ADDED
data/train_db_hyp.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data:
2
+ train_img_dir: 'dataset/train'
3
+ train_mask_dir: ''
4
+ val_img_dir: 'dataset/val'
5
+ val_mask_dir: ''
6
+ imgsz: 1024
7
+ augment: True
8
+ num_workers: 8
9
+ cache: True
10
+ aug_param:
11
+ hsv: 0.3
12
+ mini_mosaic: 0.7
13
+ flip_lr: 0.5
14
+ neg: 0.3
15
+ size_range: [0.85, 1.1]
16
+ rotate: 0.33
17
+ rotate_range: [-70, 70]
18
+ save_dir: 'results'
19
+
20
+ train:
21
+ epochs: 160
22
+ linear_lr: False
23
+ optimizer: 'adam'
24
+ batch_size: 4
25
+ lr0: 0.01
26
+ lrf: 0.002
27
+ warm_up: True
28
+ momentum: 0.937
29
+ weight_decay: 0.00002
30
+ warmup_epochs: 3.0 # warmup epochs (fractions ok)
31
+ warmup_momentum: 0.8 # warmup initial momentum
32
+ warmup_bias_lr: 0.1 # warmup initial bias lr
33
+ eval_interval: 1
34
+ loss: 'bce'
35
+ accumulation_steps: 4
36
+
37
+ model:
38
+ weights: 'data/yolov5sblk.ckpt'
39
+ unet_weights: 'data/unet_best.ckpt'
40
+ db_weights: ''
41
+ act: 'leaky'
42
+
43
+ logger:
44
+ type: 'wandb'
45
+ run_id: ''
46
+ project: 'TextDetectDB'
47
+
48
+ resume:
49
+ resume_training: False
50
+ ckpt: ''
51
+
data/train_hyp.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data:
2
+ train_img_dir: 'dataset/train'
3
+ train_mask_dir: ''
4
+ val_img_dir: 'dataset/val'
5
+ val_mask_dir: ''
6
+ imgsz: 1024
7
+ augment: True
8
+ cache: True
9
+ aug_param:
10
+ hsv: 0.3
11
+ mini_mosaic: 0.5
12
+ flip_lr: 0.5
13
+ neg: 0.3
14
+ size_range: [0.7, 1]
15
+
16
+ train:
17
+ epochs: 15
18
+ linear_lr: False
19
+ optimizer: 'adam'
20
+ batch_size: 4
21
+ lr0: 0.01
22
+ lrf: 0.005
23
+ momentum: 0.937
24
+ weight_decay: 0.0005
25
+ warmup_epochs: 3.0 # warmup epochs (fractions ok)
26
+ warmup_momentum: 0.8 # warmup initial momentum
27
+ warmup_bias_lr: 0.1 # warmup initial bias lr
28
+ eval_interval: 1
29
+ loss: 'dice'
30
+ accumulation_steps: 1
31
+
32
+ model:
33
+ weights: 'data/yolov5sblk.ckpt'
34
+ act: 'leaky'
35
+
36
+ logger:
37
+ type: 'wandb'
38
+ run_id: ''
39
+ project: ''
40
+
41
+
42
+ resume:
43
+ resume_training: False
44
+ ckpt: ''
45
+
data/training_hyp.yaml ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data:
2
+ aug_param:
3
+ flip_lr: 0.5
4
+ hsv: 0.3
5
+ mini_mosaic: 0.5
6
+ neg: 0.3
7
+ size_range:
8
+ - 0.85
9
+ - 1.1
10
+ augment: true
11
+ cache: false
12
+ imgsz: 1024
13
+ train_img_dir:
14
+ - ../datasets/codat_manga_v3/images/train
15
+ - ../datasets/ComicErased/processed
16
+ train_mask_dir: ../datasets/ComicSegV2
17
+ val_img_dir:
18
+ - ../datasets/codat_manga_v3/images/val
19
+ val_mask_dir: ../datasets/ComicSegV2
20
+ logger:
21
+ project: ''
22
+ run_id: ''
23
+ type: wandb
24
+ model:
25
+ act: leaky
26
+ weights: data/yolov5sblk.ckpt
27
+ resume:
28
+ ckpt: ''
29
+ resume_training: false
30
+ train:
31
+ accumulation_steps: 4
32
+ batch_size: 4
33
+ epochs: 120
34
+ eval_interval: 1
35
+ linear_lr: false
36
+ loss: dice
37
+ lr0: 0.004
38
+ lrf: 0.005
39
+ momentum: 0.937
40
+ optimizer: adam
41
+ warmup_bias_lr: 0.1
42
+ warmup_epochs: 3.0
43
+ warmup_momentum: 0.8
44
+ weight_decay: 2.0e-05
db_dataset.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import yaml
3
+ import torch
4
+ import glob
5
+ import os
6
+ import os.path as osp
7
+ import random
8
+ from itertools import repeat
9
+ from multiprocessing.pool import Pool, ThreadPool
10
+ from pathlib import Path
11
+ from threading import Thread
12
+ import cv2
13
+ from torch.utils.data import Dataset
14
+ from tqdm import tqdm
15
+ from pathlib import Path
16
+ from torchvision import transforms
17
+ from torch.utils.data import DataLoader, Dataset, dataloader
18
+ from utils.general import LOGGER, Loggers, CUDA, DEVICE
19
+ from utils.db_utils import MakeBorderMap, MakeShrinkMap
20
+ from seg_dataset import augment_hsv
21
+ from utils.imgproc_utils import rotate_polygons, letterbox, resize_keepasp
22
+ from PIL import Image
23
+
24
+ WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1)) # DPP
25
+ NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of multiprocessing threads
26
+ IMG_EXT = ['.bmp', '.jpg', '.png', '.jpeg']
27
+
28
+ def db_val_collate_fn(batchs):
29
+ cat_list = ['text_polys', 'ignore_tags']
30
+ ret_batchs = {}
31
+ for key in batchs[0].keys():
32
+ ret_batchs[key] = []
33
+ for batch in batchs:
34
+ if isinstance(batch[key], np.ndarray):
35
+ batch[key] = torch.from_numpy(batch[key])
36
+ ret_batchs[key].append(batch[key])
37
+ if key in cat_list:
38
+ pass
39
+ else:
40
+ ret_batchs[key] = torch.stack(ret_batchs[key], 0)
41
+ return ret_batchs
42
+
43
+ class LoadImageAndAnnotations(Dataset):
44
+ def __init__(self, img_dir, ann_dir=None, img_size=640, augment=False, aug_param=None, cache=False, stride=128, cache_ann_only=True, with_ann=False):
45
+ if isinstance(img_dir, str):
46
+ self.img_dir = [img_dir]
47
+ elif isinstance(img_dir, list):
48
+ self.img_dir = img_dir
49
+ else:
50
+ raise Exception('unknown img_dir format')
51
+
52
+ if ann_dir is None or ann_dir == '':
53
+ self.ann_dir = self.img_dir
54
+ else:
55
+ if isinstance(ann_dir, str):
56
+ self.ann_dir = [ann_dir]
57
+ elif isinstance(ann_dir, list):
58
+ self.ann_dir = ann_dir
59
+ self.with_ann = with_ann
60
+ self.make_border_map = MakeBorderMap(shrink_ratio=0.4)
61
+ self.make_shrink_map = MakeShrinkMap(shrink_ratio=0.4)
62
+ self.img_ann_list = []
63
+ self.img_size = (img_size, img_size)
64
+ self.stride = stride
65
+ self._augment = augment
66
+ if self._augment:
67
+ self._mini_mosaic = aug_param['mini_mosaic']
68
+ self._augment_hsv = aug_param['hsv']
69
+ self._flip_lr = aug_param['flip_lr']
70
+ self._neg = aug_param['neg']
71
+ self._rotate = aug_param['rotate']
72
+ self.rotate_range = aug_param['rotate_range']
73
+ size_range = aug_param['size_range']
74
+ if isinstance(size_range, list) and size_range[0] > 0:
75
+ min_size = round(img_size * size_range[0] / stride ) * stride
76
+ max_size = round(img_size * size_range[1] / stride ) * stride
77
+ self.valid_size = np.arange(min_size, max_size+1, stride)
78
+ self.multi_size = True
79
+ else:
80
+ self.valid_size = None
81
+ self.multi_size = False
82
+ for img_dir in self.img_dir:
83
+ for filep in glob.glob(osp.join(img_dir, "*")):
84
+ filename = osp.basename(filep)
85
+ file_suffix = Path(filename).suffix
86
+ if file_suffix not in IMG_EXT:
87
+ continue
88
+ annname = 'line-' + filename.replace(file_suffix, '.txt')
89
+ for ann_dir in self.ann_dir:
90
+ annp = osp.join(ann_dir, annname)
91
+ if osp.exists(annp):
92
+ self.img_ann_list.append((filep, annp))
93
+ self._img_transform = transforms.Compose([transforms.ToTensor()])
94
+
95
+ n = len(self.img_ann_list)
96
+ self.imgs, self.anns = [None] * n, [None] * n
97
+ gb = 0
98
+ if cache:
99
+ results = ThreadPool(NUM_THREADS).imap(lambda x: load_image_annotations(*x, max_size=img_size), zip(repeat(self), range(n)))
100
+ pbar = tqdm(enumerate(results), total=n)
101
+ for i, x in pbar:
102
+ im, self.anns[i] = x # im, hw_orig, hw_resized = load_image_ann(self, i)
103
+ if not cache_ann_only:
104
+ self.imgs[i] = im
105
+ gb += self.imgs[i].nbytes
106
+ gb += self.anns[i].nbytes
107
+ if gb / 1E9 > 7:
108
+ break
109
+ pbar.desc = f'Caching images ({gb / 1E9:.1f}GB )'
110
+ pbar.close()
111
+
112
+ def initialize(self):
113
+ if self.augment:
114
+ if self.multi_size:
115
+ self.img_size = random.choice(self.valid_size)
116
+
117
+ def transform(self, img):
118
+ cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
119
+ img = img.astype(np.float32) / 255
120
+ img = self._img_transform(img)
121
+ return img
122
+
123
+ def mini_mosaic(self, img, ann):
124
+ im_h, im_w = img.shape[:2]
125
+ idx = random.randint(0, len(self)-1)
126
+ img2, ann2 = load_image_annotations(self, idx, self.img_size)
127
+ img2_h, img2_w = img2.shape[:2]
128
+
129
+ if img2_h > img2_w:
130
+ imm_h = max(im_h, img2_h)
131
+ imm_w = im_w + img2_w
132
+ im_tmp = np.zeros((imm_h, imm_w, 3), np.uint8)
133
+ im_tmp[:im_h, :im_w] = img
134
+ im_tmp[:img2_h, im_w:] = img2
135
+ ann[:, :, 0] = ann[:, :, 0] * im_w / imm_w
136
+ ann[:, :, 1] = ann[:, :, 1] * im_h / imm_h
137
+ if ann2.shape[1] > 0:
138
+ ann2[:, :, 0] = ann2[:, :, 0] * img2_w / imm_w + im_w / imm_w
139
+ ann2[:, :, 1] = ann2[:, :, 1] * img2_h / imm_h
140
+ ann = np.concatenate((ann, ann2))
141
+ img = im_tmp
142
+ return img, ann
143
+
144
+ else:
145
+ return img, ann
146
+
147
+ def augment(self, img, ann):
148
+ im_h, im_w = img.shape[0], img.shape[1]
149
+ if im_h > im_w and random.random() < self._mini_mosaic:
150
+ # imp2, annp2 = random.choice(self.img_ann_list)
151
+ img, ann = self.mini_mosaic(img, ann)
152
+
153
+ if random.random() < self._augment_hsv:
154
+ augment_hsv(img)
155
+ if random.random() < self._flip_lr:
156
+ cv2.flip(img, 1, img)
157
+ ann[:, :, 0] = 1 - ann[:, :, 0]
158
+ if random.random() < self._neg:
159
+ img = 255 - img
160
+ if random.random() < self._rotate:
161
+ degrees = random.uniform(self.rotate_range[0], self.rotate_range[1])
162
+ if abs(degrees) > 15:
163
+ img = Image.fromarray(img)
164
+ center = (img.width/2, img.height/2)
165
+ ann[:, :, 0] *= img.width
166
+ ann[:, :, 1] *= img.height
167
+ ann = ann.reshape(len(ann), -1)
168
+ img = img.rotate(degrees, resample=Image.BILINEAR, expand=1)
169
+ new_center = (img.width/2, img.height/2)
170
+ ann = rotate_polygons(center, ann, degrees, new_center, to_int=False)
171
+ ann = ann.reshape(len(ann), -1, 2)
172
+ ann[:, :, 0] /= img.width
173
+ ann[:, :, 1] /= img.height
174
+ img = np.asarray(img)
175
+ return img, ann
176
+
177
+ def inverse_transform(self, img: torch.Tensor, scale=255, to_uint8=True):
178
+ img = img.permute(1, 2, 0)
179
+ img = img * scale
180
+ img = img.cpu().numpy()
181
+ if to_uint8:
182
+ img = np.ascontiguousarray(img, np.uint8)
183
+ return img
184
+
185
+ def __len__(self):
186
+ return len(self.img_ann_list)
187
+
188
+ def __getitem__(self, idx):
189
+ img, ann = load_image_annotations(self, idx, self.img_size)
190
+ in_h, in_w = img.shape[:2]
191
+
192
+ if self._augment:
193
+ img, ann = self.augment(img, ann)
194
+ ignore_tags = [False] * ann.shape[0]
195
+
196
+ img, ratio, (dw, dh) = letterbox(img, new_shape=self.img_size, auto=False)
197
+ im_h, im_w = img.shape[:2]
198
+ if ann is not None:
199
+ ann[:, :, 0] *= (im_w - dw)
200
+ ann[:, :, 1] *= (im_h - dh)
201
+ ann = ann.astype(np.int64)
202
+ data_dict = {'imgs': img, 'text_polys': ann, 'ignore_tags': ignore_tags}
203
+
204
+ shrink_map = self.make_shrink_map(data_dict)
205
+ thresh_map = self.make_border_map(data_dict)
206
+ tp = thresh_map.pop('text_polys')
207
+ it = thresh_map.pop('ignore_tags')
208
+ if self.with_ann:
209
+ thresh_map['text_polys'] = torch.from_numpy(np.array(tp))
210
+ thresh_map['ignore_tags'] = torch.from_numpy(np.array(it))
211
+
212
+ thresh_map['imgs'] = self.transform(thresh_map['imgs'])
213
+ return thresh_map
214
+
215
+
216
+ def load_image_annotations(self, i, max_size=None, ann_abs2rel=True):
217
+ # loads 1 image from dataset index 'i', returns im, original hw, resized hw
218
+ img, ann = self.imgs[i], self.anns[i]
219
+ imp, ann_path = self.img_ann_list[i]
220
+ if img is None:
221
+ img = cv2.imread(imp)
222
+ im_h, im_w = img.shape[:2]
223
+ if ann is None:
224
+ ann = np.loadtxt(ann_path)
225
+ if len(ann.shape) == 1:
226
+ ann = np.array([ann])
227
+ if ann_abs2rel:
228
+ ann[:, ::2] /= im_w
229
+ ann[:, 1::2] /= im_h
230
+ ann = ann.reshape(len(ann), -1, 2)
231
+ else:
232
+ ann = np.copy(ann)
233
+ if max_size is not None:
234
+ if isinstance(max_size, tuple):
235
+ max_size = max_size[0]
236
+ img = resize_keepasp(img, max_size)
237
+ return img, ann
238
+
239
+ def create_dataloader(img_dir, ann_dir, imgsz, batch_size, augment=False, aug_param=None, cache=False, workers=8, shuffle=False, with_ann=False):
240
+ dataset = LoadImageAndAnnotations(img_dir, ann_dir, imgsz, augment, aug_param, cache, with_ann=with_ann)
241
+ batch_size = min(batch_size, len(dataset))
242
+ nw = min([os.cpu_count() // WORLD_SIZE, batch_size if batch_size > 1 else 0, workers]) # number of workers
243
+ if with_ann:
244
+ collate_fn = db_val_collate_fn
245
+ else:
246
+ collate_fn = None
247
+ loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, pin_memory=True, num_workers=nw, collate_fn=collate_fn)
248
+ return dataset, loader
249
+
250
+ if __name__ == '__main__':
251
+ img_dir = 'data/dataset/db_sub'
252
+ hyp_p = r'data/train_db_hyp.yaml'
253
+ with open(hyp_p, 'r', encoding='utf8') as f:
254
+ hyp = yaml.safe_load(f.read())
255
+ hyp['data']['train_img_dir'] = img_dir
256
+ hyp['data']['cache'] = False
257
+ hyp_train, hyp_data, hyp_model, hyp_logger, hyp_resume = hyp['train'], hyp['data'], hyp['model'], hyp['logger'], hyp['resume']
258
+ batch_size = hyp_train['batch_size']
259
+ batch_size = 1
260
+ num_workers = 0
261
+ train_img_dir, train_mask_dir, imgsz, augment, aug_param = hyp_data['train_img_dir'], hyp_data['train_mask_dir'], hyp_data['imgsz'], hyp_data['augment'], hyp_data['aug_param']
262
+
263
+ train_dataset, train_loader = create_dataloader(train_img_dir, train_mask_dir, imgsz, batch_size, augment, aug_param, shuffle=True, workers=num_workers, cache=hyp_data['cache'], with_ann=True)
264
+
265
+ for ii in range(10):
266
+
267
+ for batchs in train_loader:
268
+ train_dataset.initialize()
269
+ print(train_dataset.img_size)
270
+ img = batchs['imgs'][0]
271
+
272
+ img = train_dataset.inverse_transform(img)
273
+ threshold_map = batchs['threshold_map'][0]
274
+ threshold_mask = batchs['threshold_mask'][0]
275
+ shrink_map = batchs['shrink_map'][0]
276
+ shrink_mask = batchs['shrink_mask'][0]
277
+ polys = batchs['text_polys'][0].numpy().astype(np.int32)
278
+ for p in polys:
279
+ cv2.polylines(img,[p],True,(255, 0, 0), thickness=2)
280
+ cv2.imshow('imgs', img)
281
+ cv2.imshow('threshold_map', threshold_map.numpy())
282
+ cv2.imshow('threshold_mask', threshold_mask.numpy())
283
+ cv2.imshow('shrink_map', shrink_map.numpy())
284
+ cv2.imshow('shrink_mask', shrink_mask.numpy())
285
+ cv2.waitKey(0)
examples.ipynb ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "## Annotate Comics/Manga\n",
8
+ "Download comictextdetector.pt and put it into data directory.\n",
9
+ "Run next block to generate following annotations for data\\examples\\AisazuNihaIrarenai-003.jpg:\n",
10
+ "- AisazuNihaIrarenai-003.txt: yolo format bounding boxes of english&japanese text block bounding boxes. 0 is eng.\n",
11
+ "- mask-AisazuNihaIrarenai-003.png\n",
12
+ "- line-AisazuNihaIrarenai-003.txt: icdar format bboxes of text lines."
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "execution_count": 1,
18
+ "metadata": {},
19
+ "outputs": [
20
+ {
21
+ "name": "stderr",
22
+ "output_type": "stream",
23
+ "text": [
24
+ "100%|██████████| 1/1 [00:04<00:00, 4.78s/it]\n"
25
+ ]
26
+ }
27
+ ],
28
+ "source": [
29
+ "from inference import model2annotations\n",
30
+ "\n",
31
+ "img_dir = r'data/examples'\n",
32
+ "model_path = r'data/comictextdetector.pt'\n",
33
+ "img_dir = r'data/examples' # can be dir list\n",
34
+ "save_dir = r'data/examples/annotations'\n",
35
+ "model2annotations(model_path, img_dir, save_dir, save_json=False)"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "markdown",
40
+ "metadata": {},
41
+ "source": [
42
+ "## Generate synthetic data\n",
43
+ "- current rendering script won't handle characters missing from fonts.\n",
44
+ "- Please use no-text images."
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": 1,
50
+ "metadata": {},
51
+ "outputs": [
52
+ {
53
+ "name": "stderr",
54
+ "output_type": "stream",
55
+ "text": [
56
+ "100%|██████████| 10/10 [00:12<00:00, 1.23s/it]\n"
57
+ ]
58
+ }
59
+ ],
60
+ "source": [
61
+ "from text_rendering import ComicTextSampler, render_comictext, ALIGN_LEFT, ALIGN_CENTER\n",
62
+ "import copy\n",
63
+ "\n",
64
+ "ja_sampler_dict = {\n",
65
+ " 'num_txtblk': 20,\n",
66
+ " 'font': {\n",
67
+ " 'font_dir': 'data/examples/fonts', # font file directory\n",
68
+ " 'font_statics': 'data/font_statics_en.csv', # Just a font list file, please create your own list and ignore the last two cols.\n",
69
+ " 'num': 1200, # first 500 of the fontlist will be used \n",
70
+ "\n",
71
+ " # params to mimic comic/manga text style\n",
72
+ " 'size': {'value': [0.02, 0.03, 0.15],\n",
73
+ " 'prob': [1, 0.4, 0.15]},\n",
74
+ " 'stroke_width': {'value': [0, 0.1, 0.15],\n",
75
+ " 'prob': [1, 0.5, 0.2]},\n",
76
+ " 'color': {'value': ['black', 'white', 'random'],\n",
77
+ " 'prob': [1, 1, 0.4]},\n",
78
+ " },\n",
79
+ " 'text': {\n",
80
+ " 'lang': 'ja', # render japanese, 'en' for english\n",
81
+ " 'orientation': {'value': [1, 0], # 1 is vertical text.\n",
82
+ " 'prob': [1, 0.3]},\n",
83
+ " 'rotation': {'value': [0, 30, 60],\n",
84
+ " 'prob': [1, 0.3, 0.1]},\n",
85
+ " 'num_lines': {'value': [0.15],\n",
86
+ " 'prob': [1]}, \n",
87
+ " 'length': {'value': [0.3],\n",
88
+ " 'prob': [1]},\n",
89
+ " 'min_num_lines': 1,\n",
90
+ " 'min_length': 3,\n",
91
+ " 'alignment': {'value': [ALIGN_LEFT, ALIGN_CENTER],\n",
92
+ " 'prob': [0.3, 1]}\n",
93
+ " }\n",
94
+ " }\n",
95
+ "\n",
96
+ "jp_cts = ComicTextSampler((845, 1280), ja_sampler_dict, seed=0)\n",
97
+ "eng_dict = copy.deepcopy(ja_sampler_dict)\n",
98
+ "eng_dict['text']['lang'] = 'en'\n",
99
+ "eng_dict['text']['orientation'] = {'value': [1, 0],\n",
100
+ " 'prob': [0, 1]}\n",
101
+ "eng_cts = ComicTextSampler((845, 1280), eng_dict, seed=0)\n",
102
+ "\n",
103
+ "img_dir = r'data/examples'\n",
104
+ "save_dir = r'data/examples/annotations'\n",
105
+ " \n",
106
+ "render_comictext([eng_cts, jp_cts], img_dir, save_dir=save_dir, save_prefix=None, render_num=10, label_dir=None, show=False)"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "markdown",
111
+ "metadata": {},
112
+ "source": [
113
+ "## Training\n",
114
+ "### Train Text Block Detector\n",
115
+ "Train yolov5s using official repo of yolov5, assume the trained model is 'yolov5sblk.pt', go to the root directory of yolov5 and run following code.\n",
116
+ "\n",
117
+ "``` python\n",
118
+ "import torch\n",
119
+ "m = torch.load('yolov5sblk.pt')['model']\n",
120
+ "save_dict = {\n",
121
+ " 'cfg': m.yaml,\n",
122
+ " 'weights': m.state_dict()\n",
123
+ "}\n",
124
+ "torch.save(save_dict, 'yolov5sblk.ckpt')\n",
125
+ "```\n",
126
+ "### Train Text Segmentation Head\n",
127
+ "1. Put yolov5sblk.ckpt into data. \n",
128
+ "2. Refer to train_seg.py for further details. \n",
129
+ "\n",
130
+ "### Train DBHead\n",
131
+ "Please refer to train_db.py.\n"
132
+ ]
133
+ },
134
+ {
135
+ "cell_type": "markdown",
136
+ "metadata": {},
137
+ "source": [
138
+ "## Concat weights & export as onnx"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "execution_count": null,
144
+ "metadata": {},
145
+ "outputs": [],
146
+ "source": [
147
+ "from utils.export import *\n",
148
+ "concate_models('data/yolov5sblk.ckpt', 'data/unet_best.ckpt', 'data/db_best.ckpt', 'data/textdetector.pt')\n",
149
+ "\n",
150
+ "batch_size, imgsz = 1, 1024\n",
151
+ "cuda = torch.cuda.is_available()\n",
152
+ "device = 'cpu'\n",
153
+ "im = torch.zeros(batch_size, 3, imgsz, imgsz).to(device)\n",
154
+ "model_path = r'data/textdetector.pt'\n",
155
+ "model = TextDetBase(model_path, device=device).to(device)\n",
156
+ "export_onnx(model, im, model_path, 11)"
157
+ ]
158
+ }
159
+ ],
160
+ "metadata": {
161
+ "interpreter": {
162
+ "hash": "545b34d9a5e72e2b90b819a16ec22002dd3dc9d66aaf1029c3177c6408a5603b"
163
+ },
164
+ "kernelspec": {
165
+ "display_name": "Python 3.9.7 64-bit",
166
+ "language": "python",
167
+ "name": "python3"
168
+ },
169
+ "language_info": {
170
+ "codemirror_mode": {
171
+ "name": "ipython",
172
+ "version": 3
173
+ },
174
+ "file_extension": ".py",
175
+ "mimetype": "text/x-python",
176
+ "name": "python",
177
+ "nbconvert_exporter": "python",
178
+ "pygments_lexer": "ipython3",
179
+ "version": "3.9.7"
180
+ },
181
+ "orig_nbformat": 4
182
+ },
183
+ "nbformat": 4,
184
+ "nbformat_minor": 2
185
+ }
inference.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from basemodel import TextDetBase, TextDetBaseDNN
3
+ import os.path as osp
4
+ from tqdm import tqdm
5
+ import numpy as np
6
+ import cv2
7
+ import torch
8
+ from pathlib import Path
9
+ import torch
10
+ from utils.yolov5_utils import non_max_suppression
11
+ from utils.db_utils import SegDetectorRepresenter
12
+ from utils.io_utils import imread, imwrite, find_all_imgs, NumpyEncoder
13
+ from utils.imgproc_utils import letterbox, xyxy2yolo, get_yololabel_strings
14
+ from utils.textblock import TextBlock, group_output, visualize_textblocks
15
+ from utils.textmask import refine_mask, refine_undetected_mask, REFINEMASK_INPAINT, REFINEMASK_ANNOTATION
16
+ from pathlib import Path
17
+ from typing import Union
18
+
19
+ def init_model(model_path, device):
20
+ cuda = torch.cuda.is_available()
21
+ device = 'cuda' if cuda else 'cpu'
22
+ model = TextDetector(model_path=model_path, input_size=1024, device=device, act='leaky')
23
+ return model
24
+
25
+ def model2annotations(img_dir_list, save_dir, save_json=False, model=None):
26
+ if isinstance(img_dir_list, str):
27
+ img_dir_list = [img_dir_list]
28
+ # cuda = torch.cuda.is_available()
29
+ # device = 'cuda' if cuda else 'cpu'
30
+ # model = TextDetector(model_path=model_path, input_size=1024, device=device, act='leaky')
31
+ imglist = []
32
+ for img_dir in img_dir_list:
33
+ imglist += find_all_imgs(img_dir, abs_path=True)
34
+ for img_path in tqdm(imglist):
35
+ imgname = osp.basename(img_path)
36
+ img = imread(img_path)
37
+ im_h, im_w = img.shape[:2]
38
+ imname = imgname.replace(Path(imgname).suffix, '')
39
+ maskname = 'mask-'+imname+'.png'
40
+ poly_save_path = osp.join(save_dir, 'line-' + imname + '.txt')
41
+ mask, mask_refined, blk_list = model(img, refine_mode=REFINEMASK_ANNOTATION, keep_undetected_mask=True)
42
+ polys = []
43
+ blk_xyxy = []
44
+ blk_dict_list = []
45
+ for blk in blk_list:
46
+ polys += blk.lines
47
+ blk_xyxy.append(blk.xyxy)
48
+ blk_dict_list.append(blk.to_dict())
49
+ blk_xyxy = xyxy2yolo(blk_xyxy, im_w, im_h)
50
+ if blk_xyxy is not None:
51
+ cls_list = [1] * len(blk_xyxy)
52
+ yolo_label = get_yololabel_strings(cls_list, blk_xyxy)
53
+ else:
54
+ yolo_label = ''
55
+ with open(osp.join(save_dir, imname+'.txt'), 'w', encoding='utf8') as f:
56
+ f.write(yolo_label)
57
+
58
+ # num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(mask)
59
+ # _, mask = cv2.threshold(mask, 50, 255, cv2.THRESH_BINARY)
60
+ # draw_connected_labels(num_labels, labels, stats, centroids)
61
+ # visualize_textblocks(img, blk_list)
62
+ # cv2.imshow('rst', img)
63
+ # cv2.imshow('mask', mask)
64
+ # cv2.imshow('mask_refined', mask_refined)
65
+ # cv2.waitKey(0)
66
+
67
+ if len(polys) != 0:
68
+ if isinstance(polys, list):
69
+ polys = np.array(polys)
70
+ polys = polys.reshape(-1, 8)
71
+ np.savetxt(poly_save_path, polys, fmt='%d')
72
+ if save_json:
73
+ with open(osp.join(save_dir, imname+'.json'), 'w', encoding='utf8') as f:
74
+ f.write(json.dumps(blk_dict_list, ensure_ascii=False, cls=NumpyEncoder))
75
+ imwrite(osp.join(save_dir, imgname), img)
76
+ imwrite(osp.join(save_dir, maskname), mask_refined)
77
+
78
+ def preprocess_img(img, input_size=(1024, 1024), device='cpu', bgr2rgb=True, half=False, to_tensor=True):
79
+ if bgr2rgb:
80
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
81
+ img_in, ratio, (dw, dh) = letterbox(img, new_shape=input_size, auto=False, stride=64)
82
+ if to_tensor:
83
+ img_in = img_in.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
84
+ img_in = np.array([np.ascontiguousarray(img_in)]).astype(np.float32) / 255
85
+ if to_tensor:
86
+ img_in = torch.from_numpy(img_in).to(device)
87
+ if half:
88
+ img_in = img_in.half()
89
+ return img_in, ratio, int(dw), int(dh)
90
+
91
+ def postprocess_mask(img: Union[torch.Tensor, np.ndarray], thresh=None):
92
+ # img = img.permute(1, 2, 0)
93
+ if isinstance(img, torch.Tensor):
94
+ img = img.squeeze_()
95
+ if img.device != 'cpu':
96
+ img = img.detach_().cpu()
97
+ img = img.numpy()
98
+ else:
99
+ img = img.squeeze()
100
+ if thresh is not None:
101
+ img = img > thresh
102
+ img = img * 255
103
+ # if isinstance(img, torch.Tensor):
104
+
105
+ return img.astype(np.uint8)
106
+
107
+ def postprocess_yolo(det, conf_thresh, nms_thresh, resize_ratio, sort_func=None):
108
+ det = non_max_suppression(det, conf_thresh, nms_thresh)[0]
109
+ # bbox = det[..., 0:4]
110
+ if det.device != 'cpu':
111
+ det = det.detach_().cpu().numpy()
112
+ det[..., [0, 2]] = det[..., [0, 2]] * resize_ratio[0]
113
+ det[..., [1, 3]] = det[..., [1, 3]] * resize_ratio[1]
114
+ if sort_func is not None:
115
+ det = sort_func(det)
116
+
117
+ blines = det[..., 0:4].astype(np.int32)
118
+ confs = np.round(det[..., 4], 3)
119
+ cls = det[..., 5].astype(np.int32)
120
+ return blines, cls, confs
121
+
122
+ class TextDetector:
123
+ lang_list = ['eng', 'ja', 'unknown']
124
+ langcls2idx = {'eng': 0, 'ja': 1, 'unknown': 2}
125
+
126
+ def __init__(self, model_path, input_size=1024, device='cpu', half=False, nms_thresh=0.35, conf_thresh=0.4, mask_thresh=0.3, act='leaky'):
127
+ super(TextDetector, self).__init__()
128
+ cuda = device == 'cuda'
129
+
130
+ if Path(model_path).suffix == '.onnx':
131
+ self.model = cv2.dnn.readNetFromONNX(model_path)
132
+ self.net = TextDetBaseDNN(input_size, model_path)
133
+ self.backend = 'opencv'
134
+ else:
135
+ self.net = TextDetBase(model_path, device=device, act=act)
136
+ self.backend = 'torch'
137
+
138
+ if isinstance(input_size, int):
139
+ input_size = (input_size, input_size)
140
+ self.input_size = input_size
141
+ self.device = device
142
+ self.half = half
143
+ self.conf_thresh = conf_thresh
144
+ self.nms_thresh = nms_thresh
145
+ self.seg_rep = SegDetectorRepresenter(thresh=0.3)
146
+
147
+ @torch.no_grad()
148
+ def __call__(self, img, refine_mode=REFINEMASK_INPAINT, keep_undetected_mask=False):
149
+ img_in, ratio, dw, dh = preprocess_img(img, input_size=self.input_size, device=self.device, half=self.half, to_tensor=self.backend=='torch')
150
+ im_h, im_w = img.shape[:2]
151
+
152
+ blks, mask, lines_map = self.net(img_in)
153
+
154
+ resize_ratio = (im_w / (self.input_size[0] - dw), im_h / (self.input_size[1] - dh))
155
+ blks = postprocess_yolo(blks, self.conf_thresh, self.nms_thresh, resize_ratio)
156
+
157
+ if self.backend == 'opencv':
158
+ if mask.shape[1] == 2: # some version of opencv spit out reversed result
159
+ tmp = mask
160
+ mask = lines_map
161
+ lines_map = tmp
162
+ mask = postprocess_mask(mask)
163
+
164
+ lines, scores = self.seg_rep(self.input_size, lines_map)
165
+ box_thresh = 0.6
166
+ idx = np.where(scores[0] > box_thresh)
167
+ lines, scores = lines[0][idx], scores[0][idx]
168
+
169
+ # map output to input img
170
+ mask = mask[: mask.shape[0]-dh, : mask.shape[1]-dw]
171
+ mask = cv2.resize(mask, (im_w, im_h), interpolation=cv2.INTER_LINEAR)
172
+ if lines.size == 0 :
173
+ lines = []
174
+ else :
175
+ lines = lines.astype(np.float64)
176
+ lines[..., 0] *= resize_ratio[0]
177
+ lines[..., 1] *= resize_ratio[1]
178
+ lines = lines.astype(np.int32)
179
+ blk_list = group_output(blks, lines, im_w, im_h, mask)
180
+ mask_refined = refine_mask(img, mask, blk_list, refine_mode=refine_mode)
181
+ if keep_undetected_mask:
182
+ mask_refined = refine_undetected_mask(img, mask, mask_refined, blk_list, refine_mode=refine_mode)
183
+
184
+ return mask, mask_refined, blk_list
185
+
186
+ def traverse_by_dict(img_dir_list, dict_dir):
187
+ if isinstance(img_dir_list, str):
188
+ img_dir_list = [img_dir_list]
189
+ imglist = []
190
+ for img_dir in img_dir_list:
191
+ imglist += find_all_imgs(img_dir, abs_path=True)
192
+ for img_path in tqdm(imglist):
193
+ imgname = osp.basename(img_path)
194
+ imname = imgname.replace(Path(imgname).suffix, '')
195
+ mask_path = osp.join(dict_dir, 'mask-'+imname+'.png')
196
+ with open(osp.join(dict_dir, imname+'.json'), 'r', encoding='utf8') as f:
197
+ blk_dict_list = json.loads(f.read())
198
+ blk_list = [TextBlock(**blk_dict) for blk_dict in blk_dict_list]
199
+ img = cv2.imread(img_path)
200
+ mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
201
+ mask = refine_mask(img, mask, blk_list)
202
+
203
+
204
+ visualize_textblocks(img, blk_list, path=dict_dir)
205
+ #cv2.imshow('im', img)
206
+ #cv2.imshow('mask', mask)
207
+ cv2.imwrite(f'{dict_dir}/labeled.png', img)
208
+ #cv2.imwrite('mask.png', mask)
209
+ #cv2.waitKey(0)
210
+ return len(blk_list)
211
+
212
+ if __name__ == '__main__':
213
+ device = 'cpu'
214
+
215
+ #model_path = 'data/comictextdetector.pt'
216
+ model_path = 'data/comictextdetector.pt.onnx'
217
+
218
+ img_dir = r'../input'
219
+ save_dir = r'../output'
220
+ model2annotations(model_path, img_dir, save_dir, save_json=True)
221
+ traverse_by_dict(img_dir, save_dir)
models/__init__.py ADDED
File without changes
models/yolov5/__init__.py ADDED
File without changes
models/yolov5/common.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Common modules
4
+ """
5
+
6
+ import json
7
+ import math
8
+ import platform
9
+ import warnings
10
+ from collections import OrderedDict, namedtuple
11
+ from copy import copy
12
+ from pathlib import Path
13
+
14
+ import cv2
15
+ import numpy as np
16
+ import requests
17
+ import torch
18
+ import torch.nn as nn
19
+ from PIL import Image
20
+ from torch.cuda import amp
21
+
22
+ from utils.yolov5_utils import make_divisible, initialize_weights, check_anchor_order, check_version, fuse_conv_and_bn
23
+
24
+ def autopad(k, p=None): # kernel, padding
25
+ # Pad to 'same'
26
+ if p is None:
27
+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
28
+ return p
29
+
30
+ class Conv(nn.Module):
31
+ # Standard convolution
32
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
33
+ super().__init__()
34
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
35
+ self.bn = nn.BatchNorm2d(c2)
36
+ if isinstance(act, bool):
37
+ self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
38
+ elif isinstance(act, str):
39
+ if act == 'leaky':
40
+ self.act = nn.LeakyReLU(0.1, inplace=True)
41
+ elif act == 'relu':
42
+ self.act = nn.ReLU(inplace=True)
43
+ else:
44
+ self.act = None
45
+ def forward(self, x):
46
+ return self.act(self.bn(self.conv(x)))
47
+
48
+ def forward_fuse(self, x):
49
+ return self.act(self.conv(x))
50
+
51
+
52
+ class DWConv(Conv):
53
+ # Depth-wise convolution class
54
+ def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
55
+ super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
56
+
57
+
58
+ class TransformerLayer(nn.Module):
59
+ # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
60
+ def __init__(self, c, num_heads):
61
+ super().__init__()
62
+ self.q = nn.Linear(c, c, bias=False)
63
+ self.k = nn.Linear(c, c, bias=False)
64
+ self.v = nn.Linear(c, c, bias=False)
65
+ self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
66
+ self.fc1 = nn.Linear(c, c, bias=False)
67
+ self.fc2 = nn.Linear(c, c, bias=False)
68
+
69
+ def forward(self, x):
70
+ x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
71
+ x = self.fc2(self.fc1(x)) + x
72
+ return x
73
+
74
+
75
+ class TransformerBlock(nn.Module):
76
+ # Vision Transformer https://arxiv.org/abs/2010.11929
77
+ def __init__(self, c1, c2, num_heads, num_layers):
78
+ super().__init__()
79
+ self.conv = None
80
+ if c1 != c2:
81
+ self.conv = Conv(c1, c2)
82
+ self.linear = nn.Linear(c2, c2) # learnable position embedding
83
+ self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
84
+ self.c2 = c2
85
+
86
+ def forward(self, x):
87
+ if self.conv is not None:
88
+ x = self.conv(x)
89
+ b, _, w, h = x.shape
90
+ p = x.flatten(2).permute(2, 0, 1)
91
+ return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
92
+
93
+
94
+ class Bottleneck(nn.Module):
95
+ # Standard bottleneck
96
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, act=True): # ch_in, ch_out, shortcut, groups, expansion
97
+ super().__init__()
98
+ c_ = int(c2 * e) # hidden channels
99
+ self.cv1 = Conv(c1, c_, 1, 1, act=act)
100
+ self.cv2 = Conv(c_, c2, 3, 1, g=g, act=act)
101
+ self.add = shortcut and c1 == c2
102
+
103
+ def forward(self, x):
104
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
105
+
106
+
107
+ class BottleneckCSP(nn.Module):
108
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
109
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
110
+ super().__init__()
111
+ c_ = int(c2 * e) # hidden channels
112
+ self.cv1 = Conv(c1, c_, 1, 1)
113
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
114
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
115
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
116
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
117
+ self.act = nn.SiLU()
118
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
119
+
120
+ def forward(self, x):
121
+ y1 = self.cv3(self.m(self.cv1(x)))
122
+ y2 = self.cv2(x)
123
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
124
+
125
+
126
+ class C3(nn.Module):
127
+ # CSP Bottleneck with 3 convolutions
128
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, act=True): # ch_in, ch_out, number, shortcut, groups, expansion
129
+ super().__init__()
130
+ c_ = int(c2 * e) # hidden channels
131
+ self.cv1 = Conv(c1, c_, 1, 1, act=act)
132
+ self.cv2 = Conv(c1, c_, 1, 1, act=act)
133
+ self.cv3 = Conv(2 * c_, c2, 1, act=act) # act=FReLU(c2)
134
+ self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0, act=act) for _ in range(n)))
135
+ # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
136
+
137
+ def forward(self, x):
138
+ return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
139
+
140
+
141
+ class C3TR(C3):
142
+ # C3 module with TransformerBlock()
143
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
144
+ super().__init__(c1, c2, n, shortcut, g, e)
145
+ c_ = int(c2 * e)
146
+ self.m = TransformerBlock(c_, c_, 4, n)
147
+
148
+
149
+ class C3SPP(C3):
150
+ # C3 module with SPP()
151
+ def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
152
+ super().__init__(c1, c2, n, shortcut, g, e)
153
+ c_ = int(c2 * e)
154
+ self.m = SPP(c_, c_, k)
155
+
156
+
157
+ class C3Ghost(C3):
158
+ # C3 module with GhostBottleneck()
159
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
160
+ super().__init__(c1, c2, n, shortcut, g, e)
161
+ c_ = int(c2 * e) # hidden channels
162
+ self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))
163
+
164
+
165
+ class SPP(nn.Module):
166
+ # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
167
+ def __init__(self, c1, c2, k=(5, 9, 13)):
168
+ super().__init__()
169
+ c_ = c1 // 2 # hidden channels
170
+ self.cv1 = Conv(c1, c_, 1, 1)
171
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
172
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
173
+
174
+ def forward(self, x):
175
+ x = self.cv1(x)
176
+ with warnings.catch_warnings():
177
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
178
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
179
+
180
+
181
+ class SPPF(nn.Module):
182
+ # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
183
+ def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
184
+ super().__init__()
185
+ c_ = c1 // 2 # hidden channels
186
+ self.cv1 = Conv(c1, c_, 1, 1)
187
+ self.cv2 = Conv(c_ * 4, c2, 1, 1)
188
+ self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
189
+
190
+ def forward(self, x):
191
+ x = self.cv1(x)
192
+ with warnings.catch_warnings():
193
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
194
+ y1 = self.m(x)
195
+ y2 = self.m(y1)
196
+ return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
197
+
198
+
199
+ class Focus(nn.Module):
200
+ # Focus wh information into c-space
201
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
202
+ super().__init__()
203
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
204
+ # self.contract = Contract(gain=2)
205
+
206
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
207
+ return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
208
+ # return self.conv(self.contract(x))
209
+
210
+
211
+ class GhostConv(nn.Module):
212
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
213
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
214
+ super().__init__()
215
+ c_ = c2 // 2 # hidden channels
216
+ self.cv1 = Conv(c1, c_, k, s, None, g, act)
217
+ self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
218
+
219
+ def forward(self, x):
220
+ y = self.cv1(x)
221
+ return torch.cat([y, self.cv2(y)], 1)
222
+
223
+
224
+ class GhostBottleneck(nn.Module):
225
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
226
+ def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
227
+ super().__init__()
228
+ c_ = c2 // 2
229
+ self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
230
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
231
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
232
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
233
+ Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
234
+
235
+ def forward(self, x):
236
+ return self.conv(x) + self.shortcut(x)
237
+
238
+
239
+ class Contract(nn.Module):
240
+ # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
241
+ def __init__(self, gain=2):
242
+ super().__init__()
243
+ self.gain = gain
244
+
245
+ def forward(self, x):
246
+ b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
247
+ s = self.gain
248
+ x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
249
+ x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
250
+ return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
251
+
252
+
253
+ class Expand(nn.Module):
254
+ # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
255
+ def __init__(self, gain=2):
256
+ super().__init__()
257
+ self.gain = gain
258
+
259
+ def forward(self, x):
260
+ b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
261
+ s = self.gain
262
+ x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
263
+ x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
264
+ return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
265
+
266
+
267
+ class Concat(nn.Module):
268
+ # Concatenate a list of tensors along dimension
269
+ def __init__(self, dimension=1):
270
+ super().__init__()
271
+ self.d = dimension
272
+
273
+ def forward(self, x):
274
+ return torch.cat(x, self.d)
275
+
276
+
277
+ class Classify(nn.Module):
278
+ # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
279
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
280
+ super().__init__()
281
+ self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
282
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
283
+ self.flat = nn.Flatten()
284
+
285
+ def forward(self, x):
286
+ z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
287
+ return self.flat(self.conv(z)) # flatten to x(b,c2)
288
+
289
+
models/yolov5/yolo.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from operator import mod
2
+ from cv2 import imshow
3
+ from utils.yolov5_utils import scale_img
4
+ from copy import deepcopy
5
+ from .common import *
6
+
7
+ class Detect(nn.Module):
8
+ stride = None # strides computed during build
9
+ onnx_dynamic = False # ONNX export parameter
10
+
11
+ def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
12
+ super().__init__()
13
+ self.nc = nc # number of classes
14
+ self.no = nc + 5 # number of outputs per anchor
15
+ self.nl = len(anchors) # number of detection layers
16
+ self.na = len(anchors[0]) // 2 # number of anchors
17
+ self.grid = [torch.zeros(1)] * self.nl # init grid
18
+ self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid
19
+ self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
20
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
21
+ self.inplace = inplace # use in-place ops (e.g. slice assignment)
22
+
23
+ def forward(self, x):
24
+ z = [] # inference output
25
+ for i in range(self.nl):
26
+ x[i] = self.m[i](x[i]) # conv
27
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
28
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
29
+
30
+ if not self.training: # inference
31
+ if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
32
+ self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
33
+
34
+ y = x[i].sigmoid()
35
+ if self.inplace:
36
+ y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy
37
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
38
+ else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
39
+ xy = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy
40
+ wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
41
+ y = torch.cat((xy, wh, y[..., 4:]), -1)
42
+ z.append(y.view(bs, -1, self.no))
43
+
44
+ return x if self.training else (torch.cat(z, 1), x)
45
+
46
+ def _make_grid(self, nx=20, ny=20, i=0):
47
+ d = self.anchors[i].device
48
+ if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
49
+ yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)], indexing='ij')
50
+ else:
51
+ yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)])
52
+ grid = torch.stack((xv, yv), 2).expand((1, self.na, ny, nx, 2)).float()
53
+ anchor_grid = (self.anchors[i].clone() * self.stride[i]) \
54
+ .view((1, self.na, 1, 1, 2)).expand((1, self.na, ny, nx, 2)).float()
55
+ return grid, anchor_grid
56
+
57
+ class Model(nn.Module):
58
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
59
+ super().__init__()
60
+ self.out_indices = None
61
+ if isinstance(cfg, dict):
62
+ self.yaml = cfg # model dict
63
+ else: # is *.yaml
64
+ import yaml # for torch hub
65
+ self.yaml_file = Path(cfg).name
66
+ with open(cfg, encoding='ascii', errors='ignore') as f:
67
+ self.yaml = yaml.safe_load(f) # model dict
68
+
69
+ # Define model
70
+ ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
71
+ if nc and nc != self.yaml['nc']:
72
+ # LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
73
+ self.yaml['nc'] = nc # override yaml value
74
+ if anchors:
75
+ # LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
76
+ self.yaml['anchors'] = round(anchors) # override yaml value
77
+ self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
78
+ self.names = [str(i) for i in range(self.yaml['nc'])] # default names
79
+ self.inplace = self.yaml.get('inplace', True)
80
+
81
+ # Build strides, anchors
82
+ m = self.model[-1] # Detect()
83
+ # with torch.no_grad():
84
+ if isinstance(m, Detect):
85
+ s = 256 # 2x min stride
86
+ m.inplace = self.inplace
87
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
88
+ m.anchors /= m.stride.view(-1, 1, 1)
89
+ check_anchor_order(m)
90
+ self.stride = m.stride
91
+ self._initialize_biases() # only run once
92
+
93
+ # Init weights, biases
94
+ initialize_weights(self)
95
+
96
+ def forward(self, x, augment=False, profile=False, visualize=False, detect=False):
97
+ if augment:
98
+ return self._forward_augment(x) # augmented inference, None
99
+ return self._forward_once(x, profile, visualize, detect=detect) # single-scale inference, train
100
+
101
+ def _forward_augment(self, x):
102
+ img_size = x.shape[-2:] # height, width
103
+ s = [1, 0.83, 0.67] # scales
104
+ f = [None, 3, None] # flips (2-ud, 3-lr)
105
+ y = [] # outputs
106
+ for si, fi in zip(s, f):
107
+ xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
108
+ yi = self._forward_once(xi)[0] # forward
109
+ # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
110
+ yi = self._descale_pred(yi, fi, si, img_size)
111
+ y.append(yi)
112
+ y = self._clip_augmented(y) # clip augmented tails
113
+ return torch.cat(y, 1), None # augmented inference, train
114
+
115
+ def _forward_once(self, x, profile=False, visualize=False, detect=False):
116
+ y, dt = [], [] # outputs
117
+ z = []
118
+ for ii, m in enumerate(self.model):
119
+ if m.f != -1: # if not from previous layer
120
+ x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
121
+ if profile:
122
+ self._profile_one_layer(m, x, dt)
123
+ x = m(x) # run
124
+ y.append(x if m.i in self.save else None) # save output
125
+ if self.out_indices is not None:
126
+ if m.i in self.out_indices:
127
+ z.append(x)
128
+ if self.out_indices is not None:
129
+ if detect:
130
+ return x, z
131
+ else:
132
+ return z
133
+ else:
134
+ return x
135
+
136
+ def _descale_pred(self, p, flips, scale, img_size):
137
+ # de-scale predictions following augmented inference (inverse operation)
138
+ if self.inplace:
139
+ p[..., :4] /= scale # de-scale
140
+ if flips == 2:
141
+ p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
142
+ elif flips == 3:
143
+ p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
144
+ else:
145
+ x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
146
+ if flips == 2:
147
+ y = img_size[0] - y # de-flip ud
148
+ elif flips == 3:
149
+ x = img_size[1] - x # de-flip lr
150
+ p = torch.cat((x, y, wh, p[..., 4:]), -1)
151
+ return p
152
+
153
+ def _clip_augmented(self, y):
154
+ # Clip YOLOv5 augmented inference tails
155
+ nl = self.model[-1].nl # number of detection layers (P3-P5)
156
+ g = sum(4 ** x for x in range(nl)) # grid points
157
+ e = 1 # exclude layer count
158
+ i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
159
+ y[0] = y[0][:, :-i] # large
160
+ i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
161
+ y[-1] = y[-1][:, i:] # small
162
+ return y
163
+
164
+ def _profile_one_layer(self, m, x, dt):
165
+ c = isinstance(m, Detect) # is final layer, copy input as inplace fix
166
+ for _ in range(10):
167
+ m(x.copy() if c else x)
168
+
169
+
170
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
171
+ # https://arxiv.org/abs/1708.02002 section 3.3
172
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
173
+ m = self.model[-1] # Detect() module
174
+ for mi, s in zip(m.m, m.stride): # from
175
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
176
+ b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
177
+ b.data[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
178
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
179
+
180
+ def _print_biases(self):
181
+ m = self.model[-1] # Detect() module
182
+ for mi in m.m: # from
183
+ b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
184
+
185
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
186
+ for m in self.model.modules():
187
+ if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
188
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
189
+ delattr(m, 'bn') # remove batchnorm
190
+ m.forward = m.forward_fuse # update forward
191
+ # self.info()
192
+ return self
193
+
194
+ # def info(self, verbose=False, img_size=640): # print model information
195
+ # model_info(self, verbose, img_size)
196
+
197
+ def _apply(self, fn):
198
+ # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
199
+ self = super()._apply(fn)
200
+ m = self.model[-1] # Detect()
201
+ if isinstance(m, Detect):
202
+ m.stride = fn(m.stride)
203
+ m.grid = list(map(fn, m.grid))
204
+ if isinstance(m.anchor_grid, list):
205
+ m.anchor_grid = list(map(fn, m.anchor_grid))
206
+ return self
207
+
208
+ def parse_model(d, ch): # model_dict, input_channels(3)
209
+ # LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
210
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
211
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
212
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
213
+
214
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
215
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
216
+ m = eval(m) if isinstance(m, str) else m # eval strings
217
+ for j, a in enumerate(args):
218
+ try:
219
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
220
+ except NameError:
221
+ pass
222
+
223
+ n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
224
+ if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, Focus,
225
+ BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:
226
+ c1, c2 = ch[f], args[0]
227
+ if c2 != no: # if not output
228
+ c2 = make_divisible(c2 * gw, 8)
229
+
230
+ args = [c1, c2, *args[1:]]
231
+ if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
232
+ args.insert(2, n) # number of repeats
233
+ n = 1
234
+ elif m is nn.BatchNorm2d:
235
+ args = [ch[f]]
236
+ elif m is Concat:
237
+ c2 = sum(ch[x] for x in f)
238
+ elif m is Detect:
239
+ args.append([ch[x] for x in f])
240
+ if isinstance(args[1], int): # number of anchors
241
+ args[1] = [list(range(args[1] * 2))] * len(f)
242
+ elif m is Contract:
243
+ c2 = ch[f] * args[0] ** 2
244
+ elif m is Expand:
245
+ c2 = ch[f] // args[0] ** 2
246
+ else:
247
+ c2 = ch[f]
248
+
249
+ m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
250
+ t = str(m)[8:-2].replace('__main__.', '') # module type
251
+ np = sum(x.numel() for x in m_.parameters()) # number params
252
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
253
+ # LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print
254
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
255
+ layers.append(m_)
256
+ if i == 0:
257
+ ch = []
258
+ ch.append(c2)
259
+ return nn.Sequential(*layers), sorted(save)
260
+
261
+ def load_yolov5(weights, map_location='cuda', fuse=True, inplace=True, out_indices=[1, 3, 5, 7, 9]):
262
+ if isinstance(weights, str):
263
+ ckpt = torch.load(weights, map_location=map_location) # load
264
+ else:
265
+ ckpt = weights
266
+
267
+ if fuse:
268
+ model = ckpt['model'].float().fuse().eval() # FP32 model
269
+ else:
270
+ model = ckpt['model'].float().eval() # without layer fuse
271
+
272
+ # Compatibility updates
273
+ for m in model.modules():
274
+ if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:
275
+ m.inplace = inplace # pytorch 1.7.0 compatibility
276
+ if type(m) is Detect:
277
+ if not isinstance(m.anchor_grid, list): # new Detect Layer compatibility
278
+ delattr(m, 'anchor_grid')
279
+ setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
280
+ elif type(m) is Conv:
281
+ m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
282
+ model.out_indices = out_indices
283
+ return model
284
+
285
+ @torch.no_grad()
286
+ def load_yolov5_ckpt(weights, map_location='cpu', fuse=True, inplace=True, out_indices=[1, 3, 5, 7, 9]):
287
+ if isinstance(weights, str):
288
+ ckpt = torch.load(weights, map_location=map_location) # load
289
+ else:
290
+ ckpt = weights
291
+
292
+ model = Model(ckpt['cfg'])
293
+ model.load_state_dict(ckpt['weights'], strict=True)
294
+
295
+ if fuse:
296
+ model = model.float().fuse().eval() # FP32 model
297
+ else:
298
+ model = model.float().eval() # without layer fuse
299
+
300
+ # Compatibility updates
301
+ for m in model.modules():
302
+ if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:
303
+ m.inplace = inplace # pytorch 1.7.0 compatibility
304
+ if type(m) is Detect:
305
+ if not isinstance(m.anchor_grid, list): # new Detect Layer compatibility
306
+ delattr(m, 'anchor_grid')
307
+ setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
308
+ elif type(m) is Conv:
309
+ m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
310
+ model.out_indices = out_indices
311
+ return model
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ onnx>=1.9.0
2
+ onnx-simplifier>=0.3.6
3
+ opencv-python>=4.1.2
4
+ Pillow>=7.1.2
5
+ torch>=1.7.0
6
+ torchvision>=0.8.1
7
+ tqdm>=4.41.0
8
+ torchsummary
9
+
10
+ numpy
11
+ wandb
12
+ trdg
13
+ gradio
14
+ zipfile
seg_dataset.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ import os.path as osp
4
+ import random
5
+ from itertools import repeat
6
+ from multiprocessing.pool import Pool, ThreadPool
7
+ from pathlib import Path
8
+ from threading import Thread
9
+ from zipfile import ZipFile
10
+
11
+ import cv2
12
+ import numpy as np
13
+ from numpy.lib.npyio import load
14
+ from numpy.random import rand
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from torch.utils import data
18
+ from torchvision.transforms.transforms import Compose
19
+
20
+ from torch.utils.data import Dataset
21
+ from tqdm import tqdm
22
+ from pathlib import Path
23
+
24
+ from tqdm import tqdm
25
+
26
+ from torchvision import transforms
27
+ import random
28
+ from torch.utils.data import DataLoader, Dataset
29
+ from utils.general import LOGGER, Loggers, CUDA, DEVICE
30
+ from utils.imgproc_utils import resize_keepasp, letterbox
31
+ from utils.io_utils import imread, imwrite
32
+
33
+ WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1)) # DPP
34
+ NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of multiprocessing threads
35
+ IMG_EXT = ['.bmp', '.jpg', '.png', '.jpeg']
36
+
37
+ def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
38
+ # HSV color-space augmentation
39
+ if hgain or sgain or vgain:
40
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
41
+ hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
42
+ dtype = im.dtype # uint8
43
+
44
+ x = np.arange(0, 256, dtype=r.dtype)
45
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
46
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
47
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
48
+
49
+ im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
50
+ cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
51
+
52
+ def load_image_mask(self, i, max_size=None):
53
+ # loads 1 image from dataset index 'i', returns im, original hw, resized hw
54
+ img, mask = self.imgs[i], self.masks[i]
55
+ imp, maskp = self.img_mask_list[i]
56
+ if img is None:
57
+ img = cv2.imread(imp)
58
+ if mask is None:
59
+ mask = cv2.imread(maskp, cv2.IMREAD_GRAYSCALE)
60
+ if max_size is not None:
61
+ if isinstance(max_size, tuple):
62
+ max_size = max_size[0]
63
+ try:
64
+ img = resize_keepasp(img, max_size)
65
+ mask = resize_keepasp(mask, max_size, interpolation=cv2.INTER_AREA)
66
+ except:
67
+ pass
68
+ return img, mask
69
+
70
+ def mini_mosaic(self, img, mask):
71
+ im_h, im_w = img.shape[0], img.shape[1]
72
+ idx = random.randint(0, len(self)-1)
73
+ img2, mask2 = load_image_mask(self, idx, self.img_size)
74
+ img2_h, img2_w = img2.shape[0], img2.shape[1]
75
+ ratio = img2_h / im_h
76
+ if img2_h > img2_w and ratio > 0.4 and ratio < 1.6:
77
+ im_h = max(im_h, img2_h)
78
+ im_w = im_w + img2_w
79
+ im_tmp = np.zeros((im_h, im_w, 3), np.uint8)
80
+ im_tmp[:img.shape[0], :img.shape[1]] = img
81
+ im_tmp[:img2_h, img.shape[1]:] = img2
82
+ mask_tmp = np.zeros((im_h, im_w), np.uint8)
83
+ mask_tmp[:img.shape[0], :img.shape[1]] = mask
84
+ mask_tmp[:img2_h, img.shape[1]:] = mask2
85
+
86
+ img = np.ascontiguousarray(im_tmp)
87
+ mask = np.ascontiguousarray(mask_tmp)
88
+ return img, mask
89
+
90
+ class LoadImageAndMask(Dataset):
91
+ def __init__(self, img_dir, mask_dir=None, img_size=640, augment=False, aug_param=None, cache=False, stride=128, cache_mask_only=True):
92
+ if isinstance(img_dir, str):
93
+ self.img_dir = [img_dir]
94
+ elif isinstance(img_dir, list):
95
+ self.img_dir = img_dir
96
+ else:
97
+ raise Exception('unknown img_dir format')
98
+
99
+ if mask_dir is None or mask_dir == '':
100
+ self.mask_dir = self.img_dir
101
+ else:
102
+ if isinstance(mask_dir, str):
103
+ self.mask_dir = [mask_dir]
104
+ elif isinstance(mask_dir, list):
105
+ self.mask_dir = mask_dir
106
+
107
+ self.img_mask_list = []
108
+ self.img_size = (img_size, img_size)
109
+ self.stride = stride
110
+ self._augment = augment
111
+ if self._augment:
112
+ self._mini_mosaic = aug_param['mini_mosaic']
113
+ self._augment_hsv = aug_param['hsv']
114
+ self._flip_lr = aug_param['flip_lr']
115
+ self._neg = aug_param['neg']
116
+ size_range = aug_param['size_range']
117
+ if size_range[0] != -1:
118
+ min_size = round(img_size * size_range[0] / stride ) * stride
119
+ max_size = round(img_size * size_range[1] / stride ) * stride
120
+ self.valid_size = np.arange(min_size, max_size+1, stride)
121
+ self.multi_size = True
122
+ else:
123
+ self.valid_size = None
124
+ self.multi_size = False
125
+ for img_dir in self.img_dir:
126
+ for filep in glob.glob(osp.join(img_dir, "*")):
127
+ filename = osp.basename(filep)
128
+ file_suffix = Path(filename).suffix
129
+ if file_suffix.lower() not in IMG_EXT:
130
+ continue
131
+ maskname = 'mask-' + filename.replace(file_suffix, '.png')
132
+ for mask_dir in self.mask_dir:
133
+ maskp = osp.join(mask_dir, maskname)
134
+ if osp.exists(maskp):
135
+ self.img_mask_list.append((filep, maskp))
136
+ self._img_transform = transforms.Compose([transforms.ToTensor()])
137
+ self._mask_transform = transforms.Compose([transforms.ToTensor()])
138
+
139
+ n = len(self.img_mask_list)
140
+ self.imgs, self.masks = [None] * n, [None] * n
141
+ gb = 0
142
+ if cache:
143
+ results = ThreadPool(NUM_THREADS).imap(lambda x: load_image_mask(*x, max_size=img_size), zip(repeat(self), range(n)))
144
+ pbar = tqdm(enumerate(results), total=n)
145
+ for i, x in pbar:
146
+ im, self.masks[i] = x # im, hw_orig, hw_resized = load_image_mask(self, i)
147
+ if not cache_mask_only:
148
+ self.imgs[i] = im
149
+ gb += self.imgs[i].nbytes
150
+ gb += self.masks[i].nbytes
151
+ if gb / 1E9 > 7:
152
+ break
153
+ pbar.desc = f'Caching images ({gb / 1E9:.1f}GB )'
154
+ pbar.close()
155
+
156
+ def initialize(self):
157
+ if self.augment:
158
+ if self.multi_size:
159
+ self.img_size = random.choice(self.valid_size)
160
+
161
+ def transform(self, img, mask):
162
+ cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
163
+ img = img.astype(np.float32) / 255
164
+ mask = (mask > 30).astype(np.float32)
165
+ # mask = mask / 255
166
+ img = self._img_transform(img)
167
+ mask = self._mask_transform(mask)
168
+ return img, mask
169
+
170
+ def augment(self, img, mask):
171
+ im_h, im_w = img.shape[0], img.shape[1]
172
+ if im_h > im_w and random.random() < self._mini_mosaic:
173
+ # imp2, maskp2 = random.choice(self.img_mask_list)
174
+ img, mask = mini_mosaic(self, img, mask)
175
+
176
+ img, ratio, (dw, dh) = letterbox(img, new_shape=self.img_size, auto=False)
177
+ mask, ratio, (dw, dh) = letterbox(mask, new_shape=self.img_size, auto=False)
178
+
179
+ if random.random() < self._augment_hsv:
180
+ augment_hsv(img)
181
+ if random.random() < self._flip_lr:
182
+ cv2.flip(img, 1, img)
183
+ cv2.flip(mask, 1, mask)
184
+ if random.random() < self._neg:
185
+ img = 255 - img
186
+ return img, mask
187
+
188
+ def inverse_transform(self, img: torch.Tensor):
189
+ img = img.permute(1, 2, 0)
190
+ img = img * 255
191
+ img = img.cpu().numpy().astype(np.uint8)
192
+ return img
193
+
194
+ def __len__(self):
195
+ return len(self.img_mask_list)
196
+
197
+ def __getitem__(self, idx):
198
+ img, mask = load_image_mask(self, idx, self.img_size)
199
+ if self._augment:
200
+ img, mask = self.augment(img, mask)
201
+ else:
202
+ img, ratio, (dw, dh) = letterbox(img, new_shape=self.img_size, auto=False)
203
+ mask, ratio, (dw, dh) = letterbox(mask, new_shape=self.img_size, auto=False)
204
+ return self.transform(img, mask)
205
+
206
+ def create_dataloader(img_dir, mask_dir, imgsz, batch_size, augment=False, aug_param=None, cache=False, workers=8, shuffle=False):
207
+ dataset = LoadImageAndMask(img_dir, mask_dir, imgsz, augment, aug_param, cache)
208
+ batch_size = min(batch_size, len(dataset))
209
+ nw = min([os.cpu_count() // WORLD_SIZE, batch_size if batch_size > 1 else 0, workers]) # number of workers
210
+ loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, pin_memory=True, num_workers=nw)
211
+ return dataset, loader
212
+
213
+ if __name__ == '__main__':
214
+ random.seed(42)
215
+ torch.random.manual_seed(42)
216
+ np.random.seed(42)
217
+ import yaml
218
+ hyp_p = r'data/train_hyp.yaml'
219
+ with open(hyp_p, 'r', encoding='utf8') as f:
220
+ hyp = yaml.safe_load(f.read())
221
+ hyp['data']['train_img_dir'] = [r'D:/neonbub/datasets/codat_manga_v3/images/train', r'D:/neonbub/datasets/ComicErased/processed']
222
+ hyp['data']['val_img_dir'] = [r'D:/neonbub/datasets/codat_manga_v3/images/val']
223
+ hyp['data']['train_mask_dir'] = r'D:/neonbub/datasets/ComicSegV2'
224
+ hyp['data']['val_mask_dir'] = r'D:/neonbub/datasets/ComicSegV2'
225
+ hyp['data']['cache'] = False
226
+
227
+ hyp_train, hyp_data, hyp_model, hyp_logger, hyp_resume = hyp['train'], hyp['data'], hyp['model'], hyp['logger'], hyp['resume']
228
+
229
+ batch_size = hyp_train['batch_size']
230
+ batch_size = 4
231
+ num_workers = 2
232
+
233
+ train_img_dir, train_mask_dir, imgsz, augment, aug_param = hyp_data['train_img_dir'], hyp_data['train_mask_dir'], hyp_data['imgsz'], hyp_data['augment'], hyp_data['aug_param']
234
+ val_img_dir, val_mask_dir = hyp_data['val_img_dir'], hyp_data['val_mask_dir']
235
+ train_dataset, train_loader = create_dataloader(train_img_dir, train_mask_dir, imgsz, batch_size, augment, aug_param, shuffle=True, workers=num_workers, cache=hyp_data['cache'])
236
+ val_dataset, val_loader = create_dataloader(val_img_dir, val_mask_dir, imgsz, batch_size, augment=False, shuffle=False, workers=num_workers, cache=hyp_data['cache'])
237
+ LOGGER.info(f'num training imgs: {len(train_dataset)}, num val imgs: {len(val_dataset)}')
238
+
239
+ for epoch in range(0, 4): # epoch ------------------------------------------------------------------
240
+ train_dataset.initialize()
241
+ pbar = enumerate(train_loader)
242
+ pbar = tqdm(pbar, total=len(train_loader), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
243
+ pbar.set_description(f' training size: {train_dataset.img_size}')
244
+ for i, (imgs, masks) in pbar:
245
+ img, mask = imgs[0], masks[0]
246
+ imgs = imgs
247
+ masks = masks
248
+ img = train_dataset.inverse_transform(img)
249
+ mask = train_dataset.inverse_transform(mask)
250
+ cv2.imshow('img', img)
251
+ cv2.imshow('mask', mask)
252
+ cv2.waitKey(0)
253
+ pbar.close()
text_rendering.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import copy
2
+ from http.client import IM_USED
3
+ import pathlib
4
+ import shutil
5
+ import PIL
6
+ import cv2
7
+
8
+ import numpy as np
9
+ import os.path as osp
10
+ import os
11
+ from PIL import Image, ImageColor, ImageFont, ImageDraw, ImageFilter, ImageOps
12
+ import random
13
+
14
+ from numpy.random import rand
15
+ from trdg.utils import load_dict, load_fonts
16
+ from tqdm import tqdm
17
+ import pandas as pd
18
+ import sys
19
+ sys.path.append(os.getcwd())
20
+ from utils.io_utils import find_all_imgs, imread, imwrite
21
+ from utils.imgproc_utils import *
22
+ import copy
23
+
24
+ ALIGN_LEFT = 0
25
+ ALIGN_CENTER = 1
26
+ ALIGN_RIGHT = 2
27
+
28
+ ORIENTATION_HOR = 0
29
+ ORIENTATION_VER = 1
30
+
31
+ def get_textlines_from_langdict(lang_dict, num_line, line_len, sampler=None):
32
+ textlines = []
33
+ dict_len = len(lang_dict)
34
+ for ii in range(num_line):
35
+ line = ''
36
+ for jj in range(line_len):
37
+ line += lang_dict[random.randrange(dict_len)] + ' '
38
+ textlines.append(line[:line_len])
39
+ if sampler is None:
40
+ return textlines
41
+ return textlines
42
+
43
+ def draw_text_polygons(img, text_polygons, color=None):
44
+ if isinstance(img, PIL.Image.Image):
45
+ img = np.array(img)
46
+ img = np.copy(img)
47
+ for poly in text_polygons:
48
+ if color is None:
49
+ randcolor = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
50
+ else:
51
+ randcolor = color
52
+ cv2.polylines(img,[poly.reshape((-1, 1, 2))],True,randcolor, thickness=2)
53
+ return img
54
+
55
+ def draw_textblk(textlines, font,
56
+ fill='black',
57
+ stroke_width=0,
58
+ stroke_fill='grey',
59
+ spacing=0,
60
+ rotation=0,
61
+ orientation=ORIENTATION_HOR,
62
+ alignment=ALIGN_LEFT):
63
+
64
+ text_size = np.array([font.getsize(line) for line in textlines])
65
+ if orientation == ORIENTATION_HOR:
66
+ line_widths, line_heights = text_size[:, 0], text_size[:, 1]
67
+ textblk_w = max(text_size[:, 0]) + 3*stroke_width
68
+ textblk_h = (len(textlines) - 1) * spacing + text_size[:, 1].sum() + 3*stroke_width
69
+ else:
70
+ line_widths, line_heights = text_size[:, 1], text_size[:, 0]
71
+ textblk_w = line_widths.sum() + 3*stroke_width
72
+ textblk_h = max(line_heights) + 3*stroke_width
73
+ if orientation == ORIENTATION_VER:
74
+ textblk_h += font.size * 3 # some fonts are not correctly aligned
75
+
76
+ txtblk_img = Image.new("RGBA", (textblk_w, textblk_h), (255, 255, 255, 255))
77
+ txtblk_draw = ImageDraw.Draw(txtblk_img)
78
+ txtblk_draw.fontmode = '1' # disable anti-aliasing
79
+ txtblk_mask = Image.new("L", (textblk_w, textblk_h), (0))
80
+ tmp_msk = txtblk_mask.copy()
81
+ tmp_msk_draw = ImageDraw.Draw(tmp_msk)
82
+ tmp_msk_draw.fontmode = '1'
83
+
84
+ textpolygons = []
85
+ if orientation == ORIENTATION_VER:
86
+ for ii, line in enumerate(textlines):
87
+ x_offset = sum(line_widths[:ii]) + stroke_width
88
+ for jj, char in enumerate(line):
89
+ txtblk_draw.text((x_offset, jj*font.size), char, font=font, fill=fill, stroke_width=stroke_width, stroke_fill=stroke_fill)
90
+ tmp_msk_draw.text((x_offset, jj*font.size), char, font=font, fill='white', stroke_width=stroke_width, stroke_fill='white')
91
+ valid_bbox = tmp_msk.getbbox()
92
+ if valid_bbox is None:
93
+ continue
94
+ txtblk_mask.paste(tmp_msk, mask=tmp_msk)
95
+ tmp_msk.paste('black', [0, 0, tmp_msk.size[0],tmp_msk.size[1]])
96
+ textpolygons.append([valid_bbox[0], valid_bbox[1], valid_bbox[2]-valid_bbox[0], valid_bbox[3]-valid_bbox[1]])
97
+ else:
98
+ for ii, line in enumerate(textlines):
99
+ x_offset = stroke_width
100
+ y_offset = sum(line_heights[0:ii]) + stroke_width
101
+ if alignment == ALIGN_CENTER:
102
+ x_offset += (textblk_w - line_widths[ii]) / 2
103
+ txtblk_draw.text((x_offset, y_offset), line, font=font, fill=fill, stroke_width=stroke_width, stroke_fill=stroke_fill)
104
+ tmp_msk_draw.text((x_offset, y_offset), line, font=font, fill='white', stroke_width=stroke_width, stroke_fill='white')
105
+ valid_bbox = tmp_msk.getbbox()
106
+ if valid_bbox is None:
107
+ continue
108
+ txtblk_mask.paste(tmp_msk, mask=tmp_msk)
109
+ tmp_msk.paste('black', [0, 0, tmp_msk.size[0],tmp_msk.size[1]])
110
+ textpolygons.append([valid_bbox[0], valid_bbox[1], valid_bbox[2]-valid_bbox[0], valid_bbox[3]-valid_bbox[1]])
111
+ bbox = txtblk_mask.getbbox()
112
+ if bbox is None:
113
+ return None, None, None
114
+ textpolygons = np.array(textpolygons)
115
+ textpolygons = xywh2xyxypoly(textpolygons)
116
+ txtblk_img, txtblk_mask = txtblk_img.crop(bbox), txtblk_mask.crop(bbox)
117
+ textpolygons[:, ::2] = np.clip(textpolygons[:, ::2] - bbox[0], 0, txtblk_mask.width-1)
118
+ textpolygons[:, 1::2] = np.clip(textpolygons[:, 1::2] - bbox[1], 0, txtblk_mask.height-1)
119
+ if rotation != 0:
120
+ center = (txtblk_img.width/2, txtblk_img.height/2)
121
+ txtblk_img = txtblk_img.rotate(rotation, Image.BICUBIC, expand=1)
122
+ txtblk_mask = txtblk_mask.rotate(rotation, Image.BICUBIC, expand=1)
123
+ new_center = (txtblk_img.width / 2, txtblk_img.height / 2)
124
+ textpolygons = rotate_polygons(center, textpolygons, rotation, new_center)
125
+ # txtblk_img, txtblk_mask = txtblk_img.crop(bbox), txtblk_mask.crop(bbox)
126
+ # textpolygons[:, ::2] = np.clip(textpolygons[:, ::2] - bbox[0], 0, txtblk_mask.width-1)
127
+ # textpolygons[:, 1::2] = np.clip(textpolygons[:, 1::2] - bbox[1], 0, txtblk_mask.height-1)
128
+ return txtblk_img, txtblk_mask, textpolygons
129
+
130
+ def create_random_sampler(value, prob):
131
+ if isinstance(prob, list):
132
+ prob = np.array(prob).astype(np.float32)
133
+ prob /= prob.sum()
134
+ sampler = lambda : np.random.choice(value, replace=False, p=prob)
135
+ return sampler
136
+
137
+ class ScaledSampler:
138
+ def __init__(self, func_args, func='default'):
139
+ if func == 'default':
140
+ self.sampler_func = create_random_sampler(**func_args)
141
+ else:
142
+ raise NotImplementedError()
143
+ pass
144
+ def __call__(self, scaler=None, to_int=True):
145
+ value = self.sampler_func()
146
+ if scaler is not None:
147
+ value = scaler * value
148
+ if to_int:
149
+ value = int(round(value))
150
+ return value
151
+ pass
152
+
153
+ class RandColorSampler:
154
+ def __init__(self, func_args, func='default'):
155
+ if func == 'default':
156
+ self.sampler_func = create_random_sampler(**func_args)
157
+ else:
158
+ raise NotImplementedError()
159
+ pass
160
+ def __call__(self, scaler=None):
161
+ value = self.sampler_func()
162
+ if value == 'random':
163
+ return (random.randint(0,255), random.randint(0,255), random.randint(0,255), 255)
164
+ return value
165
+
166
+ class TextLinesSampler:
167
+ def __init__(self, page_size, sampler_dict):
168
+ self.page_w, self.page_h = page_size
169
+ self.lang = sampler_dict['lang']
170
+ self.lang_dict = load_dict(lang=self.lang)
171
+ self.orientation_sampler = ScaledSampler(sampler_dict['orientation'])
172
+ self.numlines_sampler = ScaledSampler(sampler_dict['num_lines'])
173
+ self.length_sampler = ScaledSampler(sampler_dict['length'])
174
+ self.min_num_lines = sampler_dict['min_num_lines']
175
+ self.min_length = sampler_dict['min_length']
176
+ self.alignment_sampler = create_random_sampler(**sampler_dict['alignment'])
177
+ self.rotation_sampler = create_random_sampler(**sampler_dict['rotation'])
178
+
179
+ def __call__(self, page_w=None, page_h=None, font_size=1):
180
+ if page_w == None:
181
+ page_w = self.page_w
182
+ if page_h == None:
183
+ page_h = self.page_h
184
+ orientation = self.orientation_sampler()
185
+ rotation = self.rotation_sampler()
186
+ if rotation != 0:
187
+ rotation = random.randint(-rotation, rotation)
188
+ num_lines = max(self.numlines_sampler(page_h/font_size), self.min_num_lines)
189
+ num_lines = random.randint(self.min_num_lines, num_lines)
190
+ max_length = max(self.length_sampler(page_h/font_size), self.min_length)
191
+
192
+ textlines = []
193
+ dict_len = len(self.lang_dict)
194
+ for ii in range(num_lines):
195
+ line = ''
196
+ length = random.randint(self.min_length, max_length)
197
+ for jj in range(length):
198
+ line += self.lang_dict[random.randrange(dict_len)] + ' '
199
+ textlines.append(line[:length])
200
+ return textlines, orientation, self.alignment_sampler(), rotation
201
+
202
+ class FontSampler:
203
+ def __init__(self, font_dict, page_size) -> None:
204
+ font_statics = font_dict['font_statics']
205
+ font_dir = font_dict['font_dir']
206
+ self.page_size = page_size
207
+
208
+ self.size_sampler = ScaledSampler(font_dict['size'])
209
+ self.color_sampler = RandColorSampler(font_dict['color'])
210
+ self.sw_sampler = ScaledSampler(font_dict['stroke_width'])
211
+
212
+ self.font_dir = font_dir
213
+ self.sampler_range = font_dict['num']
214
+ self.font_idx = 0
215
+
216
+ font_statics = pd.read_csv(font_statics)
217
+ self.font_list = list()
218
+ for fontname in font_statics['font']:
219
+ if osp.exists(osp.join(self.font_dir, fontname)):
220
+ self.font_list.append(fontname)
221
+ if len(self.font_list) >= self.sampler_range:
222
+ break
223
+ assert len(self.font_list) > 0
224
+
225
+ def __call__(self, page_size = None):
226
+ if page_size is None:
227
+ page_size = self.page_size
228
+ page_w, page_h = page_size
229
+ fontsize = self.size_sampler(page_h)
230
+ stroke_width = self.sw_sampler(fontsize)
231
+ color = self.color_sampler()
232
+ if color == 'black':
233
+ sw_color = (255, 255, 255, 255)
234
+ elif color == 'white':
235
+ sw_color = (0, 0, 0, 255)
236
+ else:
237
+ sw_color = self.color_sampler()
238
+ # while (True):
239
+ # self.font_idx = random.randrange(0, self.sampler_range)
240
+ # fontname = self.font_statics.iloc[self.font_idx]['font']
241
+ # font_path = osp.join(self.font_dir, fontname)
242
+ # if osp.exists(font_path):
243
+ # break
244
+ self.font_idx = random.randrange(0, self.sampler_range) % len(self.font_list)
245
+ font_path = osp.join(self.font_dir, self.font_list[self.font_idx])
246
+ font = ImageFont.truetype(font_path, fontsize)
247
+
248
+ return font, color, stroke_width, sw_color
249
+
250
+
251
+ class TextBlkSampler:
252
+ def __init__(self, page_size, max_tries, bboxlist=[]):
253
+ self.page_w, self.page_h = page_size
254
+ self.bboxlist = bboxlist
255
+ self.max_tries = max_tries
256
+ self.max_padding = int(round(0.05 * self.page_h))
257
+
258
+ def __call__(self, bbox_w, bbox_h, padding=0, page_size=None):
259
+ padding = int(round(padding))
260
+ if page_size is not None:
261
+ page_w, page_h = page_size
262
+ else:
263
+ page_w, page_h = self.page_w, self.page_h
264
+ padding = min(self.max_padding, padding)
265
+ bbox_w += 2*padding
266
+ bbox_h += 2*padding
267
+ x_range = page_w-bbox_w-1
268
+ y_range = page_h-bbox_h-1
269
+ if x_range < 0 or y_range < 0:
270
+ return None
271
+ for ii in range(self.max_tries):
272
+ x, y = random.randint(0, x_range), random.randint(0, y_range)
273
+ bbox_padded = [x, y, x + bbox_w, y + bbox_h]
274
+ collide = False
275
+ for bbox_exist in self.bboxlist:
276
+ if union_area(bbox_exist, bbox_padded) > 0:
277
+ collide = True
278
+ break
279
+ if not collide:
280
+ break
281
+ if not collide:
282
+ bbox = [bbox_padded[0]+padding, bbox_padded[1]+padding, bbox_padded[2]-padding, bbox_padded[3]-padding]
283
+ # bbox = [int(bb) for bb in bbox]
284
+ self.bboxlist.append(bbox)
285
+ return bbox
286
+ return None
287
+
288
+ def initialize(self, page_w, page_h, bboxlist=None, to_xywh=False):
289
+ if bboxlist is None:
290
+ self.bboxlist = []
291
+ else:
292
+ if to_xywh:
293
+ self.bboxlist = yolo_xywh2xyxy(bboxlist, page_w, page_h)
294
+ if self.bboxlist is not None:
295
+ self.bboxlist = self.bboxlist.tolist()
296
+ else:
297
+ self.bboxlist = []
298
+
299
+
300
+ LANG_DICT = {'en': 0, 'ja': 1}
301
+ def lang2cls(lang: str) -> int:
302
+ return LANG_DICT[lang]
303
+ def cls2lang(cls: int) -> str:
304
+ return list(LANG_DICT.keys())[cls]
305
+
306
+ def get_max_var_color(mean_bgcolor):
307
+ color_candidate = np.clip(np.array([mean_bgcolor-127, mean_bgcolor+127]), 0, 255).astype(np.int64)
308
+ max_var_color = [c[0] if abs(c[0]-mean_bgcolor[ii]) > abs(c[1]-mean_bgcolor[ii]) else c[1] for ii, c in enumerate(zip(color_candidate[0], color_candidate[1]))]
309
+ max_var_color = (max_var_color[0], max_var_color[1], max_var_color[2])
310
+ return max_var_color
311
+
312
+
313
+ class ComicTextSampler:
314
+ def __init__(self, page_size, sampler_dict, seed=None):
315
+ if seed is not None:
316
+ random.seed(seed)
317
+ np.random.seed(seed)
318
+ self.page_size = page_size
319
+ self.num_txtblk = sampler_dict['num_txtblk']
320
+ self.font_dict = sampler_dict['font']
321
+ self.text_dict = sampler_dict['text']
322
+
323
+ self.textlines_sampler = TextLinesSampler(page_size, sampler_dict['text'])
324
+ self.font_sampler = FontSampler(self.font_dict, self.page_size)
325
+ self.textblk_sampler = TextBlkSampler(page_size, max_tries=20)
326
+
327
+ self.lang = sampler_dict['text']['lang']
328
+
329
+ def drawtext_one_page(self, page_size=None, bboxlist=None, im_in=None, adaptive_color=False):
330
+ if page_size is not None:
331
+ page_w, page_h = page_size
332
+ else:
333
+ page_w, page_h = self.page_size
334
+ if im_in is None:
335
+ canvas = Image.new("RGBA", (page_w, page_h), 'white')
336
+ else:
337
+ canvas = Image.fromarray(cv2.cvtColor(im_in, cv2.COLOR_BGR2RGB))
338
+ page_w, page_h = canvas.width, canvas.height
339
+ canvas_msk = Image.new("L", (page_w, page_h), 'black')
340
+ canvas_draw = ImageDraw.Draw(canvas)
341
+ block_dicts = {}
342
+ yolo_labels = []
343
+ textpolylines = []
344
+ self.textblk_sampler.initialize(page_w, page_h, bboxlist, True)
345
+ for ii in range(self.num_txtblk):
346
+ font, color, stroke_width, sw_color = self.font_sampler(page_size=self.page_size)
347
+ textlines, orientation, alignment, rotation = self.textlines_sampler(font_size=font.size)
348
+ txtblk_img, txtblk_mask, textpolygons = draw_textblk(textlines, font, fill=color, stroke_width=stroke_width, stroke_fill=sw_color, orientation=orientation, alignment=alignment, rotation=rotation)
349
+ if txtblk_mask is None:
350
+ continue
351
+ bbox = self.textblk_sampler(txtblk_img.width, txtblk_img.height, font.size*1.2, page_size=(page_w, page_h))
352
+ if bbox is not None:
353
+ x1, y1, x2, y2 = bbox[0], bbox[1], bbox[0] + txtblk_mask.width, bbox[1] + txtblk_mask.height
354
+ re_draw = False
355
+ if im_in is not None:
356
+ mean_bgcolor = np.mean(im_in[y1: y2, x1: x2], axis=(0, 1))
357
+ max_var_color = get_max_var_color(mean_bgcolor)
358
+ # color_candidate = np.clip(np.array([mean_bgcolor-127, mean_bgcolor+127]), 0, 255).astype(np.int64)
359
+ # max_var_color = [c[0] if abs(c[0]-mean_bgcolor[ii]) > abs(c[1]-mean_bgcolor[ii]) else c[1] for ii, c in enumerate(zip(color_candidate[0], color_candidate[1]))]
360
+ # max_var_color = (max_var_color[0], max_var_color[1], max_var_color[2])
361
+ if color == 'black':
362
+ color_rep = np.array([0, 0, 0])
363
+ elif color == 'white':
364
+ color_rep = np.array([255, 255, 255])
365
+ else:
366
+ color_rep = np.array(color[:3])
367
+ color_var = np.sum(np.abs(mean_bgcolor - color_rep))
368
+ if not adaptive_color:
369
+ if color_var < 127:
370
+ color = max_var_color
371
+
372
+ sw_color = get_max_var_color(np.array(color))
373
+ re_draw = True
374
+ else:
375
+ color = max_var_color
376
+ sw_color = get_max_var_color(np.array(color))
377
+ re_draw = True
378
+ if stroke_width != 0 and im_in is not None:
379
+ # sw_color = get_max_var_color(color)
380
+ re_draw = True
381
+ if re_draw:
382
+ txtblk_img, txtblk_mask, textpolygons = draw_textblk(textlines, font, fill=color, stroke_width=stroke_width, stroke_fill=sw_color, orientation=orientation, alignment=alignment, rotation=rotation)
383
+ blk_dict = {
384
+ 'lang': self.lang,
385
+ 'lang_cls': lang2cls(self.lang),
386
+ 'xyxy': [x1, y1, x2, y2],
387
+ 'polylines': textpolygons
388
+ }
389
+ block_dicts[str(ii)+'-'+self.lang] = blk_dict
390
+ textpolygons[:, ::2] += x1
391
+ textpolygons[:, 1::2] += y1
392
+ textpolylines += textpolygons.astype(np.int64).tolist()
393
+ yolo_labels += [[x1, y1, x2, y2]]
394
+ canvas.paste(txtblk_img, (bbox[0], bbox[1]), mask=txtblk_mask)
395
+ canvas_msk.paste(txtblk_mask, (bbox[0], bbox[1]), mask=txtblk_mask)
396
+
397
+ rst = cv2.cvtColor(np.array(canvas), cv2.COLOR_RGB2BGR)
398
+ rst_msk = np.array(canvas_msk)
399
+ yolo_labels = xyxy2yolo(np.array(yolo_labels), page_w, page_h)
400
+ if yolo_labels is not None:
401
+ cls = np.ones((yolo_labels.shape[0], 1)) * lang2cls(self.lang)
402
+ yolo_labels = np.concatenate((cls, yolo_labels), axis=1)
403
+ return rst, rst_msk, block_dicts, yolo_labels, np.array(textpolylines)
404
+
405
+ def render_comictext(comic_sampler_list, img_dir, label_dir=None, render_num=700, save_dir=None, save_prefix=None, show=False):
406
+ if osp.exists(osp.join(img_dir, 'statistics.csv')):
407
+ statistics = pd.read_csv(osp.join(img_dir, 'statistics.csv'))
408
+ else:
409
+ statistics = None
410
+ imglist = find_all_imgs(img_dir)
411
+ # render_num = min(render_num, len(imglist))
412
+ num_im = len(imglist)
413
+ for ii in tqdm(range(render_num)):
414
+ im_idx = ii % num_im
415
+ if statistics is not None:
416
+ imgname = statistics.loc[im_idx]['name']
417
+ else:
418
+ imgname = imglist[im_idx]
419
+ img = imread(osp.join(img_dir, imgname))
420
+ cs_idx = ii % len(comic_sampler_list)
421
+ bboxlist = []
422
+ labels = None
423
+ if label_dir is not None:
424
+ labelname = imgname.replace(pathlib.Path(imgname).suffix, '.txt')
425
+ label_path = osp.join(label_dir, labelname)
426
+ labels = np.loadtxt(label_path)
427
+ if len(labels) != 0:
428
+ if len(labels.shape) == 1:
429
+ labels = np.array([labels])
430
+ clslist, bboxlist = labels[:, 0], np.copy(labels[:, 1:])
431
+ else:
432
+ labels = None
433
+ bboxlist = []
434
+ rst, rst_msk, block_dicts, yolo_labels, textpolylines = comic_sampler_list[cs_idx].drawtext_one_page(im_in=img, bboxlist=bboxlist, adaptive_color=True)
435
+ if save_dir is not None:
436
+ if save_prefix is not None:
437
+ save_name = save_prefix + '{0:09d}'.format(ii) + '.jpg'
438
+ else:
439
+ save_name = 'syn-' + imgname
440
+ yolo_save_path = osp.join(save_dir, save_name.replace(pathlib.Path(save_name).suffix, '.txt'))
441
+ content = ''
442
+ if yolo_labels is not None:
443
+ if labels is None:
444
+ content = get_yololabel_strings(yolo_labels[:, 0], yolo_labels[:, 1:])
445
+ else:
446
+ yolo_labels = np.concatenate((labels, yolo_labels))
447
+ content = get_yololabel_strings(yolo_labels[:, 0], yolo_labels[:, 1:])
448
+ if content == '' and label_dir is not None:
449
+ shutil.copy(label_path, yolo_save_path)
450
+ else:
451
+ with open(yolo_save_path, 'w', encoding='utf8') as f:
452
+ f.write(content)
453
+
454
+ linepoly_save_path = osp.join(save_dir, 'line-'+osp.basename(yolo_save_path))
455
+ np.savetxt(linepoly_save_path, textpolylines, fmt='%d')
456
+ imwrite(osp.join(save_dir, save_name), rst, ext='.jpg')
457
+ imwrite(osp.join(save_dir, 'mask-'+save_name), rst_msk)
458
+
459
+ if show:
460
+ for pts in textpolylines:
461
+ rst = cv2.polylines(rst, [np.array(pts).reshape((-1, 1, 2))], color=(255, 0, 0), isClosed=True, thickness=2)
462
+ cv2.imshow('rst', rst)
463
+ cv2.waitKey(0)
464
+
465
+
466
+ if __name__ == '__main__':
467
+
468
+ eng_sampler_dict = {
469
+ 'num_txtblk': 20,
470
+ 'font': {
471
+ 'font_dir': 'data/fonts',
472
+ 'font_statics': 'data/font_statics_en.csv',
473
+ 'num': 500,
474
+ 'size': {'value': [0.02, 0.03, 0.15],
475
+ 'prob': [1, 0.4, 0.15]},
476
+ 'stroke_width': {'value': [0, 0.1, 0.15],
477
+ 'prob': [1, 0.2, 0.2]},
478
+ 'color': {'value': ['black', 'random'],
479
+ 'prob': [1, 0.4]},
480
+ },
481
+ 'text': {
482
+ 'lang': 'en',
483
+ 'orientation': {'value': [1, 0],
484
+ 'prob': [0, 1]},
485
+ 'rotation': {'value': [0, 30, 60],
486
+ 'prob': [1, 0.3, 0.1]},
487
+ 'num_lines': {'value': [0.15],
488
+ 'prob': [1]},
489
+ 'length': {'value': [1],
490
+ 'prob': [1]},
491
+ 'min_num_lines': 1,
492
+ 'min_length': 3,
493
+ 'alignment': {'value': [ALIGN_LEFT, ALIGN_CENTER],
494
+ 'prob': [0.3, 1]}
495
+ }
496
+ }
497
+
498
+ ja_sampler_dict = {
499
+ 'num_txtblk': 20,
500
+ 'font': {
501
+ 'font_dir': 'data/fonts', # font file directory
502
+ 'font_statics': 'data/font_statics_jp.csv', # Just a font list to use, please create your own list and ignore the last two cols.
503
+ 'num': 500, # first 500 of the fontlist will be used
504
+ # params to
505
+ 'size': {'value': [0.02, 0.03, 0.15],
506
+ 'prob': [1, 0.4, 0.15]},
507
+ 'stroke_width': {'value': [0, 0.1, 0.15],
508
+ 'prob': [1, 0.5, 0.2]},
509
+ 'color': {'value': ['black', 'white', 'random'],
510
+ 'prob': [1, 1, 0.4]},
511
+ },
512
+ 'text': {
513
+ 'lang': 'ja', # render japanese, 'en' for english
514
+ 'orientation': {'value': [1, 0], # 1 is vertical text.
515
+ 'prob': [1, 0.3]},
516
+ 'rotation': {'value': [0, 30, 60],
517
+ 'prob': [1, 0.3, 0.1]},
518
+ 'num_lines': {'value': [0.15],
519
+ 'prob': [1]},
520
+ 'length': {'value': [0.3],
521
+ 'prob': [1]},
522
+ 'min_num_lines': 1,
523
+ 'min_length': 3,
524
+ 'alignment': {'value': [ALIGN_LEFT, ALIGN_CENTER],
525
+ 'prob': [0.3, 1]}
526
+ }
527
+ }
528
+
529
+
530
+
531
+ # random.seed(0)
532
+ # cts = ComicTextSampler((845, 1280), sampler_dict, seed=0)
533
+ # jp_cts = ComicTextSampler((845, 1280), ja_sampler_dict, seed=0)
534
+
535
+ # img_dir = r'../../datasets/pixanimegirls'
536
+ # save_dir = r'../../datasets/pixanimegirls/processed'
537
+ # os.makedirs(save_dir, exist_ok=True)
538
+
539
+ # img_dir = r'../../datasets/ComicErased'
540
+ # label_dir = img_dir
541
+ # save_dir = r'../../datasets/ComicErased/processed'
542
+ # os.makedirs(save_dir, exist_ok=True)
543
+ # render_comictext([jp_cts, cts], img_dir, save_dir=save_dir, save_prefix=None, render_num=4000, label_dir=None)
544
+
545
+
train_db.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.autograd.grad_mode import F
2
+ from torch.nn.functional import sigmoid
3
+ from torch.nn.modules.loss import CrossEntropyLoss
4
+ from torch.optim import SGD, Adam, lr_scheduler
5
+ from tqdm import tqdm
6
+ import math
7
+ from torch.cuda import amp
8
+ import torch
9
+ from utils.loss import DBLoss
10
+ import torch.nn as nn
11
+ import yaml
12
+ from basemodel import TextDetector
13
+ from utils.db_utils import SegDetectorRepresenter, QuadMetric
14
+ import numpy as np
15
+ from datetime import datetime
16
+ from torchsummary import summary
17
+ import numexpr
18
+ import os
19
+ import shutil
20
+ os.environ['NUMEXPR_MAX_THREADS'] = str(numexpr.detect_number_of_cores())
21
+
22
+ from db_dataset import create_dataloader
23
+ from utils.general import LOGGER, Loggers, CUDA, DEVICE
24
+ import time
25
+ import random
26
+
27
+ torch.random.manual_seed(0)
28
+ random.seed(0)
29
+ np.random.seed(0)
30
+
31
+ def one_cycle(y1=0.0, y2=1.0, steps=100):
32
+ return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
33
+
34
+ def eval_model(model: nn.Module, val_loader, post_process, metric_cls):
35
+ # global DEVICE
36
+ raw_metrics = []
37
+ total_frame = 0.0
38
+ total_time = 0.0
39
+ model.eval()
40
+ for i, batch in tqdm(enumerate(val_loader), total=len(val_loader), desc='test model'):
41
+ with torch.no_grad():
42
+ # 数据进行转换和丢到gpu
43
+ for key, value in batch.items():
44
+ if value is not None:
45
+ if isinstance(value, torch.Tensor):
46
+ batch[key] = value.to(DEVICE)
47
+ start = time.time()
48
+ with amp.autocast():
49
+ preds = model(batch['imgs'])
50
+ boxes, scores = post_process(batch, preds,is_output_polygon=False)
51
+ total_frame += batch['imgs'].size()[0]
52
+ total_time += time.time() - start
53
+ raw_metric = metric_cls.validate_measure(batch, (boxes, scores))
54
+ raw_metrics.append(raw_metric)
55
+ metrics = metric_cls.gather_measure(raw_metrics)
56
+ LOGGER.info('FPS:{}'.format(total_frame / total_time))
57
+ return metrics['recall'].avg, metrics['precision'].avg, metrics['fmeasure'].avg
58
+
59
+ def train(hyp):
60
+ start_epoch = 0
61
+ hyp_train, hyp_data, hyp_model, hyp_logger, hyp_resume = hyp['train'], hyp['data'], hyp['model'], hyp['logger'], hyp['resume']
62
+ epochs = hyp_train['epochs']
63
+ batch_size = hyp_train['batch_size']
64
+
65
+ scaler = amp.GradScaler(enabled=CUDA)
66
+ criterion = DBLoss()
67
+ use_bce = False
68
+ if hyp_train['loss'] == 'bce':
69
+ use_bce = True
70
+ shrink_with_sigmoid = not use_bce
71
+
72
+ model = TextDetector(hyp_model['weights'], map_location='cpu', act=hyp_model['act'])
73
+ model.initialize_db(hyp_model['unet_weights'])
74
+ model.dbnet.shrink_with_sigmoid = shrink_with_sigmoid
75
+ model.train_db()
76
+ model.to(DEVICE)
77
+
78
+ if hyp_model['db_weights'] != '':
79
+ model.dbnet.load_state_dict(torch.load(hyp_model['db_weights'])['weights'])
80
+ if hyp_train['optimizer'] == 'adam':
81
+ optimizer = Adam(model.dbnet.parameters(), lr=hyp_train['lr0'], betas=(0.937, 0.999), weight_decay=0.00002) # adjust beta1 to momentum
82
+ else:
83
+ optimizer = SGD(model.dbnet.parameters(), lr=hyp_train['lr0'], momentum=hyp_train['momentum'], nesterov=True, weight_decay=hyp_train['weight_decay'])
84
+
85
+ if hyp_train['linear_lr']:
86
+ lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp_train['lrf']) + hyp_train['lrf'] # linear
87
+ else:
88
+ lf = one_cycle(1, hyp_train['lrf'], epochs) # cosine 1->hyp['lrf']
89
+
90
+ if hyp_train['linear_lr']:
91
+ lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp_train['lrf']) + hyp_train['lrf'] # linear
92
+ else:
93
+ lf = one_cycle(1, hyp_train['lrf'], epochs) # cosine 1->hyp['lrf']
94
+ scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
95
+
96
+ logger = None
97
+ if hyp_resume['resume_training']:
98
+ LOGGER.info(f'resume traning ... ')
99
+ ckpt = torch.load(hyp_resume['ckpt'], map_location=DEVICE)
100
+ model.dbnet.load_state_dict(ckpt['weights'])
101
+ optimizer.load_state_dict(ckpt['optimizer'])
102
+ scheduler.load_state_dict(ckpt['scheduler'])
103
+ scheduler.step()
104
+ start_epoch = ckpt['epoch'] + 1
105
+ hyp_logger['run_id'] = ckpt['run_id']
106
+ logger = Loggers(hyp)
107
+
108
+ else:
109
+ # if hyp_logger['type'] == 'wandb':
110
+ logger = Loggers(hyp)
111
+
112
+ train_img_dir, train_mask_dir, imgsz, augment, aug_param = hyp_data['train_img_dir'], hyp_data['train_mask_dir'], hyp_data['imgsz'], hyp_data['augment'], hyp_data['aug_param']
113
+ val_img_dir, val_mask_dir = hyp_data['val_img_dir'], hyp_data['val_mask_dir']
114
+ train_dataset, train_loader = create_dataloader(train_img_dir, train_mask_dir, imgsz, batch_size, augment, aug_param, shuffle=True, workers=hyp_data['num_workers'], cache=hyp_data['cache'])
115
+ val_dataset, val_loader = create_dataloader(val_img_dir, val_mask_dir, imgsz, batch_size, augment=False, shuffle=False, workers=hyp_data['num_workers'], cache=hyp_data['cache'], with_ann=True)
116
+ nb = len(train_loader)
117
+ nw = max(round(3 * nb), 700)
118
+
119
+ LOGGER.info(f'num training imgs: {len(train_dataset)}, num val imgs: {len(val_dataset)}')
120
+
121
+ eval_interval = hyp_train['eval_interval']
122
+ best_f1 = best_epoch = -1
123
+ best_val_loss = np.inf
124
+
125
+ accumulation_steps = hyp_train['accumulation_steps']
126
+ summary(model, (3, 640, 640), device=DEVICE)
127
+ metric_cls = QuadMetric()
128
+ post_process = SegDetectorRepresenter(thresh=0.5)
129
+ best_f1 = -1
130
+ for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
131
+ model.train_db()
132
+ pbar = enumerate(train_loader)
133
+ pbar = tqdm(pbar, total=nb, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
134
+ m_loss = 0
135
+ m_loss_s = 0
136
+ m_loss_t = 0
137
+ m_loss_b = 0
138
+ for i, batchs in pbar:
139
+ if (i+2) % 256 == 0:
140
+ train_dataset.initialize()
141
+ pbar.set_description(f' training size: {train_dataset.img_size}')
142
+ # warm up
143
+ if hyp_train['warm_up']:
144
+ ni = i + nb * epoch
145
+ if ni <= nw:
146
+ xi = [0, nw] # x interp
147
+ for j, x in enumerate(optimizer.param_groups):
148
+ x['lr'] = np.interp(ni, xi, [hyp_train['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
149
+ if 'momentum' in x:
150
+ x['momentum'] = np.interp(ni, xi, [hyp_train['warmup_momentum'], hyp_train['momentum']])
151
+
152
+ with amp.autocast():
153
+ for key in batchs.keys():
154
+ batchs[key] = batchs[key].cuda()
155
+ preds = model(batchs['imgs'])
156
+ metric = criterion(preds, batchs, use_bce)
157
+ loss = metric['loss'] / accumulation_steps
158
+ scaler.scale(loss).backward()
159
+ if (i+1) % accumulation_steps == 0:
160
+ scaler.step(optimizer)
161
+ scaler.update()
162
+ optimizer.zero_grad()
163
+ m_loss = (m_loss * i + metric['loss'].detach()) / (i + 1)
164
+ m_loss_s = (m_loss_s * i + metric['loss_shrink_maps'].detach()) / (i + 1)
165
+ m_loss_t = (m_loss_t * i + metric['loss_threshold_maps'].detach()) / (i + 1)
166
+ m_loss_b = (m_loss_b * i + metric['loss_binary_maps'].detach()) / (i + 1)
167
+
168
+ if i % eval_interval == 0:
169
+ recall, precision, fmeasure = eval_model(model, val_loader, post_process, metric_cls)
170
+ log_dict = {}
171
+ log_dict['train/lr'] = optimizer.param_groups[0]['lr']
172
+ log_dict['train/loss'] = m_loss
173
+ log_dict['train/loss_shrink'] = m_loss_s
174
+ log_dict['train/loss_threshold'] = m_loss_t
175
+ log_dict['train/loss_binary_maps'] = m_loss_b
176
+ log_dict['eval/recall'] = recall
177
+ log_dict['eval/precision'] = precision
178
+ log_dict['eval/f1'] = fmeasure
179
+
180
+ save_best = best_f1 < fmeasure
181
+ if save_best:
182
+ best_f1 = fmeasure
183
+ last_ckpt = {'epoch': epoch,
184
+ 'best_f1': best_f1,
185
+ 'weights': model.dbnet.state_dict(),
186
+ 'best_val_loss': best_val_loss,
187
+ 'optimizer': optimizer.state_dict(),
188
+ 'scheduler': scheduler.state_dict(),
189
+ 'run_id': logger.wandb.id if logger.wandb is not None else None,
190
+ 'date': datetime.now().isoformat(),
191
+ 'hyp': hyp}
192
+ torch.save(last_ckpt, 'data/db_last.ckpt')
193
+ if save_best:
194
+ shutil.copy('data/db_last.ckpt', 'data/db_best.ckpt')
195
+ if logger is not None:
196
+ logger.on_train_epoch_end(epoch, log_dict)
197
+ scheduler.step()
198
+ pbar.close()
199
+
200
+ if __name__ == '__main__':
201
+ hyp_p = r'data/train_db_hyp.yaml'
202
+ with open(hyp_p, 'r', encoding='utf8') as f:
203
+ hyp = yaml.safe_load(f.read())
204
+
205
+ # hyp['data']['train_img_dir'] = r'../datasets/pixanimegirls/processed'
206
+ hyp['data']['train_img_dir'] = [r'../datasets/codat_manga_v3/images/train', r'../datasets/codat_manga_v3/images/val', r'../datasets/pixanimegirls/processed']
207
+ hyp['data']['train_mask_dir'] = r'../datasets/TextLines'
208
+ # hyp['data']['train_img_dir'] = r'data/dataset/db_sub'
209
+ hyp['data']['val_img_dir'] = r'data/dataset/db_sub'
210
+ hyp['data']['cache'] = False
211
+ # hyp['data']['aug_param']['size_range'] = [-1]
212
+
213
+ hyp['train']['lr0'] = 0.01
214
+ hyp['train']['lrf'] = 0.002
215
+ hyp['train']['weight_decay'] = 0.00002
216
+ hyp['train']['batch_size'] = 4
217
+ hyp['train']['epochs'] = 160
218
+ # hyp['train']['optimizer'] = 'sgd'
219
+
220
+ hyp['train']['loss'] = 'bce'
221
+ hyp['logger']['type'] = 'wandb'
222
+
223
+ # hyp['resume']['resume_training'] = True
224
+ # hyp['resume']['ckpt'] = 'data/db_last_bk.ckpt'
225
+ # hyp['model']['db_weights'] = r'data/db_last.ckpt'
226
+ train(hyp)
train_seg.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.optim import SGD, Adam, lr_scheduler
3
+ from tqdm import tqdm
4
+ import math
5
+ from torch.cuda import amp
6
+ import torch
7
+ from utils.loss import BinaryDiceLoss
8
+ import torch.nn as nn
9
+ import yaml
10
+ from basemodel import TextDetector
11
+ import numpy as np
12
+ from datetime import datetime
13
+ from torchsummary import summary
14
+ import numexpr
15
+ import os
16
+ import shutil
17
+ os.environ['NUMEXPR_MAX_THREADS'] = str(numexpr.detect_number_of_cores())
18
+
19
+ from seg_dataset import create_dataloader
20
+ from utils.general import LOGGER, Loggers, CUDA, DEVICE
21
+ import random
22
+
23
+ torch.random.manual_seed(0)
24
+ random.seed(0)
25
+ np.random.seed(0)
26
+
27
+
28
+ def one_cycle(y1=0.0, y2=1.0, steps=100):
29
+ return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
30
+
31
+ def eval_model(model: nn.Module, val_loader):
32
+ global DEVICE
33
+ loss_func = BinaryDiceLoss()
34
+ pbar = enumerate(val_loader)
35
+ nb = len(val_loader)
36
+ model.eval()
37
+ pbar = tqdm(pbar, total=nb, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
38
+ pr = tp = gt = m_loss = 0
39
+ with torch.no_grad():
40
+ for i, (imgs, masks) in pbar:
41
+ imgs = imgs.to(DEVICE)
42
+ masks = masks.to(DEVICE)
43
+ pred = model(imgs)
44
+ imgs.detach_()
45
+ del imgs
46
+ tp += torch.mul(pred, masks).sum().detach_()
47
+ gt += masks.sum().detach_()
48
+ pr += pred.sum().detach_()
49
+ loss = loss_func(pred, masks)
50
+ m_loss = (m_loss * i + loss.detach()) / (i + 1)
51
+ masks.detach_()
52
+ del masks
53
+ recall = tp / gt
54
+ precision = tp / pr
55
+ return recall, precision, m_loss
56
+
57
+ def train(hyp):
58
+ with open(r'data/training_hyp.yaml', 'w', encoding='utf8') as f:
59
+ yaml.safe_dump(hyp, f)
60
+ start_epoch = 0
61
+ hyp_train, hyp_data, hyp_model, hyp_logger, hyp_resume = hyp['train'], hyp['data'], hyp['model'], hyp['logger'], hyp['resume']
62
+ epochs = hyp_train['epochs']
63
+ batch_size = hyp_train['batch_size']
64
+ model = TextDetector(**hyp_model)
65
+ if CUDA:
66
+ model.cuda()
67
+ params = model.seg_net.parameters()
68
+
69
+ if hyp_train['optimizer'] == 'adam':
70
+ optimizer = Adam(params, lr=hyp_train['lr0'], betas=(hyp_train['momentum'], 0.999), weight_decay=hyp_train['weight_decay']) # adjust beta1 to momentum
71
+ else:
72
+ optimizer = SGD(params, lr=hyp_train['lr0'], momentum=hyp_train['momentum'], nesterov=True, weight_decay=hyp_train['weight_decay'])
73
+
74
+ if hyp_train['linear_lr']:
75
+ lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp_train['lrf']) + hyp_train['lrf'] # linear
76
+ else:
77
+ lf = one_cycle(1, hyp_train['lrf'], epochs) # cosine 1->hyp['lrf']
78
+
79
+ scaler = amp.GradScaler(enabled=CUDA)
80
+ loss_func = BinaryDiceLoss()
81
+
82
+ # Scheduler
83
+ if hyp_train['linear_lr']:
84
+ lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp_train['lrf']) + hyp_train['lrf'] # linear
85
+ else:
86
+ lf = one_cycle(1, hyp_train['lrf'], epochs) # cosine 1->hyp['lrf']
87
+ scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
88
+
89
+ logger = None
90
+ if hyp_resume['resume_training']:
91
+ LOGGER.info(f'resume traning ... ')
92
+ ckpt = torch.load(hyp_resume['ckpt'], map_location=DEVICE)
93
+ model.seg_net.load_state_dict(ckpt['weights'])
94
+ optimizer.load_state_dict(ckpt['optimizer'])
95
+ scheduler.load_state_dict(ckpt['scheduler'])
96
+ scheduler.step()
97
+ start_epoch = ckpt['epoch'] + 1
98
+ hyp_logger['run_id'] = ckpt['run_id']
99
+ logger = Loggers(hyp)
100
+
101
+ else:
102
+ if hyp_logger['type'] == 'wandb':
103
+ logger = Loggers(hyp)
104
+
105
+ num_workers = 8
106
+ train_img_dir, train_mask_dir, imgsz, augment, aug_param = hyp_data['train_img_dir'], hyp_data['train_mask_dir'], hyp_data['imgsz'], hyp_data['augment'], hyp_data['aug_param']
107
+ val_img_dir, val_mask_dir = hyp_data['val_img_dir'], hyp_data['val_mask_dir']
108
+ train_dataset, train_loader = create_dataloader(train_img_dir, train_mask_dir, imgsz, batch_size, augment, aug_param, shuffle=True, workers=num_workers, cache=hyp_data['cache'])
109
+ val_dataset, val_loader = create_dataloader(val_img_dir, val_mask_dir, imgsz, 4, augment=False, shuffle=False, workers=num_workers, cache=hyp_data['cache'])
110
+ nb = len(train_loader)
111
+ nw = max(round(3 * nb), 700)
112
+
113
+ LOGGER.info(f'num training imgs: {len(train_dataset)}, num val imgs: {len(val_dataset)}')
114
+
115
+ eval_interval = hyp_train['eval_interval']
116
+ best_f1 = -1
117
+ best_val_loss = np.inf
118
+ accumulation_steps = hyp_train['accumulation_steps']
119
+ summary(model, (3, 640, 640), device=DEVICE)
120
+ for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
121
+
122
+ model.train_mask()
123
+ train_dataset.initialize()
124
+ pbar = enumerate(train_loader)
125
+ pbar = tqdm(pbar, total=nb, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
126
+
127
+ m_loss = 0
128
+ for i, (imgs, masks) in pbar:
129
+
130
+ pbar.set_description(f' training size: {train_dataset.img_size}')
131
+ # warm up
132
+ ni = i + nb * epoch
133
+ if ni <= nw:
134
+ xi = [0, nw] # x interp
135
+ for j, x in enumerate(optimizer.param_groups):
136
+ x['lr'] = np.interp(ni, xi, [hyp_train['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
137
+ if 'momentum' in x:
138
+ x['momentum'] = np.interp(ni, xi, [hyp_train['warmup_momentum'], hyp_train['momentum']])
139
+
140
+ imgs, masks = imgs.to(DEVICE), masks.to(DEVICE)
141
+ with amp.autocast():
142
+ preds = model(imgs)
143
+ imgs.detach_()
144
+ del imgs
145
+ loss = loss_func(preds, masks)
146
+ masks.detach_()
147
+ del masks
148
+ scaler.scale(loss).backward()
149
+ if i % accumulation_steps == 0:
150
+ scaler.step(optimizer)
151
+ scaler.update()
152
+ optimizer.zero_grad()
153
+ m_loss = (m_loss * i + loss.detach()) / (i + 1)
154
+
155
+ if (epoch + 1) % eval_interval == 0:
156
+ recall, precision, eval_m_loss = eval_model(model, val_loader)
157
+ f1 = 2 * recall * precision / (recall + precision)
158
+ last_ckpt = {'epoch': epoch,
159
+ 'best_f1': best_f1,
160
+ 'weights': model.seg_net.state_dict(),
161
+ 'best_val_loss': best_val_loss,
162
+ 'optimizer': optimizer.state_dict(),
163
+ 'scheduler': scheduler.state_dict(),
164
+ 'run_id': logger.wandb.id if logger is not None else None,
165
+ 'date': datetime.now().isoformat(),
166
+ 'hyp': hyp}
167
+ torch.save(last_ckpt, 'data/unet_last.ckpt')
168
+ if best_f1 < f1:
169
+ best_f1 = f1
170
+ LOGGER.info(f'saving model at epoch {epoch}, best val f1: {best_f1}')
171
+ shutil.copy2('data/unet_last.ckpt', 'data/unet_best.ckpt')
172
+ LOGGER.info(f'epoch {epoch}/{epochs-1} loss: {m_loss} precision: {precision} recall: {recall}')
173
+ if logger is not None:
174
+ log_dict = {}
175
+ log_dict['train/lr'] = optimizer.param_groups[0]['lr']
176
+ log_dict['train/loss'] = m_loss
177
+ log_dict['eval/recall'] = recall
178
+ log_dict['eval/precision'] = precision
179
+ log_dict['eval/f1'] = f1
180
+ log_dict['eval/eval_m_loss'] = eval_m_loss
181
+ logger.on_train_epoch_end(epoch, log_dict)
182
+ scheduler.step()
183
+ pbar.close()
184
+
185
+ if __name__ == '__main__':
186
+ hyp_p = r'data/train_hyp.yaml'
187
+ with open(hyp_p, 'r', encoding='utf8') as f:
188
+ hyp = yaml.safe_load(f.read())
189
+
190
+ hyp['data']['train_img_dir'] = [r'../datasets/codat_manga_v3/images/train', r'../datasets/ComicErased/processed']
191
+ # hyp['data']['train_img_dir'] = [r'../datasets/codat_manga_v3/images/val']
192
+ hyp['data']['val_img_dir'] = [r'../datasets/codat_manga_v3/images/val']
193
+ hyp['data']['train_mask_dir'] = r'../datasets/ComicSegV2'
194
+ hyp['data']['val_mask_dir'] = r'../datasets/ComicSegV2'
195
+ hyp['data']['imgsz'] = 1024
196
+ hyp['data']['cache'] = False
197
+ hyp['data']['aug_param']['neg'] = 0.3
198
+ hyp['data']['aug_param']['size_range'] = [0.85, 1.1]
199
+
200
+ hyp['train']['lr0'] = 0.004
201
+ hyp['train']['lrf'] = 0.005
202
+ hyp['train']['weight_decay'] = 0.00002
203
+ hyp['train']['epochs'] = 120
204
+ hyp['train']['accumulation_steps'] = 4
205
+ hyp['train']['batch_size'] = 4
206
+ hyp['logger']['type'] = 'wandb'
207
+
208
+ # hyp['resume']['resume_training'] = True
209
+ # hyp['resume']['ckpt'] = 'data/unet_last.ckpt'
210
+ train(hyp)
utils/db_utils.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import pyclipper
4
+ from shapely.geometry import Polygon
5
+ from collections import namedtuple
6
+ import torch
7
+ import warnings
8
+ warnings.filterwarnings('ignore')
9
+
10
+
11
+ def iou_rotate(box_a, box_b, method='union'):
12
+ rect_a = cv2.minAreaRect(box_a)
13
+ rect_b = cv2.minAreaRect(box_b)
14
+ r1 = cv2.rotatedRectangleIntersection(rect_a, rect_b)
15
+ if r1[0] == 0:
16
+ return 0
17
+ else:
18
+ inter_area = cv2.contourArea(r1[1])
19
+ area_a = cv2.contourArea(box_a)
20
+ area_b = cv2.contourArea(box_b)
21
+ union_area = area_a + area_b - inter_area
22
+ if union_area == 0 or inter_area == 0:
23
+ return 0
24
+ if method == 'union':
25
+ iou = inter_area / union_area
26
+ elif method == 'intersection':
27
+ iou = inter_area / min(area_a, area_b)
28
+ else:
29
+ raise NotImplementedError
30
+ return iou
31
+
32
+ class SegDetectorRepresenter():
33
+ def __init__(self, thresh=0.3, box_thresh=0.7, max_candidates=1000, unclip_ratio=1.5):
34
+ self.min_size = 3
35
+ self.thresh = thresh
36
+ self.box_thresh = box_thresh
37
+ self.max_candidates = max_candidates
38
+ self.unclip_ratio = unclip_ratio
39
+
40
+ def __call__(self, batch, pred, is_output_polygon=False):
41
+ '''
42
+ batch: (image, polygons, ignore_tags
43
+ batch: a dict produced by dataloaders.
44
+ image: tensor of shape (N, C, H, W).
45
+ polygons: tensor of shape (N, K, 4, 2), the polygons of objective regions.
46
+ ignore_tags: tensor of shape (N, K), indicates whether a region is ignorable or not.
47
+ shape: the original shape of images.
48
+ filename: the original filenames of images.
49
+ pred:
50
+ binary: text region segmentation map, with shape (N, H, W)
51
+ thresh: [if exists] thresh hold prediction with shape (N, H, W)
52
+ thresh_binary: [if exists] binarized with threshold, (N, H, W)
53
+ '''
54
+ pred = pred[:, 0, :, :]
55
+ segmentation = self.binarize(pred)
56
+ boxes_batch = []
57
+ scores_batch = []
58
+ # print(pred.size())
59
+ batch_size = pred.size(0) if isinstance(pred, torch.Tensor) else pred.shape[0]
60
+ for batch_index in range(batch_size):
61
+ # height, width = batch['shape'][batch_index]
62
+ height, width = pred.shape[1], pred.shape[2]
63
+ if is_output_polygon:
64
+ boxes, scores = self.polygons_from_bitmap(pred[batch_index], segmentation[batch_index], width, height)
65
+ else:
66
+ boxes, scores = self.boxes_from_bitmap(pred[batch_index], segmentation[batch_index], width, height)
67
+ boxes_batch.append(boxes)
68
+ scores_batch.append(scores)
69
+ return boxes_batch, scores_batch
70
+
71
+ def binarize(self, pred):
72
+ return pred > self.thresh
73
+
74
+ def polygons_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
75
+ '''
76
+ _bitmap: single map with shape (H, W),
77
+ whose values are binarized as {0, 1}
78
+ '''
79
+
80
+ assert len(_bitmap.shape) == 2
81
+ bitmap = _bitmap.cpu().numpy() # The first channel
82
+ pred = pred.cpu().detach().numpy()
83
+ height, width = bitmap.shape
84
+ boxes = []
85
+ scores = []
86
+
87
+ contours, _ = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
88
+
89
+ for contour in contours[:self.max_candidates]:
90
+ epsilon = 0.005 * cv2.arcLength(contour, True)
91
+ approx = cv2.approxPolyDP(contour, epsilon, True)
92
+ points = approx.reshape((-1, 2))
93
+ if points.shape[0] < 4:
94
+ continue
95
+ # _, sside = self.get_mini_boxes(contour)
96
+ # if sside < self.min_size:
97
+ # continue
98
+ score = self.box_score_fast(pred, contour.squeeze(1))
99
+ if self.box_thresh > score:
100
+ continue
101
+
102
+ if points.shape[0] > 2:
103
+ box = self.unclip(points, unclip_ratio=self.unclip_ratio)
104
+ if len(box) > 1:
105
+ continue
106
+ else:
107
+ continue
108
+ box = box.reshape(-1, 2)
109
+ _, sside = self.get_mini_boxes(box.reshape((-1, 1, 2)))
110
+ if sside < self.min_size + 2:
111
+ continue
112
+
113
+ if not isinstance(dest_width, int):
114
+ dest_width = dest_width.item()
115
+ dest_height = dest_height.item()
116
+
117
+ box[:, 0] = np.clip(np.round(box[:, 0] / width * dest_width), 0, dest_width)
118
+ box[:, 1] = np.clip(np.round(box[:, 1] / height * dest_height), 0, dest_height)
119
+ boxes.append(box)
120
+ scores.append(score)
121
+ return boxes, scores
122
+
123
+ def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
124
+ '''
125
+ _bitmap: single map with shape (H, W),
126
+ whose values are binarized as {0, 1}
127
+ '''
128
+
129
+ assert len(_bitmap.shape) == 2
130
+ if isinstance(pred, torch.Tensor):
131
+ bitmap = _bitmap.cpu().numpy() # The first channel
132
+ pred = pred.cpu().detach().numpy()
133
+ else:
134
+ bitmap = _bitmap
135
+ height, width = bitmap.shape
136
+ contours, _ = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
137
+ num_contours = min(len(contours), self.max_candidates)
138
+ boxes = np.zeros((num_contours, 4, 2), dtype=np.int16)
139
+ scores = np.zeros((num_contours,), dtype=np.float32)
140
+
141
+ for index in range(num_contours):
142
+ contour = contours[index].squeeze(1)
143
+ points, sside = self.get_mini_boxes(contour)
144
+ # if sside < self.min_size:
145
+ # continue
146
+ if sside < 2:
147
+ continue
148
+ points = np.array(points)
149
+ score = self.box_score_fast(pred, contour)
150
+ # if self.box_thresh > score:
151
+ # continue
152
+
153
+ box = self.unclip(points, unclip_ratio=self.unclip_ratio).reshape(-1, 1, 2)
154
+ box, sside = self.get_mini_boxes(box)
155
+ # if sside < 5:
156
+ # continue
157
+ box = np.array(box)
158
+ if not isinstance(dest_width, int):
159
+ dest_width = dest_width.item()
160
+ dest_height = dest_height.item()
161
+
162
+ box[:, 0] = np.clip(np.round(box[:, 0] / width * dest_width), 0, dest_width)
163
+ box[:, 1] = np.clip(np.round(box[:, 1] / height * dest_height), 0, dest_height)
164
+ boxes[index, :, :] = box.astype(np.int16)
165
+ scores[index] = score
166
+ return boxes, scores
167
+
168
+ def unclip(self, box, unclip_ratio=1.5):
169
+ poly = Polygon(box)
170
+ distance = poly.area * unclip_ratio / poly.length
171
+ offset = pyclipper.PyclipperOffset()
172
+ offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
173
+ expanded = np.array(offset.Execute(distance))
174
+ return expanded
175
+
176
+ def get_mini_boxes(self, contour):
177
+ bounding_box = cv2.minAreaRect(contour)
178
+ points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
179
+
180
+ index_1, index_2, index_3, index_4 = 0, 1, 2, 3
181
+ if points[1][1] > points[0][1]:
182
+ index_1 = 0
183
+ index_4 = 1
184
+ else:
185
+ index_1 = 1
186
+ index_4 = 0
187
+ if points[3][1] > points[2][1]:
188
+ index_2 = 2
189
+ index_3 = 3
190
+ else:
191
+ index_2 = 3
192
+ index_3 = 2
193
+
194
+ box = [points[index_1], points[index_2], points[index_3], points[index_4]]
195
+ return box, min(bounding_box[1])
196
+
197
+ def box_score_fast(self, bitmap, _box):
198
+ h, w = bitmap.shape[:2]
199
+ box = _box.copy()
200
+ xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int64), 0, w - 1)
201
+ xmax = np.clip(np.ceil(box[:, 0].max()).astype(np.int64), 0, w - 1)
202
+ ymin = np.clip(np.floor(box[:, 1].min()).astype(np.int64), 0, h - 1)
203
+ ymax = np.clip(np.ceil(box[:, 1].max()).astype(np.int64), 0, h - 1)
204
+
205
+ mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
206
+ box[:, 0] = box[:, 0] - xmin
207
+ box[:, 1] = box[:, 1] - ymin
208
+ cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1)
209
+ if bitmap.dtype == np.float16:
210
+ bitmap = bitmap.astype(np.float32)
211
+ return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]
212
+
213
+ class AverageMeter(object):
214
+ """Computes and stores the average and current value"""
215
+
216
+ def __init__(self):
217
+ self.reset()
218
+
219
+ def reset(self):
220
+ self.val = 0
221
+ self.avg = 0
222
+ self.sum = 0
223
+ self.count = 0
224
+
225
+ def update(self, val, n=1):
226
+ self.val = val
227
+ self.sum += val * n
228
+ self.count += n
229
+ self.avg = self.sum / self.count
230
+ return self
231
+
232
+
233
+ class DetectionIoUEvaluator(object):
234
+ def __init__(self, is_output_polygon=False, iou_constraint=0.5, area_precision_constraint=0.5):
235
+ self.is_output_polygon = is_output_polygon
236
+ self.iou_constraint = iou_constraint
237
+ self.area_precision_constraint = area_precision_constraint
238
+
239
+ def evaluate_image(self, gt, pred):
240
+
241
+ def get_union(pD, pG):
242
+ return Polygon(pD).union(Polygon(pG)).area
243
+
244
+ def get_intersection_over_union(pD, pG):
245
+ return get_intersection(pD, pG) / get_union(pD, pG)
246
+
247
+ def get_intersection(pD, pG):
248
+ return Polygon(pD).intersection(Polygon(pG)).area
249
+
250
+ def compute_ap(confList, matchList, numGtCare):
251
+ correct = 0
252
+ AP = 0
253
+ if len(confList) > 0:
254
+ confList = np.array(confList)
255
+ matchList = np.array(matchList)
256
+ sorted_ind = np.argsort(-confList)
257
+ confList = confList[sorted_ind]
258
+ matchList = matchList[sorted_ind]
259
+ for n in range(len(confList)):
260
+ match = matchList[n]
261
+ if match:
262
+ correct += 1
263
+ AP += float(correct) / (n + 1)
264
+
265
+ if numGtCare > 0:
266
+ AP /= numGtCare
267
+
268
+ return AP
269
+
270
+ perSampleMetrics = {}
271
+
272
+ matchedSum = 0
273
+
274
+ Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax')
275
+
276
+ numGlobalCareGt = 0
277
+ numGlobalCareDet = 0
278
+
279
+ arrGlobalConfidences = []
280
+ arrGlobalMatches = []
281
+
282
+ recall = 0
283
+ precision = 0
284
+ hmean = 0
285
+
286
+ detMatched = 0
287
+
288
+ iouMat = np.empty([1, 1])
289
+
290
+ gtPols = []
291
+ detPols = []
292
+
293
+ gtPolPoints = []
294
+ detPolPoints = []
295
+
296
+ # Array of Ground Truth Polygons' keys marked as don't Care
297
+ gtDontCarePolsNum = []
298
+ # Array of Detected Polygons' matched with a don't Care GT
299
+ detDontCarePolsNum = []
300
+
301
+ pairs = []
302
+ detMatchedNums = []
303
+
304
+ arrSampleConfidences = []
305
+ arrSampleMatch = []
306
+
307
+ evaluationLog = ""
308
+
309
+ for n in range(len(gt)):
310
+ points = gt[n]['points']
311
+ # transcription = gt[n]['text']
312
+ dontCare = gt[n]['ignore']
313
+
314
+ if not Polygon(points).is_valid or not Polygon(points).is_simple:
315
+ continue
316
+
317
+ gtPol = points
318
+ gtPols.append(gtPol)
319
+ gtPolPoints.append(points)
320
+ if dontCare:
321
+ gtDontCarePolsNum.append(len(gtPols) - 1)
322
+
323
+ evaluationLog += "GT polygons: " + str(len(gtPols)) + (" (" + str(len(
324
+ gtDontCarePolsNum)) + " don't care)\n" if len(gtDontCarePolsNum) > 0 else "\n")
325
+
326
+ for n in range(len(pred)):
327
+ points = pred[n]['points']
328
+ if not Polygon(points).is_valid or not Polygon(points).is_simple:
329
+ continue
330
+
331
+ detPol = points
332
+ detPols.append(detPol)
333
+ detPolPoints.append(points)
334
+ if len(gtDontCarePolsNum) > 0:
335
+ for dontCarePol in gtDontCarePolsNum:
336
+ dontCarePol = gtPols[dontCarePol]
337
+ intersected_area = get_intersection(dontCarePol, detPol)
338
+ pdDimensions = Polygon(detPol).area
339
+ precision = 0 if pdDimensions == 0 else intersected_area / pdDimensions
340
+ if (precision > self.area_precision_constraint):
341
+ detDontCarePolsNum.append(len(detPols) - 1)
342
+ break
343
+
344
+ evaluationLog += "DET polygons: " + str(len(detPols)) + (" (" + str(len(
345
+ detDontCarePolsNum)) + " don't care)\n" if len(detDontCarePolsNum) > 0 else "\n")
346
+
347
+ if len(gtPols) > 0 and len(detPols) > 0:
348
+ # Calculate IoU and precision matrixs
349
+ outputShape = [len(gtPols), len(detPols)]
350
+ iouMat = np.empty(outputShape)
351
+ gtRectMat = np.zeros(len(gtPols), np.int8)
352
+ detRectMat = np.zeros(len(detPols), np.int8)
353
+ if self.is_output_polygon:
354
+ for gtNum in range(len(gtPols)):
355
+ for detNum in range(len(detPols)):
356
+ pG = gtPols[gtNum]
357
+ pD = detPols[detNum]
358
+ iouMat[gtNum, detNum] = get_intersection_over_union(pD, pG)
359
+ else:
360
+ # gtPols = np.float32(gtPols)
361
+ # detPols = np.float32(detPols)
362
+ for gtNum in range(len(gtPols)):
363
+ for detNum in range(len(detPols)):
364
+ pG = np.float32(gtPols[gtNum])
365
+ pD = np.float32(detPols[detNum])
366
+ iouMat[gtNum, detNum] = iou_rotate(pD, pG)
367
+ for gtNum in range(len(gtPols)):
368
+ for detNum in range(len(detPols)):
369
+ if gtRectMat[gtNum] == 0 and detRectMat[
370
+ detNum] == 0 and gtNum not in gtDontCarePolsNum and detNum not in detDontCarePolsNum:
371
+ if iouMat[gtNum, detNum] > self.iou_constraint:
372
+ gtRectMat[gtNum] = 1
373
+ detRectMat[detNum] = 1
374
+ detMatched += 1
375
+ pairs.append({'gt': gtNum, 'det': detNum})
376
+ detMatchedNums.append(detNum)
377
+ evaluationLog += "Match GT #" + \
378
+ str(gtNum) + " with Det #" + str(detNum) + "\n"
379
+
380
+ numGtCare = (len(gtPols) - len(gtDontCarePolsNum))
381
+ numDetCare = (len(detPols) - len(detDontCarePolsNum))
382
+ if numGtCare == 0:
383
+ recall = float(1)
384
+ precision = float(0) if numDetCare > 0 else float(1)
385
+ else:
386
+ recall = float(detMatched) / numGtCare
387
+ precision = 0 if numDetCare == 0 else float(
388
+ detMatched) / numDetCare
389
+
390
+ hmean = 0 if (precision + recall) == 0 else 2.0 * \
391
+ precision * recall / (precision + recall)
392
+
393
+ matchedSum += detMatched
394
+ numGlobalCareGt += numGtCare
395
+ numGlobalCareDet += numDetCare
396
+
397
+ perSampleMetrics = {
398
+ 'precision': precision,
399
+ 'recall': recall,
400
+ 'hmean': hmean,
401
+ 'pairs': pairs,
402
+ 'iouMat': [] if len(detPols) > 100 else iouMat.tolist(),
403
+ 'gtPolPoints': gtPolPoints,
404
+ 'detPolPoints': detPolPoints,
405
+ 'gtCare': numGtCare,
406
+ 'detCare': numDetCare,
407
+ 'gtDontCare': gtDontCarePolsNum,
408
+ 'detDontCare': detDontCarePolsNum,
409
+ 'detMatched': detMatched,
410
+ 'evaluationLog': evaluationLog
411
+ }
412
+
413
+ return perSampleMetrics
414
+
415
+ def combine_results(self, results):
416
+ numGlobalCareGt = 0
417
+ numGlobalCareDet = 0
418
+ matchedSum = 0
419
+ for result in results:
420
+ numGlobalCareGt += result['gtCare']
421
+ numGlobalCareDet += result['detCare']
422
+ matchedSum += result['detMatched']
423
+
424
+ methodRecall = 0 if numGlobalCareGt == 0 else float(
425
+ matchedSum) / numGlobalCareGt
426
+ methodPrecision = 0 if numGlobalCareDet == 0 else float(
427
+ matchedSum) / numGlobalCareDet
428
+ methodHmean = 0 if methodRecall + methodPrecision == 0 else 2 * \
429
+ methodRecall * methodPrecision / (
430
+ methodRecall + methodPrecision)
431
+
432
+ methodMetrics = {'precision': methodPrecision,
433
+ 'recall': methodRecall, 'hmean': methodHmean}
434
+
435
+ return methodMetrics
436
+
437
+ class QuadMetric():
438
+ def __init__(self, is_output_polygon=False):
439
+ self.is_output_polygon = is_output_polygon
440
+ self.evaluator = DetectionIoUEvaluator(is_output_polygon=is_output_polygon)
441
+
442
+ def measure(self, batch, output, box_thresh=0.6):
443
+ '''
444
+ batch: (image, polygons, ignore_tags
445
+ batch: a dict produced by dataloaders.
446
+ image: tensor of shape (N, C, H, W).
447
+ polygons: tensor of shape (N, K, 4, 2), the polygons of objective regions.
448
+ ignore_tags: tensor of shape (N, K), indicates whether a region is ignorable or not.
449
+ shape: the original shape of images.
450
+ filename: the original filenames of images.
451
+ output: (polygons, ...)
452
+ '''
453
+ results = []
454
+ gt_polyons_batch = batch['text_polys']
455
+ ignore_tags_batch = batch['ignore_tags']
456
+ pred_polygons_batch = np.array(output[0])
457
+ pred_scores_batch = np.array(output[1])
458
+ for polygons, pred_polygons, pred_scores, ignore_tags in zip(gt_polyons_batch, pred_polygons_batch, pred_scores_batch, ignore_tags_batch):
459
+ gt = [dict(points=np.int64(polygons[i]), ignore=ignore_tags[i]) for i in range(len(polygons))]
460
+ if self.is_output_polygon:
461
+ pred = [dict(points=pred_polygons[i]) for i in range(len(pred_polygons))]
462
+ else:
463
+ pred = []
464
+ # print(pred_polygons.shape)
465
+ for i in range(pred_polygons.shape[0]):
466
+ if pred_scores[i] >= box_thresh:
467
+ # print(pred_polygons[i,:,:].tolist())
468
+ pred.append(dict(points=pred_polygons[i, :, :].astype(np.int64)))
469
+ # pred = [dict(points=pred_polygons[i,:,:].tolist()) if pred_scores[i] >= box_thresh for i in range(pred_polygons.shape[0])]
470
+ results.append(self.evaluator.evaluate_image(gt, pred))
471
+ return results
472
+
473
+ def validate_measure(self, batch, output, box_thresh=0.6):
474
+ return self.measure(batch, output, box_thresh)
475
+
476
+ def evaluate_measure(self, batch, output):
477
+ return self.measure(batch, output), np.linspace(0, batch['image'].shape[0]).tolist()
478
+
479
+ def gather_measure(self, raw_metrics):
480
+ raw_metrics = [image_metrics
481
+ for batch_metrics in raw_metrics
482
+ for image_metrics in batch_metrics]
483
+
484
+ result = self.evaluator.combine_results(raw_metrics)
485
+
486
+ precision = AverageMeter()
487
+ recall = AverageMeter()
488
+ fmeasure = AverageMeter()
489
+
490
+ precision.update(result['precision'], n=len(raw_metrics))
491
+ recall.update(result['recall'], n=len(raw_metrics))
492
+ fmeasure_score = 2 * precision.val * recall.val / (precision.val + recall.val + 1e-8)
493
+ fmeasure.update(fmeasure_score)
494
+
495
+ return {
496
+ 'precision': precision,
497
+ 'recall': recall,
498
+ 'fmeasure': fmeasure
499
+ }
500
+
501
+ def shrink_polygon_py(polygon, shrink_ratio):
502
+ """
503
+ 对框进行缩放,返回去的比例为1/shrink_ratio 即可
504
+ """
505
+ cx = polygon[:, 0].mean()
506
+ cy = polygon[:, 1].mean()
507
+ polygon[:, 0] = cx + (polygon[:, 0] - cx) * shrink_ratio
508
+ polygon[:, 1] = cy + (polygon[:, 1] - cy) * shrink_ratio
509
+ return polygon
510
+
511
+
512
+ def shrink_polygon_pyclipper(polygon, shrink_ratio):
513
+ from shapely.geometry import Polygon
514
+ import pyclipper
515
+ polygon_shape = Polygon(polygon)
516
+ distance = polygon_shape.area * (1 - np.power(shrink_ratio, 2)) / polygon_shape.length
517
+ subject = [tuple(l) for l in polygon]
518
+ padding = pyclipper.PyclipperOffset()
519
+ padding.AddPath(subject, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
520
+ shrunk = padding.Execute(-distance)
521
+ if shrunk == []:
522
+ shrunk = np.array(shrunk)
523
+ else:
524
+ shrunk = np.array(shrunk[0]).reshape(-1, 2)
525
+ return shrunk
526
+
527
+ class MakeShrinkMap():
528
+ r'''
529
+ Making binary mask from detection data with ICDAR format.
530
+ Typically following the process of class `MakeICDARData`.
531
+ '''
532
+
533
+ def __init__(self, min_text_size=4, shrink_ratio=0.4, shrink_type='pyclipper'):
534
+ shrink_func_dict = {'py': shrink_polygon_py, 'pyclipper': shrink_polygon_pyclipper}
535
+ self.shrink_func = shrink_func_dict[shrink_type]
536
+ self.min_text_size = min_text_size
537
+ self.shrink_ratio = shrink_ratio
538
+
539
+ def __call__(self, data: dict) -> dict:
540
+ """
541
+ 从scales中随机选择一个尺度,对图片和文本框进行缩放
542
+ :param data: {'imgs':,'text_polys':,'texts':,'ignore_tags':}
543
+ :return:
544
+ """
545
+ image = data['imgs']
546
+ text_polys = data['text_polys']
547
+ ignore_tags = data['ignore_tags']
548
+
549
+ h, w = image.shape[:2]
550
+ text_polys, ignore_tags = self.validate_polygons(text_polys, ignore_tags, h, w)
551
+ gt = np.zeros((h, w), dtype=np.float32)
552
+ mask = np.ones((h, w), dtype=np.float32)
553
+ for i in range(len(text_polys)):
554
+ polygon = text_polys[i]
555
+ height = max(polygon[:, 1]) - min(polygon[:, 1])
556
+ width = max(polygon[:, 0]) - min(polygon[:, 0])
557
+ if ignore_tags[i] or min(height, width) < self.min_text_size:
558
+ cv2.fillPoly(mask, polygon.astype(np.int32)[np.newaxis, :, :], 0)
559
+ ignore_tags[i] = True
560
+ else:
561
+ shrunk = self.shrink_func(polygon, self.shrink_ratio)
562
+ if shrunk.size == 0:
563
+ cv2.fillPoly(mask, polygon.astype(np.int32)[np.newaxis, :, :], 0)
564
+ ignore_tags[i] = True
565
+ continue
566
+ cv2.fillPoly(gt, [shrunk.astype(np.int32)], 1)
567
+
568
+ data['shrink_map'] = gt
569
+ data['shrink_mask'] = mask
570
+ return data
571
+
572
+ def validate_polygons(self, polygons, ignore_tags, h, w):
573
+ '''
574
+ polygons (numpy.array, required): of shape (num_instances, num_points, 2)
575
+ '''
576
+ if len(polygons) == 0:
577
+ return polygons, ignore_tags
578
+ assert len(polygons) == len(ignore_tags)
579
+ for polygon in polygons:
580
+ polygon[:, 0] = np.clip(polygon[:, 0], 0, w - 1)
581
+ polygon[:, 1] = np.clip(polygon[:, 1], 0, h - 1)
582
+
583
+ for i in range(len(polygons)):
584
+ area = self.polygon_area(polygons[i])
585
+ if abs(area) < 1:
586
+ ignore_tags[i] = True
587
+ if area > 0:
588
+ polygons[i] = polygons[i][::-1, :]
589
+ return polygons, ignore_tags
590
+
591
+ def polygon_area(self, polygon):
592
+ return cv2.contourArea(polygon)
593
+
594
+
595
+ class MakeBorderMap():
596
+ def __init__(self, shrink_ratio=0.4, thresh_min=0.3, thresh_max=0.7):
597
+ self.shrink_ratio = shrink_ratio
598
+ self.thresh_min = thresh_min
599
+ self.thresh_max = thresh_max
600
+
601
+ def __call__(self, data: dict) -> dict:
602
+ """
603
+ 从scales中随机选择一个尺度,对图片和文本框进行缩放
604
+ :param data: {'imgs':,'text_polys':,'texts':,'ignore_tags':}
605
+ :return:
606
+ """
607
+ im = data['imgs']
608
+ text_polys = data['text_polys']
609
+ ignore_tags = data['ignore_tags']
610
+
611
+ canvas = np.zeros(im.shape[:2], dtype=np.float32)
612
+ mask = np.zeros(im.shape[:2], dtype=np.float32)
613
+
614
+ for i in range(len(text_polys)):
615
+ if ignore_tags[i]:
616
+ continue
617
+ self.draw_border_map(text_polys[i], canvas, mask=mask)
618
+ canvas = canvas * (self.thresh_max - self.thresh_min) + self.thresh_min
619
+
620
+ data['threshold_map'] = canvas
621
+ data['threshold_mask'] = mask
622
+ return data
623
+
624
+ def draw_border_map(self, polygon, canvas, mask):
625
+ polygon = np.array(polygon)
626
+ assert polygon.ndim == 2
627
+ assert polygon.shape[1] == 2
628
+
629
+ polygon_shape = Polygon(polygon)
630
+ if polygon_shape.area <= 0:
631
+ return
632
+ distance = polygon_shape.area * (1 - np.power(self.shrink_ratio, 2)) / polygon_shape.length
633
+ subject = [tuple(l) for l in polygon]
634
+ padding = pyclipper.PyclipperOffset()
635
+ padding.AddPath(subject, pyclipper.JT_ROUND,
636
+ pyclipper.ET_CLOSEDPOLYGON)
637
+
638
+ padded_polygon = np.array(padding.Execute(distance)[0])
639
+ cv2.fillPoly(mask, [padded_polygon.astype(np.int32)], 1.0)
640
+
641
+ xmin = padded_polygon[:, 0].min()
642
+ xmax = padded_polygon[:, 0].max()
643
+ ymin = padded_polygon[:, 1].min()
644
+ ymax = padded_polygon[:, 1].max()
645
+ width = xmax - xmin + 1
646
+ height = ymax - ymin + 1
647
+
648
+ polygon[:, 0] = polygon[:, 0] - xmin
649
+ polygon[:, 1] = polygon[:, 1] - ymin
650
+
651
+ xs = np.broadcast_to(
652
+ np.linspace(0, width - 1, num=width).reshape(1, width), (height, width))
653
+ ys = np.broadcast_to(
654
+ np.linspace(0, height - 1, num=height).reshape(height, 1), (height, width))
655
+
656
+ distance_map = np.zeros(
657
+ (polygon.shape[0], height, width), dtype=np.float32)
658
+ for i in range(polygon.shape[0]):
659
+ j = (i + 1) % polygon.shape[0]
660
+ absolute_distance = self.distance(xs, ys, polygon[i], polygon[j])
661
+ distance_map[i] = np.clip(absolute_distance / distance, 0, 1)
662
+ distance_map = distance_map.min(axis=0)
663
+
664
+ xmin_valid = min(max(0, xmin), canvas.shape[1] - 1)
665
+ xmax_valid = min(max(0, xmax), canvas.shape[1] - 1)
666
+ ymin_valid = min(max(0, ymin), canvas.shape[0] - 1)
667
+ ymax_valid = min(max(0, ymax), canvas.shape[0] - 1)
668
+ canvas[ymin_valid:ymax_valid + 1, xmin_valid:xmax_valid + 1] = np.fmax(
669
+ 1 - distance_map[
670
+ ymin_valid - ymin:ymax_valid - ymax + height,
671
+ xmin_valid - xmin:xmax_valid - xmax + width],
672
+ canvas[ymin_valid:ymax_valid + 1, xmin_valid:xmax_valid + 1])
673
+
674
+ def distance(self, xs, ys, point_1, point_2):
675
+ '''
676
+ compute the distance from point to a line
677
+ ys: coordinates in the first axis
678
+ xs: coordinates in the second axis
679
+ point_1, point_2: (x, y), the end of the line
680
+ '''
681
+ height, width = xs.shape[:2]
682
+ square_distance_1 = np.square(xs - point_1[0]) + np.square(ys - point_1[1])
683
+ square_distance_2 = np.square(xs - point_2[0]) + np.square(ys - point_2[1])
684
+ square_distance = np.square(point_1[0] - point_2[0]) + np.square(point_1[1] - point_2[1])
685
+
686
+ cosin = (square_distance - square_distance_1 - square_distance_2) / (2 * np.sqrt(square_distance_1 * square_distance_2))
687
+ square_sin = 1 - np.square(cosin)
688
+ square_sin = np.nan_to_num(square_sin)
689
+
690
+ result = np.sqrt(square_distance_1 * square_distance_2 * square_sin / square_distance)
691
+ result[cosin < 0] = np.sqrt(np.fmin(square_distance_1, square_distance_2))[cosin < 0]
692
+ return result
693
+
694
+ def extend_line(self, point_1, point_2, result):
695
+ ex_point_1 = (int(round(point_1[0] + (point_1[0] - point_2[0]) * (1 + self.shrink_ratio))),
696
+ int(round(point_1[1] + (point_1[1] - point_2[1]) * (1 + self.shrink_ratio))))
697
+ cv2.line(result, tuple(ex_point_1), tuple(point_1), 4096.0, 1, lineType=cv2.LINE_AA, shift=0)
698
+ ex_point_2 = (int(round(point_2[0] + (point_2[0] - point_1[0]) * (1 + self.shrink_ratio))),
699
+ int(round(point_2[1] + (point_2[1] - point_1[1]) * (1 + self.shrink_ratio))))
700
+ cv2.line(result, tuple(ex_point_2), tuple(point_2), 4096.0, 1, lineType=cv2.LINE_AA, shift=0)
701
+ return ex_point_1, ex_point_2
utils/export.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from cv2 import imshow
3
+ from matplotlib import lines
4
+ import numpy as np
5
+ import onnxruntime
6
+ import cv2
7
+ import torch
8
+ import onnx
9
+ from basemodel import TextDetBase
10
+ import onnxsim
11
+ from models.yolov5.common import Conv
12
+ from models.yolov5.yolo import Detect
13
+ import torch.nn as nn
14
+ import time
15
+ from seg_dataset import letterbox
16
+ from utils.yolov5_utils import fuse_conv_and_bn
17
+
18
+ class SiLU(nn.Module): # export-friendly version of nn.SiLU()
19
+ @staticmethod
20
+ def forward(x):
21
+ return x * torch.sigmoid(x)
22
+
23
+ def concate_models(blk_weights, seg_weights, det_weights, save_path):
24
+ textdetector_dict = dict()
25
+ textdetector_dict['blk_det'] = torch.load(blk_weights, map_location='cpu')
26
+ textdetector_dict['text_seg'] = torch.load(seg_weights, map_location='cpu')['weights']
27
+ textdetector_dict['text_det'] = torch.load(det_weights, map_location='cpu')['weights']
28
+ torch.save(textdetector_dict, save_path)
29
+
30
+ def export_onnx(model, im, file, opset, train=False, simplify=True, dynamic=False, inplace=False):
31
+ # YOLOv5 ONNX export
32
+ f = file + '.onnx'
33
+ for k, m in model.named_modules():
34
+ if isinstance(m, Conv): # assign export-friendly activations
35
+ if isinstance(m.act, nn.SiLU):
36
+ m.act = SiLU()
37
+ elif isinstance(m, Detect):
38
+ m.inplace = inplace
39
+ m.onnx_dynamic = False
40
+ torch.onnx.export(model, im, f, verbose=False, opset_version=opset,
41
+ training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
42
+ do_constant_folding=not train,
43
+ input_names=['images'],
44
+ output_names=['blk', 'seg', 'det'],
45
+ dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
46
+ 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
47
+ } if dynamic else None)
48
+
49
+ # Checks
50
+ model_onnx = onnx.load(f) # load onnx model
51
+ onnx.checker.check_model(model_onnx) # check onnx model
52
+
53
+ model_onnx, check = onnxsim.simplify(
54
+ model_onnx,
55
+ dynamic_input_shape=dynamic,
56
+ input_shapes={'images': list(im.shape)} if dynamic else None)
57
+ assert check, 'assert check failed'
58
+ onnx.save(model_onnx, f)
utils/general.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import logging
4
+ import wandb
5
+ import torch
6
+
7
+ def set_logging(name=None, verbose=True):
8
+ for handler in logging.root.handlers[:]:
9
+ logging.root.removeHandler(handler)
10
+ # Sets level and returns logger
11
+ rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings
12
+ logging.basicConfig(format="%(message)s", level=logging.INFO if (verbose and rank in (-1, 0)) else logging.WARNING)
13
+ return logging.getLogger(name)
14
+
15
+ LOGGER = set_logging(__name__) # define globally (used in train.py, val.py, detect.py, etc.)
16
+
17
+ LOGGERS = ('csv', 'tb', 'wandb')
18
+
19
+ CUDA = True if torch.cuda.is_available() else False
20
+ DEVICE = 'cuda' if CUDA else 'cpu'
21
+
22
+ LOGGER_WANDB = 'wandb'
23
+ LOGGER_TENSORBOARD = 'tb'
24
+
25
+
26
+ class Loggers():
27
+ def __init__(self, hyp):
28
+ self.type = hyp['logger']['type']
29
+ self.epochs = hyp['train']['epochs']
30
+ self.wandb = None
31
+ self.writer = None
32
+ if self.type == LOGGER_WANDB:
33
+ if hyp['logger']['project'] == '':
34
+ project = 'ComicTextDetector'
35
+ else:
36
+ project = hyp['logger']['project']
37
+ if hyp['logger']['run_id'] == '':
38
+ self.wandb = wandb.init(project=project, config=hyp, resume='allow')
39
+ else:
40
+ self.wandb = wandb.init(project=project, config=hyp, resume='must', id=hyp['logger']['run_id'])
41
+ elif self.type == LOGGER_TENSORBOARD:
42
+ from torch.utils.tensorboard import SummaryWriter
43
+ self.writer = SummaryWriter(hyp['data']['save_dir'])
44
+
45
+ def on_train_batch_end(self, metrics):
46
+ # Callback runs on train batch end
47
+ if self.wandb:
48
+ self.wandb.log(metrics)
49
+ pass
50
+
51
+ def on_train_epoch_end(self, epoch, metrics):
52
+ LOGGER.info(f'fin epoch {epoch}/{self.epochs}, metrics: {metrics}')
53
+ if self.type == LOGGER_WANDB:
54
+ self.wandb.log(metrics)
55
+ elif self.type == LOGGER_TENSORBOARD:
56
+ for key in metrics.keys():
57
+ self.writer.add_scalar(key, metrics[key], epoch)
58
+
59
+ def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
60
+ # Callback runs on model save event
61
+ if self.wandb:
62
+ if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1:
63
+ self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)
64
+
65
+
utils/imgproc_utils.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ import random
4
+
5
+ def hex2bgr(hex):
6
+ gmask = 254 << 8
7
+ rmask = 254
8
+ b = hex >> 16
9
+ g = (hex & gmask) >> 8
10
+ r = hex & rmask
11
+ return np.stack([b, g, r]).transpose()
12
+
13
+ def union_area(bboxa, bboxb):
14
+ x1 = max(bboxa[0], bboxb[0])
15
+ y1 = max(bboxa[1], bboxb[1])
16
+ x2 = min(bboxa[2], bboxb[2])
17
+ y2 = min(bboxa[3], bboxb[3])
18
+ if y2 < y1 or x2 < x1:
19
+ return -1
20
+ return (y2 - y1) * (x2 - x1)
21
+
22
+ def get_yololabel_strings(clslist, labellist):
23
+ content = ''
24
+ for cls, xywh in zip(clslist, labellist):
25
+ content += str(int(cls)) + ' ' + ' '.join([str(e) for e in xywh]) + '\n'
26
+ if len(content) != 0:
27
+ content = content[:-1]
28
+ return content
29
+
30
+ # 4 points bbox to 8 points polygon
31
+ def xywh2xyxypoly(xywh, to_int=True):
32
+ xyxypoly = np.tile(xywh[:, [0, 1]], 4)
33
+ xyxypoly[:, [2, 4]] += xywh[:, [2]]
34
+ xyxypoly[:, [5, 7]] += xywh[:, [3]]
35
+ if to_int:
36
+ xyxypoly = xyxypoly.astype(np.int64)
37
+ return xyxypoly
38
+
39
+ def xyxy2yolo(xyxy, w: int, h: int):
40
+ if xyxy == [] or len(xyxy) == 0:
41
+ return None
42
+ if isinstance(xyxy, list):
43
+ xyxy = np.array(xyxy)
44
+ if len(xyxy.shape) == 1:
45
+ xyxy = np.array([xyxy])
46
+ yolo = np.copy(xyxy).astype(np.float64)
47
+ yolo[:, [0, 2]] = yolo[:, [0, 2]] / w
48
+ yolo[:, [1, 3]] = yolo[:, [1, 3]] / h
49
+ yolo[:, [2, 3]] -= yolo[:, [0, 1]]
50
+ yolo[:, [0, 1]] += yolo[:, [2, 3]] / 2
51
+ return yolo
52
+
53
+ def yolo_xywh2xyxy(xywh: np.array, w: int, h: int, to_int=True):
54
+ if xywh is None:
55
+ return None
56
+ if len(xywh) == 0:
57
+ return None
58
+ if len(xywh.shape) == 1:
59
+ xywh = np.array([xywh])
60
+ xywh[:, [0, 2]] *= w
61
+ xywh[:, [1, 3]] *= h
62
+ xywh[:, [0, 1]] -= xywh[:, [2, 3]] / 2
63
+ xywh[:, [2, 3]] += xywh[:, [0, 1]]
64
+ if to_int:
65
+ xywh = xywh.astype(np.int64)
66
+ return xywh
67
+
68
+ def rotate_polygons(center, polygons, rotation, new_center=None, to_int=True):
69
+ if new_center is None:
70
+ new_center = center
71
+ rotation = np.deg2rad(rotation)
72
+ s, c = np.sin(rotation), np.cos(rotation)
73
+ polygons = polygons.astype(np.float32)
74
+
75
+ polygons[:, 1::2] -= center[1]
76
+ polygons[:, ::2] -= center[0]
77
+ rotated = np.copy(polygons)
78
+ rotated[:, 1::2] = polygons[:, 1::2] * c - polygons[:, ::2] * s
79
+ rotated[:, ::2] = polygons[:, 1::2] * s + polygons[:, ::2] * c
80
+ rotated[:, 1::2] += new_center[1]
81
+ rotated[:, ::2] += new_center[0]
82
+ if to_int:
83
+ return rotated.astype(np.int64)
84
+ return rotated
85
+
86
+ def letterbox(im, new_shape=(640, 640), color=(0, 0, 0), auto=False, scaleFill=False, scaleup=True, stride=128):
87
+ # Resize and pad image while meeting stride-multiple constraints
88
+ shape = im.shape[:2] # current shape [height, width]
89
+ if not isinstance(new_shape, tuple):
90
+ new_shape = (new_shape, new_shape)
91
+
92
+ # Scale ratio (new / old)
93
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
94
+ if not scaleup: # only scale down, do not scale up (for better val mAP)
95
+ r = min(r, 1.0)
96
+
97
+ # Compute padding
98
+ ratio = r, r # width, height ratios
99
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
100
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
101
+ if auto: # minimum rectangle
102
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
103
+ elif scaleFill: # stretch
104
+ dw, dh = 0.0, 0.0
105
+ new_unpad = (new_shape[1], new_shape[0])
106
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
107
+
108
+ # dw /= 2 # divide padding into 2 sides
109
+ # dh /= 2
110
+ dh, dw = int(dh), int(dw)
111
+
112
+ if shape[::-1] != new_unpad: # resize
113
+ im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
114
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
115
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
116
+ im = cv2.copyMakeBorder(im, 0, dh, 0, dw, cv2.BORDER_CONSTANT, value=color) # add border
117
+ return im, ratio, (dw, dh)
118
+
119
+ def resize_keepasp(im, new_shape=640, scaleup=True, interpolation=cv2.INTER_LINEAR, stride=None):
120
+ shape = im.shape[:2] # current shape [height, width]
121
+
122
+ if new_shape is not None:
123
+ if not isinstance(new_shape, tuple):
124
+ new_shape = (new_shape, new_shape)
125
+ else:
126
+ new_shape = shape
127
+
128
+ # Scale ratio (new / old)
129
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
130
+ if not scaleup: # only scale down, do not scale up (for better val mAP)
131
+ r = min(r, 1.0)
132
+
133
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
134
+
135
+ if stride is not None:
136
+ h, w = new_unpad
137
+ if new_shape[0] % stride != 0 :
138
+ new_h = (stride - (new_shape[0] % stride)) + h
139
+ else :
140
+ new_h = h
141
+ if w % stride != 0 :
142
+ new_w = (stride - (w % stride)) + w
143
+ else :
144
+ new_w = w
145
+ new_unpad = (new_h, new_w)
146
+
147
+ if shape[::-1] != new_unpad: # resize
148
+ im = cv2.resize(im, new_unpad, interpolation=interpolation)
149
+ return im
150
+
151
+ def expand_textwindow(img_size, xyxy, expand_r=8, shrink=False):
152
+ im_h, im_w = img_size[:2]
153
+ x1, y1 , x2, y2 = xyxy
154
+ w = x2 - x1
155
+ h = y2 - y1
156
+ paddings = int(round((max(h, w) * 0.25 + min(h, w) * 0.75) / expand_r))
157
+ if shrink:
158
+ paddings *= -1
159
+ x1, y1 = max(0, x1 - paddings), max(0, y1 - paddings)
160
+ x2, y2 = min(im_w-1, x2+paddings), min(im_h-1, y2+paddings)
161
+ return [x1, y1, x2, y2]
162
+
163
+ def draw_connected_labels(num_labels, labels, stats, centroids, names="draw_connected_labels", skip_background=True):
164
+ labdraw = np.zeros((labels.shape[0], labels.shape[1], 3), dtype=np.uint8)
165
+ max_ind = 0
166
+ if isinstance(num_labels, int):
167
+ num_labels = range(num_labels)
168
+
169
+ # for ind, lab in enumerate((range(num_labels))):
170
+ for lab in num_labels:
171
+ if skip_background and lab == 0:
172
+ continue
173
+ randcolor = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
174
+ labdraw[np.where(labels==lab)] = randcolor
175
+ maxr, minr = 0.5, 0.001
176
+ maxw, maxh = stats[max_ind][2] * maxr, stats[max_ind][3] * maxr
177
+ minarea = labdraw.shape[0] * labdraw.shape[1] * minr
178
+
179
+ stat = stats[lab]
180
+ bboxarea = stat[2] * stat[3]
181
+ if stat[2] < maxw and stat[3] < maxh and bboxarea > minarea:
182
+ pix = np.zeros((labels.shape[0], labels.shape[1]), dtype=np.uint8)
183
+ pix[np.where(labels==lab)] = 255
184
+
185
+ rect = cv2.minAreaRect(cv2.findNonZero(pix))
186
+ box = np.int0(cv2.boxPoints(rect))
187
+ labdraw = cv2.drawContours(labdraw, [box], 0, randcolor, 2)
188
+ labdraw = cv2.circle(labdraw, (int(centroids[lab][0]),int(centroids[lab][1])), radius=5, color=(random.randint(0,255), random.randint(0,255), random.randint(0,255)), thickness=-1)
189
+
190
+ cv2.imshow(names, labdraw)
191
+ return labdraw
192
+
utils/io_utils.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os.path as osp
3
+ import glob
4
+ from pathlib import Path
5
+ import cv2
6
+ import numpy as np
7
+ import json
8
+
9
+ IMG_EXT = ['.bmp', '.jpg', '.png', '.jpeg']
10
+
11
+ NP_BOOL_TYPES = (np.bool_, np.bool8)
12
+ NP_FLOAT_TYPES = (np.float_, np.float16, np.float32, np.float64)
13
+ NP_INT_TYPES = (np.int_, np.int8, np.int16, np.int32, np.int64, np.uint, np.uint8, np.uint16, np.uint32, np.uint64)
14
+
15
+ # https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable
16
+ class NumpyEncoder(json.JSONEncoder):
17
+ def default(self, obj):
18
+ if isinstance(obj, np.ndarray):
19
+ return obj.tolist()
20
+ elif isinstance(obj, np.ScalarType):
21
+ if isinstance(obj, NP_BOOL_TYPES):
22
+ return bool(obj)
23
+ elif isinstance(obj, NP_FLOAT_TYPES):
24
+ return float(obj)
25
+ elif isinstance(obj, NP_INT_TYPES):
26
+ return int(obj)
27
+ return json.JSONEncoder.default(self, obj)
28
+
29
+ def find_all_imgs(img_dir, abs_path=False):
30
+ imglist = list()
31
+ for filep in glob.glob(osp.join(img_dir, "*")):
32
+ filename = osp.basename(filep)
33
+ file_suffix = Path(filename).suffix
34
+ if file_suffix.lower() not in IMG_EXT:
35
+ continue
36
+ if abs_path:
37
+ imglist.append(filep)
38
+ else:
39
+ imglist.append(filename)
40
+ return imglist
41
+
42
+ imread = lambda imgpath, read_type=cv2.IMREAD_COLOR: cv2.imdecode(np.fromfile(imgpath, dtype=np.uint8), read_type)
43
+ # def imread(imgpath, read_type=cv2.IMREAD_COLOR):
44
+ # img = cv2.imdecode(np.fromfile(imgpath, dtype=np.uint8), read_type)
45
+ # return img
46
+
47
+ def imwrite(img_path, img, ext='.png'):
48
+ suffix = Path(img_path).suffix
49
+ if suffix != '':
50
+ img_path = img_path.replace(suffix, ext)
51
+ else:
52
+ img_path += ext
53
+ cv2.imencode(ext, img)[1].tofile(img_path)
utils/loss.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ """Modified from https://github.com/LikeLy-Journey/SegmenTron/blob/master/
3
+ segmentron/solver/loss.py (Apache-2.0 License)"""
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from torch.nn.modules.loss import BCEWithLogitsLoss
8
+
9
+
10
+ class BinaryDiceLoss(nn.Module):
11
+ """Dice loss of binary class
12
+ Args:
13
+ smooth: A float number to smooth loss, and avoid NaN error, default: 1
14
+ p: Denominator value: \sum{x^p} + \sum{y^p}, default: 2
15
+ predict: A tensor of shape [N, *]
16
+ target: A tensor of shape same with predict
17
+ reduction: Reduction method to apply, return mean over batch if 'mean',
18
+ return sum if 'sum', return a tensor of shape [N,] if 'none'
19
+ Returns:
20
+ Loss tensor according to arg reduction
21
+ Raise:
22
+ Exception if unexpected reduction
23
+ """
24
+ def __init__(self, smooth=1, p=2, reduction='mean'):
25
+ super(BinaryDiceLoss, self).__init__()
26
+ self.smooth = smooth
27
+ self.p = p
28
+ self.reduction = reduction
29
+
30
+ def forward(self, predict, target):
31
+ assert predict.shape[0] == target.shape[0], "predict & target batch size don't match"
32
+ predict = predict.contiguous().view(predict.shape[0], -1)
33
+ target = target.contiguous().view(target.shape[0], -1)
34
+
35
+ num = torch.sum(torch.mul(predict, target), dim=1) + self.smooth
36
+ den = torch.sum(predict.pow(self.p) + target.pow(self.p), dim=1) + self.smooth
37
+
38
+ loss = 1 - num / den
39
+
40
+ if self.reduction == 'mean':
41
+ return loss.mean()
42
+ elif self.reduction == 'sum':
43
+ return loss.sum()
44
+ elif self.reduction == 'none':
45
+ return loss
46
+ else:
47
+ raise Exception('Unexpected reduction {}'.format(self.reduction))
48
+
49
+
50
+ class BalanceCrossEntropyLoss(nn.Module):
51
+ '''
52
+ Balanced cross entropy loss.
53
+ Shape:
54
+ - Input: :math:`(N, 1, H, W)`
55
+ - GT: :math:`(N, 1, H, W)`, same shape as the input
56
+ - Mask: :math:`(N, H, W)`, same spatial shape as the input
57
+ - Output: scalar.
58
+
59
+ Examples::
60
+
61
+ >>> m = nn.Sigmoid()
62
+ >>> loss = nn.BCELoss()
63
+ >>> input = torch.randn(3, requires_grad=True)
64
+ >>> target = torch.empty(3).random_(2)
65
+ >>> output = loss(m(input), target)
66
+ >>> output.backward()
67
+ '''
68
+
69
+ def __init__(self, negative_ratio=3.0, eps=1e-6):
70
+ super(BalanceCrossEntropyLoss, self).__init__()
71
+ self.negative_ratio = negative_ratio
72
+ self.eps = eps
73
+
74
+ def forward(self,
75
+ pred: torch.Tensor,
76
+ gt: torch.Tensor,
77
+ mask: torch.Tensor,
78
+ return_origin=False):
79
+ '''
80
+ Args:
81
+ pred: shape :math:`(N, 1, H, W)`, the prediction of network
82
+ gt: shape :math:`(N, 1, H, W)`, the target
83
+ mask: shape :math:`(N, H, W)`, the mask indicates positive regions
84
+ '''
85
+ positive = (gt * mask).byte()
86
+ negative = ((1 - gt) * mask).byte()
87
+ positive_count = int(positive.float().sum())
88
+ negative_count = min(int(negative.float().sum()), int(positive_count * self.negative_ratio))
89
+ # loss = nn.functional.binary_cross_entropy(pred, gt, reduction='none')
90
+ loss = nn.functional.binary_cross_entropy_with_logits(pred, gt, reduction='none')
91
+ positive_loss = loss * positive.float()
92
+ negative_loss = loss * negative.float()
93
+ # negative_loss, _ = torch.topk(negative_loss.view(-1).contiguous(), negative_count)
94
+ negative_loss, _ = negative_loss.view(-1).topk(negative_count)
95
+
96
+ balance_loss = (positive_loss.sum() + negative_loss.sum()) / (positive_count + negative_count + self.eps)
97
+
98
+ if return_origin:
99
+ return balance_loss, loss
100
+ return balance_loss
101
+
102
+
103
+ class DiceLoss(nn.Module):
104
+ '''
105
+ Loss function from https://arxiv.org/abs/1707.03237,
106
+ where iou computation is introduced heatmap manner to measure the
107
+ diversity between tow heatmaps.
108
+ '''
109
+
110
+ def __init__(self, eps=1e-6):
111
+ super(DiceLoss, self).__init__()
112
+ self.eps = eps
113
+
114
+ def forward(self, pred: torch.Tensor, gt, mask, weights=None):
115
+ '''
116
+ pred: one or two heatmaps of shape (N, 1, H, W),
117
+ the losses of tow heatmaps are added together.
118
+ gt: (N, 1, H, W)
119
+ mask: (N, H, W)
120
+ '''
121
+ return self._compute(pred, gt, mask, weights)
122
+
123
+ def _compute(self, pred, gt, mask, weights):
124
+ if pred.dim() == 4:
125
+ pred = pred[:, 0, :, :]
126
+ gt = gt[:, 0, :, :]
127
+ assert pred.shape == gt.shape
128
+ assert pred.shape == mask.shape
129
+ if weights is not None:
130
+ assert weights.shape == mask.shape
131
+ mask = weights * mask
132
+ intersection = (pred * gt * mask).sum()
133
+
134
+ union = (pred * mask).sum() + (gt * mask).sum() + self.eps
135
+ loss = 1 - 2.0 * intersection / union
136
+ assert loss <= 1
137
+ return loss
138
+
139
+
140
+ class MaskL1Loss(nn.Module):
141
+ def __init__(self, eps=1e-6):
142
+ super(MaskL1Loss, self).__init__()
143
+ self.eps = eps
144
+
145
+ def forward(self, pred: torch.Tensor, gt, mask):
146
+ loss = (torch.abs(pred - gt) * mask).sum() / (mask.sum() + self.eps)
147
+ return loss
148
+
149
+ class DBLoss(nn.Module):
150
+ def __init__(self, alpha=3.0, beta=1.0, ohem_ratio=3, reduction='mean', eps=1e-6):
151
+ """
152
+ Implement PSE Loss.
153
+ :param alpha: binary_map loss 前面的系数
154
+ :param beta: threshold_map loss 前面的系数
155
+ :param ohem_ratio: OHEM的比例
156
+ :param reduction: 'mean' or 'sum'对 batch里的loss 算均值或求和
157
+ """
158
+ super().__init__()
159
+ assert reduction in ['mean', 'sum'], " reduction must in ['mean','sum']"
160
+ self.alpha = alpha
161
+ self.beta = beta
162
+ self.bce_loss = BalanceCrossEntropyLoss(negative_ratio=ohem_ratio)
163
+ self.dice_loss = DiceLoss(eps=eps)
164
+ self.l1_loss = MaskL1Loss(eps=eps)
165
+ self.ohem_ratio = ohem_ratio
166
+ self.reduction = reduction
167
+
168
+ def forward(self, pred, batch, use_bce=True):
169
+ shrink_maps = pred[:, 0, :, :]
170
+ threshold_maps = pred[:, 1, :, :]
171
+ binary_maps = pred[:, 2, :, :]
172
+
173
+ if use_bce:
174
+ loss_shrink_maps = self.bce_loss(pred[:, 3, :, :], batch['shrink_map'], batch['shrink_mask']) + self.dice_loss(shrink_maps, batch['shrink_map'], batch['shrink_mask'])
175
+ else:
176
+ loss_shrink_maps = self.dice_loss(shrink_maps, batch['shrink_map'], batch['shrink_mask'])
177
+
178
+ loss_threshold_maps = self.l1_loss(threshold_maps, batch['threshold_map'], batch['threshold_mask'])
179
+ metrics = dict(loss_shrink_maps=loss_shrink_maps, loss_threshold_maps=loss_threshold_maps)
180
+ if pred.size()[1] > 2:
181
+ loss_binary_maps = self.dice_loss(binary_maps, batch['shrink_map'], batch['shrink_mask']) + self.bce_loss(binary_maps, batch['shrink_map'], batch['shrink_mask'])
182
+ metrics['loss_binary_maps'] = loss_binary_maps
183
+ loss_all = self.alpha * loss_shrink_maps + self.beta * loss_threshold_maps + loss_binary_maps
184
+ metrics['loss'] = loss_all
185
+ else:
186
+ metrics['loss'] = loss_shrink_maps
187
+ return metrics
188
+
utils/textblock.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ import numpy as np
3
+ from shapely.geometry import Polygon
4
+ import math
5
+ import copy
6
+ from utils.imgproc_utils import union_area, xywh2xyxypoly, rotate_polygons
7
+ import cv2
8
+
9
+ LANG_LIST = ['eng', 'ja', 'unknown']
10
+ LANGCLS2IDX = {'eng': 0, 'ja': 1, 'unknown': 2}
11
+
12
+ class TextBlock(object):
13
+ def __init__(self, xyxy: List,
14
+ lines: List = None,
15
+ language: str = 'unknown',
16
+ vertical: bool = False,
17
+ font_size: float = -1,
18
+ distance: List = None,
19
+ angle: int = 0,
20
+ vec: List = None,
21
+ norm: float = -1,
22
+ merged: bool = False,
23
+ weight: float = -1,
24
+ text: List = None,
25
+ translation: str = "",
26
+ fg_r = 0,
27
+ fg_g = 0,
28
+ fg_b = 0,
29
+ bg_r = 0,
30
+ bg_g = 0,
31
+ bg_b = 0,
32
+ line_spacing = 1.,
33
+ font_family: str = "",
34
+ bold: bool = False,
35
+ underline: bool = False,
36
+ italic: bool = False,
37
+ alignment: int = -1,
38
+ alpha: float = 255,
39
+ rich_text: str = "",
40
+ _bounding_rect: List = None,
41
+ accumulate_color = True,
42
+ default_stroke_width = 0.2,
43
+ target_lang: str = "",
44
+ **kwargs) -> None:
45
+ self.xyxy = [int(num) for num in xyxy] # boundingbox of textblock
46
+ self.lines = [] if lines is None else lines # polygons of textlines
47
+ self.vertical = vertical # orientation of textlines
48
+ self.language = language
49
+ self.font_size = font_size # font pixel size
50
+ self.distance = None if distance is None else np.array(distance, np.float64) # distance between textlines and "origin"
51
+ self.angle = angle # rotation angle of textlines
52
+
53
+ self.vec = None if vec is None else np.array(vec, np.float64) # primary vector of textblock
54
+ self.norm = norm # primary norm of textblock
55
+ self.merged = merged
56
+ self.weight = weight
57
+
58
+ self.text = text if text is not None else []
59
+ self.prob = 1
60
+
61
+ self.translation = translation
62
+
63
+ # note they're accumulative rgb values of textlines
64
+ self.fg_r = fg_r
65
+ self.fg_g = fg_g
66
+ self.fg_b = fg_b
67
+ self.bg_r = bg_r
68
+ self.bg_g = bg_g
69
+ self.bg_b = bg_b
70
+
71
+ # self.stroke_width = stroke_width
72
+ self.font_family: str = font_family
73
+ self.bold: bool = bold
74
+ self.underline: bool = underline
75
+ self.italic: bool = italic
76
+ self.alpha = alpha
77
+ self.rich_text = rich_text
78
+ self.line_spacing = line_spacing
79
+ # self.alignment = alignment
80
+ self._alignment = alignment
81
+ self._target_lang = target_lang
82
+
83
+ self._bounding_rect = _bounding_rect
84
+ self.default_stroke_width = default_stroke_width
85
+ self.accumulate_color = accumulate_color
86
+
87
+ def adjust_bbox(self, with_bbox=False):
88
+ lines = self.lines_array().astype(np.int32)
89
+ if with_bbox:
90
+ self.xyxy[0] = min(lines[..., 0].min(), self.xyxy[0])
91
+ self.xyxy[1] = min(lines[..., 1].min(), self.xyxy[1])
92
+ self.xyxy[2] = max(lines[..., 0].max(), self.xyxy[2])
93
+ self.xyxy[3] = max(lines[..., 1].max(), self.xyxy[3])
94
+ else:
95
+ self.xyxy[0] = lines[..., 0].min()
96
+ self.xyxy[1] = lines[..., 1].min()
97
+ self.xyxy[2] = lines[..., 0].max()
98
+ self.xyxy[3] = lines[..., 1].max()
99
+
100
+ def sort_lines(self):
101
+ if self.distance is not None:
102
+ idx = np.argsort(self.distance)
103
+ self.distance = self.distance[idx]
104
+ lines = np.array(self.lines, dtype=np.int32)
105
+ self.lines = lines[idx].tolist()
106
+
107
+ def lines_array(self, dtype=np.float64):
108
+ return np.array(self.lines, dtype=dtype)
109
+
110
+ def aspect_ratio(self) -> float:
111
+ min_rect = self.min_rect()
112
+ middle_pnts = (min_rect[:, [1, 2, 3, 0]] + min_rect) / 2
113
+ norm_v = np.linalg.norm(middle_pnts[:, 2] - middle_pnts[:, 0])
114
+ norm_h = np.linalg.norm(middle_pnts[:, 1] - middle_pnts[:, 3])
115
+ return norm_v / norm_h
116
+
117
+ def center(self):
118
+ xyxy = np.array(self.xyxy)
119
+ return (xyxy[:2] + xyxy[2:]) / 2
120
+
121
+ def min_rect(self, rotate_back=True):
122
+ angled = self.angle != 0
123
+ center = self.center()
124
+ polygons = self.lines_array().reshape(-1, 8)
125
+ if angled:
126
+ polygons = rotate_polygons(center, polygons, self.angle)
127
+ min_x = polygons[:, ::2].min()
128
+ min_y = polygons[:, 1::2].min()
129
+ max_x = polygons[:, ::2].max()
130
+ max_y = polygons[:, 1::2].max()
131
+ min_bbox = np.array([[min_x, min_y, max_x, min_y, max_x, max_y, min_x, max_y]])
132
+ if angled and rotate_back:
133
+ min_bbox = rotate_polygons(center, min_bbox, -self.angle)
134
+ return min_bbox.reshape(-1, 4, 2).astype(np.int64)
135
+
136
+ # equivalent to qt's boundingRect, ignore angle
137
+ def bounding_rect(self):
138
+ if self._bounding_rect is None:
139
+ # if True:
140
+ min_bbox = self.min_rect(rotate_back=False)[0]
141
+ x, y = min_bbox[0]
142
+ w, h = min_bbox[2] - min_bbox[0]
143
+ return [x, y, w, h]
144
+ return self._bounding_rect
145
+
146
+ def __getattribute__(self, name: str):
147
+ if name == 'pts':
148
+ return self.lines_array()
149
+ # else:
150
+ return object.__getattribute__(self, name)
151
+
152
+ def __len__(self):
153
+ return len(self.lines)
154
+
155
+ def __getitem__(self, idx):
156
+ return self.lines[idx]
157
+
158
+ def to_dict(self):
159
+ blk_dict = copy.deepcopy(vars(self))
160
+ return blk_dict
161
+
162
+ def get_transformed_region(self, img, idx, textheight) -> np.ndarray :
163
+ im_h, im_w = img.shape[:2]
164
+ direction = 'v' if self.vertical else 'h'
165
+ src_pts = np.array(self.lines[idx], dtype=np.float64)
166
+
167
+ if self.language == 'eng' or (self.language == 'unknown' and not self.vertical):
168
+ e_size = self.font_size / 3
169
+ src_pts[..., 0] += np.array([-e_size, e_size, e_size, -e_size])
170
+ src_pts[..., 1] += np.array([-e_size, -e_size, e_size, e_size])
171
+ src_pts[..., 0] = np.clip(src_pts[..., 0], 0, im_w)
172
+ src_pts[..., 1] = np.clip(src_pts[..., 1], 0, im_h)
173
+
174
+ middle_pnt = (src_pts[[1, 2, 3, 0]] + src_pts) / 2
175
+ vec_v = middle_pnt[2] - middle_pnt[0] # vertical vectors of textlines
176
+ vec_h = middle_pnt[1] - middle_pnt[3] # horizontal vectors of textlines
177
+ ratio = np.linalg.norm(vec_v) / np.linalg.norm(vec_h)
178
+
179
+ if direction == 'h' :
180
+ h = int(textheight)
181
+ w = int(round(textheight / ratio))
182
+ dst_pts = np.array([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]]).astype(np.float32)
183
+ M, _ = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
184
+ region = cv2.warpPerspective(img, M, (w, h))
185
+ elif direction == 'v' :
186
+ w = int(textheight)
187
+ h = int(round(textheight * ratio))
188
+ dst_pts = np.array([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]]).astype(np.float32)
189
+ M, _ = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
190
+ region = cv2.warpPerspective(img, M, (w, h))
191
+ region = cv2.rotate(region, cv2.ROTATE_90_COUNTERCLOCKWISE)
192
+ # cv2.imshow('region'+str(idx), region)
193
+ # cv2.waitKey(0)
194
+ return region
195
+
196
+ def get_text(self):
197
+ if isinstance(self.text, str):
198
+ return self.text
199
+ return ' '.join(self.text).strip()
200
+
201
+ def set_font_colors(self, frgb, srgb, accumulate=True):
202
+ self.accumulate_color = accumulate
203
+ num_lines = len(self.lines) if accumulate and len(self.lines) > 0 else 1
204
+ # set font color
205
+ frgb = np.array(frgb) * num_lines
206
+ self.fg_r, self.fg_g, self.fg_b = frgb
207
+ # set stroke color
208
+ srgb = np.array(srgb) * num_lines
209
+ self.bg_r, self.bg_g, self.bg_b = srgb
210
+
211
+ def get_font_colors(self, bgr=False):
212
+ num_lines = len(self.lines)
213
+ frgb = np.array([self.fg_r, self.fg_g, self.fg_b])
214
+ brgb = np.array([self.bg_r, self.bg_g, self.bg_b])
215
+ if self.accumulate_color:
216
+ if num_lines > 0:
217
+ frgb = (frgb / num_lines).astype(np.int32)
218
+ brgb = (brgb / num_lines).astype(np.int32)
219
+ if bgr:
220
+ return frgb[::-1], brgb[::-1]
221
+ else:
222
+ return frgb, brgb
223
+ else:
224
+ return [0, 0, 0], [0, 0, 0]
225
+ else:
226
+ return frgb, brgb
227
+
228
+ def xywh(self):
229
+ x, y, w, h = self.xyxy
230
+ return [x, y, w-x, h-y]
231
+
232
+ # alignleft: 0, center: 1, right: 2
233
+ def alignment(self):
234
+ if self._alignment >= 0:
235
+ return self._alignment
236
+ elif self.vertical:
237
+ return 0
238
+ lines = self.lines_array()
239
+ if len(lines) == 1:
240
+ return 0
241
+ angled = self.angle != 0
242
+ polygons = lines.reshape(-1, 8)
243
+ if angled:
244
+ polygons = rotate_polygons((0, 0), polygons, self.angle)
245
+ polygons = polygons.reshape(-1, 4, 2)
246
+
247
+ left_std = np.std(polygons[:, 0, 0])
248
+ # right_std = np.std(polygons[:, 1, 0])
249
+ center_std = np.std((polygons[:, 0, 0] + polygons[:, 1, 0]) / 2)
250
+ if left_std < center_std:
251
+ return 0
252
+ else:
253
+ return 1
254
+
255
+ def target_lang(self):
256
+ return self.target_lang
257
+
258
+ @property
259
+ def stroke_width(self):
260
+ var = np.array([self.fg_r, self.fg_g, self.fg_b]) \
261
+ - np.array([self.bg_r, self.bg_g, self.bg_b])
262
+ var = np.abs(var).sum()
263
+ if var > 40:
264
+ return self.default_stroke_width
265
+ return 0
266
+
267
+ def sort_textblk_list(blk_list: List[TextBlock], im_w: int, im_h: int) -> List[TextBlock]:
268
+ if len(blk_list) == 0:
269
+ return blk_list
270
+ num_ja = 0
271
+ xyxy = []
272
+ for blk in blk_list:
273
+ if blk.language == 'ja':
274
+ num_ja += 1
275
+ xyxy.append(blk.xyxy)
276
+ xyxy = np.array(xyxy)
277
+ flip_lr = num_ja > len(blk_list) / 2
278
+ im_oriw = im_w
279
+ if im_w > im_h:
280
+ im_w /= 2
281
+ num_gridy, num_gridx = 4, 3
282
+ img_area = im_h * im_w
283
+ center_x = (xyxy[:, 0] + xyxy[:, 2]) / 2
284
+ if flip_lr:
285
+ if im_w != im_oriw:
286
+ center_x = im_oriw - center_x
287
+ else:
288
+ center_x = im_w - center_x
289
+ grid_x = (center_x / im_w * num_gridx).astype(np.int32)
290
+ center_y = (xyxy[:, 1] + xyxy[:, 3]) / 2
291
+ grid_y = (center_y / im_h * num_gridy).astype(np.int32)
292
+ grid_indices = grid_y * num_gridx + grid_x
293
+ grid_weights = grid_indices * img_area + 1.2 * (center_x - grid_x * im_w / num_gridx) + (center_y - grid_y * im_h / num_gridy)
294
+ if im_w != im_oriw:
295
+ grid_weights[np.where(grid_x >= num_gridx)] += img_area * num_gridy * num_gridx
296
+
297
+ for blk, weight in zip(blk_list, grid_weights):
298
+ blk.weight = weight
299
+ blk_list.sort(key=lambda blk: blk.weight)
300
+ return blk_list
301
+
302
+ def examine_textblk(blk: TextBlock, im_w: int, im_h: int, sort: bool = False) -> None:
303
+ lines = blk.lines_array()
304
+ middle_pnts = (lines[:, [1, 2, 3, 0]] + lines) / 2
305
+ vec_v = middle_pnts[:, 2] - middle_pnts[:, 0] # vertical vectors of textlines
306
+ vec_h = middle_pnts[:, 1] - middle_pnts[:, 3] # horizontal vectors of textlines
307
+ # if sum of vertical vectors is longer, then text orientation is vertical, and vice versa.
308
+ center_pnts = (lines[:, 0] + lines[:, 2]) / 2
309
+ v = np.sum(vec_v, axis=0)
310
+ h = np.sum(vec_h, axis=0)
311
+ norm_v, norm_h = np.linalg.norm(v), np.linalg.norm(h)
312
+ if blk.language == 'ja':
313
+ vertical = norm_v > norm_h
314
+ else:
315
+ vertical = norm_v > norm_h * 2
316
+ # calculate distance between textlines and origin
317
+ if vertical:
318
+ primary_vec, primary_norm = v, norm_v
319
+ distance_vectors = center_pnts - np.array([[im_w, 0]], dtype=np.float64) # vertical manga text is read from right to left, so origin is (imw, 0)
320
+ font_size = int(round(norm_h / len(lines)))
321
+ else:
322
+ primary_vec, primary_norm = h, norm_h
323
+ distance_vectors = center_pnts - np.array([[0, 0]], dtype=np.float64)
324
+ font_size = int(round(norm_v / len(lines)))
325
+
326
+ rotation_angle = int(math.atan2(primary_vec[1], primary_vec[0]) / math.pi * 180) # rotation angle of textlines
327
+ distance = np.linalg.norm(distance_vectors, axis=1) # distance between textlinecenters and origin
328
+ rad_matrix = np.arccos(np.einsum('ij, j->i', distance_vectors, primary_vec) / (distance * primary_norm))
329
+ distance = np.abs(np.sin(rad_matrix) * distance)
330
+ blk.lines = lines.astype(np.int32).tolist()
331
+ blk.distance = distance
332
+ blk.angle = rotation_angle
333
+ if vertical:
334
+ blk.angle -= 90
335
+ if abs(blk.angle) < 3:
336
+ blk.angle = 0
337
+ blk.font_size = font_size
338
+ blk.vertical = vertical
339
+ blk.vec = primary_vec
340
+ blk.norm = primary_norm
341
+ if sort:
342
+ blk.sort_lines()
343
+
344
+ def try_merge_textline(blk: TextBlock, blk2: TextBlock, fntsize_tol=1.3, distance_tol=2) -> bool:
345
+ if blk2.merged:
346
+ return False
347
+ fntsize_div = blk.font_size / blk2.font_size
348
+ num_l1, num_l2 = len(blk), len(blk2)
349
+ fntsz_avg = (blk.font_size * num_l1 + blk2.font_size * num_l2) / (num_l1 + num_l2)
350
+ vec_prod = blk.vec @ blk2.vec
351
+ vec_sum = blk.vec + blk2.vec
352
+ cos_vec = vec_prod / blk.norm / blk2.norm
353
+ distance = blk2.distance[-1] - blk.distance[-1]
354
+ distance_p1 = np.linalg.norm(np.array(blk2.lines[-1][0]) - np.array(blk.lines[-1][0]))
355
+ l1, l2 = Polygon(blk.lines[-1]), Polygon(blk2.lines[-1])
356
+ if not l1.intersects(l2):
357
+ if fntsize_div > fntsize_tol or 1 / fntsize_div > fntsize_tol:
358
+ return False
359
+ if abs(cos_vec) < 0.866: # cos30
360
+ return False
361
+ if distance > distance_tol * fntsz_avg or distance_p1 > fntsz_avg * 2.5:
362
+ return False
363
+ # merge
364
+ blk.lines.append(blk2.lines[0])
365
+ blk.vec = vec_sum
366
+ blk.angle = int(round(np.rad2deg(math.atan2(vec_sum[1], vec_sum[0]))))
367
+ if blk.vertical:
368
+ blk.angle -= 90
369
+ blk.norm = np.linalg.norm(vec_sum)
370
+ blk.distance = np.append(blk.distance, blk2.distance[-1])
371
+ blk.font_size = fntsz_avg
372
+ blk2.merged = True
373
+ return True
374
+
375
+ def merge_textlines(blk_list: List[TextBlock]) -> List[TextBlock]:
376
+ if len(blk_list) < 2:
377
+ return blk_list
378
+ blk_list.sort(key=lambda blk: blk.distance[0])
379
+ merged_list = []
380
+ for ii, current_blk in enumerate(blk_list):
381
+ if current_blk.merged:
382
+ continue
383
+ for jj, blk in enumerate(blk_list[ii+1:]):
384
+ try_merge_textline(current_blk, blk)
385
+ merged_list.append(current_blk)
386
+ for blk in merged_list:
387
+ blk.adjust_bbox(with_bbox=False)
388
+ return merged_list
389
+
390
+ def split_textblk(blk: TextBlock):
391
+ font_size, distance, lines = blk.font_size, blk.distance, blk.lines
392
+ l0 = np.array(blk.lines[0])
393
+ lines.sort(key=lambda line: np.linalg.norm(np.array(line[0]) - l0[0]))
394
+ distance_tol = font_size * 2
395
+ current_blk = copy.deepcopy(blk)
396
+ current_blk.lines = [l0]
397
+ sub_blk_list = [current_blk]
398
+ textblock_splitted = False
399
+ for jj, line in enumerate(lines[1:]):
400
+ l1, l2 = Polygon(lines[jj]), Polygon(line)
401
+ split = False
402
+ if not l1.intersects(l2):
403
+ line_disance = abs(distance[jj+1] - distance[jj])
404
+ if line_disance > distance_tol:
405
+ split = True
406
+ elif blk.vertical and abs(blk.angle) < 15:
407
+ if len(current_blk.lines) > 1 or line_disance > font_size:
408
+ split = abs(lines[jj][0][1] - line[0][1]) > font_size
409
+ if split:
410
+ current_blk = copy.deepcopy(current_blk)
411
+ current_blk.lines = [line]
412
+ sub_blk_list.append(current_blk)
413
+ else:
414
+ current_blk.lines.append(line)
415
+ if len(sub_blk_list) > 1:
416
+ textblock_splitted = True
417
+ for current_blk in sub_blk_list:
418
+ current_blk.adjust_bbox(with_bbox=False)
419
+ return textblock_splitted, sub_blk_list
420
+
421
+ def group_output(blks, lines, im_w, im_h, mask=None, sort_blklist=True) -> List[TextBlock]:
422
+ blk_list: List[TextBlock] = []
423
+ scattered_lines = {'ver': [], 'hor': []}
424
+ for bbox, cls, conf in zip(*blks):
425
+ # cls could give wrong result
426
+ blk_list.append(TextBlock(bbox, language=LANG_LIST[cls]))
427
+
428
+ # step1: filter & assign lines to textblocks
429
+ bbox_score_thresh = 0.4
430
+ mask_score_thresh = 0.1
431
+ for ii, line in enumerate(lines):
432
+ bx1, bx2 = line[:, 0].min(), line[:, 0].max()
433
+ by1, by2 = line[:, 1].min(), line[:, 1].max()
434
+ bbox_score, bbox_idx = -1, -1
435
+ line_area = (by2-by1) * (bx2-bx1)
436
+ for jj, blk in enumerate(blk_list):
437
+ score = union_area(blk.xyxy, [bx1, by1, bx2, by2]) / line_area
438
+ if bbox_score < score:
439
+ bbox_score = score
440
+ bbox_idx = jj
441
+ if bbox_score > bbox_score_thresh:
442
+ blk_list[bbox_idx].lines.append(line)
443
+ else: # if no textblock was assigned, check whether there is "enough" textmask
444
+ if mask is not None:
445
+ mask_score = mask[by1: by2, bx1: bx2].mean() / 255
446
+ if mask_score < mask_score_thresh:
447
+ continue
448
+ blk = TextBlock([bx1, by1, bx2, by2], [line])
449
+ examine_textblk(blk, im_w, im_h, sort=False)
450
+ if blk.vertical:
451
+ scattered_lines['ver'].append(blk)
452
+ else:
453
+ scattered_lines['hor'].append(blk)
454
+
455
+ # step2: filter textblocks, sort & split textlines
456
+ final_blk_list = []
457
+ for blk in blk_list:
458
+ # filter textblocks
459
+ if len(blk.lines) == 0:
460
+ bx1, by1, bx2, by2 = blk.xyxy
461
+ if mask is not None:
462
+ mask_score = mask[by1: by2, bx1: bx2].mean() / 255
463
+ if mask_score < mask_score_thresh:
464
+ continue
465
+ xywh = np.array([[bx1, by1, bx2-bx1, by2-by1]])
466
+ blk.lines = xywh2xyxypoly(xywh).reshape(-1, 4, 2).tolist()
467
+ examine_textblk(blk, im_w, im_h, sort=True)
468
+
469
+ # split manga text if there is a distance gap
470
+ textblock_splitted = False
471
+ if len(blk.lines) > 1:
472
+ if blk.language == 'ja':
473
+ textblock_splitted = True
474
+ elif blk.vertical:
475
+ textblock_splitted = True
476
+ if textblock_splitted:
477
+ textblock_splitted, sub_blk_list = split_textblk(blk)
478
+ else:
479
+ sub_blk_list = [blk]
480
+ # modify textblock to fit its textlines
481
+ if not textblock_splitted:
482
+ for blk in sub_blk_list:
483
+ blk.adjust_bbox(with_bbox=True)
484
+ final_blk_list += sub_blk_list
485
+
486
+ # step3: merge scattered lines, sort textblocks by "grid"
487
+ final_blk_list += merge_textlines(scattered_lines['hor'])
488
+ final_blk_list += merge_textlines(scattered_lines['ver'])
489
+ if sort_blklist:
490
+ final_blk_list = sort_textblk_list(final_blk_list, im_w, im_h)
491
+
492
+ for blk in final_blk_list:
493
+ if blk.language == 'eng' and not blk.vertical:
494
+ num_lines = len(blk.lines)
495
+ if num_lines == 0:
496
+ continue
497
+ # blk.line_spacing = blk.bounding_rect()[3] / num_lines / blk.font_size
498
+ expand_size = max(int(blk.font_size * 0.1), 2)
499
+ rad = np.deg2rad(blk.angle)
500
+ shifted_vec = np.array([[[-1, -1],[1, -1],[1, 1],[-1, 1]]])
501
+ shifted_vec = shifted_vec * np.array([[[np.sin(rad), np.cos(rad)]]]) * expand_size
502
+ lines = blk.lines_array() + shifted_vec
503
+ lines[..., 0] = np.clip(lines[..., 0], 0, im_w-1)
504
+ lines[..., 1] = np.clip(lines[..., 1], 0, im_h-1)
505
+ blk.lines = lines.astype(np.int64).tolist()
506
+ blk.font_size += expand_size
507
+
508
+ return final_blk_list
509
+
510
+ def visualize_textblocks(canvas, blk_list: List[TextBlock], path = '../output/'):
511
+ lw = max(round(sum(canvas.shape) / 2 * 0.003), 2) # line width
512
+ for ii, blk in enumerate(blk_list):
513
+ bx1, by1, bx2, by2 = blk.xyxy
514
+ cv2.rectangle(canvas, (bx1, by1), (bx2, by2), (127, 255, 127), lw)
515
+ cut_img = canvas[by1:by2, bx1:bx2]
516
+ cv2.imwrite(path + f'/cut_image_{ii}.png', cut_img)
517
+ lines = blk.lines_array(dtype=np.int32)
518
+ for jj, line in enumerate(lines):
519
+ cv2.putText(canvas, str(jj), line[0], cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,127,0), 1)
520
+ cv2.polylines(canvas, [line], True, (0,127,255), 2)
521
+ cv2.polylines(canvas, [blk.min_rect()], True, (127,127,0), 2)
522
+ center = [int((bx1 + bx2)/2), int((by1 + by2)/2)]
523
+ cv2.putText(canvas, str(blk.angle), center, cv2.FONT_HERSHEY_SIMPLEX, 1, (127,127,255), 2)
524
+ cv2.putText(canvas, str(ii), (bx1, by1 + lw + 2), 0, lw / 3, (255,127,127), max(lw-1, 1), cv2.LINE_AA)
525
+ return canvas
526
+
utils/textmask.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from os import stat
2
+ from typing import List
3
+ import cv2
4
+ import numpy as np
5
+ from .textblock import TextBlock
6
+ from .imgproc_utils import draw_connected_labels, expand_textwindow, union_area
7
+
8
+ WHITE = (255, 255, 255)
9
+ BLACK = (0, 0, 0)
10
+ LANG_ENG = 0
11
+ LANG_JPN = 1
12
+
13
+ REFINEMASK_INPAINT = 0
14
+ REFINEMASK_ANNOTATION = 1
15
+
16
+ def get_topk_color(color_list, bins, k=3, color_var=10, bin_tol=0.001):
17
+ idx = np.argsort(bins * -1)
18
+ color_list, bins = color_list[idx], bins[idx]
19
+ top_colors = [color_list[0]]
20
+ bin_tol = np.sum(bins) * bin_tol
21
+ if len(color_list) > 1:
22
+ for color, bin in zip(color_list[1:], bins[1:]):
23
+ if np.abs(np.array(top_colors) - color).min() > color_var:
24
+ top_colors.append(color)
25
+ if len(top_colors) >= k or bin < bin_tol:
26
+ break
27
+ return top_colors
28
+
29
+ def minxor_thresh(threshed, mask, dilate=False):
30
+ neg_threshed = 255 - threshed
31
+ e_size = 1
32
+ if dilate:
33
+ element = cv2.getStructuringElement(cv2.MORPH_RECT, (2 * e_size + 1, 2 * e_size + 1),(e_size, e_size))
34
+ neg_threshed = cv2.dilate(neg_threshed, element, iterations=1)
35
+ threshed = cv2.dilate(threshed, element, iterations=1)
36
+ neg_xor_sum = cv2.bitwise_xor(neg_threshed, mask).sum()
37
+ xor_sum = cv2.bitwise_xor(threshed, mask).sum()
38
+ if neg_xor_sum < xor_sum:
39
+ return neg_threshed, neg_xor_sum
40
+ else:
41
+ return threshed, xor_sum
42
+
43
+ def get_otsuthresh_masklist(img, pred_mask, per_channel=False) -> List[np.ndarray]:
44
+ channels = [img[..., 0], img[..., 1], img[..., 2]]
45
+ mask_list = []
46
+ for c in channels:
47
+ _, threshed = cv2.threshold(c, 1, 255, cv2.THRESH_OTSU+cv2.THRESH_BINARY)
48
+ threshed, xor_sum = minxor_thresh(threshed, pred_mask, dilate=False)
49
+ mask_list.append([threshed, xor_sum])
50
+ mask_list.sort(key=lambda x: x[1])
51
+ if per_channel:
52
+ return mask_list
53
+ else:
54
+ return [mask_list[0]]
55
+
56
+ def get_topk_masklist(im_grey, pred_mask):
57
+ if len(im_grey.shape) == 3 and im_grey.shape[-1] == 3:
58
+ im_grey = cv2.cvtColor(im_grey, cv2.COLOR_BGR2GRAY)
59
+ msk = np.ascontiguousarray(pred_mask)
60
+ candidate_grey_px = im_grey[np.where(cv2.erode(msk, np.ones((3,3), np.uint8), iterations=1) > 127)]
61
+ bin, his = np.histogram(candidate_grey_px, bins=255)
62
+ topk_color = get_topk_color(his, bin, color_var=10, k=3)
63
+ color_range = 30
64
+ mask_list = list()
65
+ for ii, color in enumerate(topk_color):
66
+ c_top = min(color+color_range, 255)
67
+ c_bottom = c_top - 2 * color_range
68
+ threshed = cv2.inRange(im_grey, c_bottom, c_top)
69
+ threshed, xor_sum = minxor_thresh(threshed, msk)
70
+ mask_list.append([threshed, xor_sum])
71
+ return mask_list
72
+
73
+ def merge_mask_list(mask_list, pred_mask, blk: TextBlock = None, pred_thresh=30, text_window=None, filter_with_lines=False, refine_mode=REFINEMASK_INPAINT):
74
+ mask_list.sort(key=lambda x: x[1])
75
+ linemask = None
76
+ if blk is not None and filter_with_lines:
77
+ linemask = np.zeros_like(pred_mask)
78
+ lines = blk.lines_array(dtype=np.int64)
79
+ for line in lines:
80
+ line[..., 0] -= text_window[0]
81
+ line[..., 1] -= text_window[1]
82
+ cv2.fillPoly(linemask, [line], 255)
83
+ linemask = cv2.dilate(linemask, np.ones((3, 3), np.uint8), iterations=3)
84
+
85
+ if pred_thresh > 0:
86
+ e_size = 1
87
+ element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * e_size + 1, 2 * e_size + 1),(e_size, e_size))
88
+ pred_mask = cv2.erode(pred_mask, element, iterations=1)
89
+ _, pred_mask = cv2.threshold(pred_mask, 60, 255, cv2.THRESH_BINARY)
90
+ connectivity = 8
91
+ mask_merged = np.zeros_like(pred_mask)
92
+ for ii, (candidate_mask, xor_sum) in enumerate(mask_list):
93
+ num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(candidate_mask, connectivity, cv2.CV_16U)
94
+ for label_index, stat, centroid in zip(range(num_labels), stats, centroids):
95
+ if label_index != 0: # skip background label
96
+ x, y, w, h, area = stat
97
+ if w * h < 3:
98
+ continue
99
+ x1, y1, x2, y2 = x, y, x+w, y+h
100
+ label_local = labels[y1: y2, x1: x2]
101
+ label_coordinates = np.where(label_local==label_index)
102
+ tmp_merged = np.zeros_like(label_local, np.uint8)
103
+ tmp_merged[label_coordinates] = 255
104
+ tmp_merged = cv2.bitwise_or(mask_merged[y1: y2, x1: x2], tmp_merged)
105
+ xor_merged = cv2.bitwise_xor(tmp_merged, pred_mask[y1: y2, x1: x2]).sum()
106
+ xor_origin = cv2.bitwise_xor(mask_merged[y1: y2, x1: x2], pred_mask[y1: y2, x1: x2]).sum()
107
+ if xor_merged < xor_origin:
108
+ mask_merged[y1: y2, x1: x2] = tmp_merged
109
+
110
+ if refine_mode == REFINEMASK_INPAINT:
111
+ mask_merged = cv2.dilate(mask_merged, np.ones((3, 3), np.uint8), iterations=1)
112
+ # fill holes
113
+ num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(255-mask_merged, connectivity, cv2.CV_16U)
114
+ sorted_area = np.sort(stats[:, -1])
115
+ if len(sorted_area) > 1:
116
+ area_thresh = sorted_area[-2]
117
+ else:
118
+ area_thresh = sorted_area[-1]
119
+ for label_index, stat, centroid in zip(range(num_labels), stats, centroids):
120
+ x, y, w, h, area = stat
121
+ if area < area_thresh:
122
+ x1, y1, x2, y2 = x, y, x+w, y+h
123
+ label_local = labels[y1: y2, x1: x2]
124
+ label_coordinates = np.where(label_local==label_index)
125
+ tmp_merged = np.zeros_like(label_local, np.uint8)
126
+ tmp_merged[label_coordinates] = 255
127
+ tmp_merged = cv2.bitwise_or(mask_merged[y1: y2, x1: x2], tmp_merged)
128
+ xor_merged = cv2.bitwise_xor(tmp_merged, pred_mask[y1: y2, x1: x2]).sum()
129
+ xor_origin = cv2.bitwise_xor(mask_merged[y1: y2, x1: x2], pred_mask[y1: y2, x1: x2]).sum()
130
+ if xor_merged < xor_origin:
131
+ mask_merged[y1: y2, x1: x2] = tmp_merged
132
+ return mask_merged
133
+
134
+
135
+ def refine_undetected_mask(img: np.ndarray, mask_pred: np.ndarray, mask_refined: np.ndarray, blk_list: List[TextBlock], refine_mode=REFINEMASK_INPAINT):
136
+ mask_pred[np.where(mask_refined > 30)] = 0
137
+ _, pred_mask_t = cv2.threshold(mask_pred, 30, 255, cv2.THRESH_BINARY)
138
+ num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(pred_mask_t, 4, cv2.CV_16U)
139
+ valid_labels = np.where(stats[:, -1] > 50)[0]
140
+ seg_blk_list = []
141
+ if len(valid_labels) > 0:
142
+ for lab_index in valid_labels[1:]:
143
+ x, y, w, h, area = stats[lab_index]
144
+ bx1, by1 = x, y
145
+ bx2, by2 = x+w, y+h
146
+ bbox = [bx1, by1, bx2, by2]
147
+ bbox_score = -1
148
+ for blk in blk_list:
149
+ bbox_s = union_area(blk.xyxy, bbox)
150
+ if bbox_s > bbox_score:
151
+ bbox_score = bbox_s
152
+ if bbox_score / w / h < 0.5:
153
+ seg_blk_list.append(TextBlock(bbox))
154
+ if len(seg_blk_list) > 0:
155
+ mask_refined = cv2.bitwise_or(mask_refined, refine_mask(img, mask_pred, seg_blk_list, refine_mode=refine_mode))
156
+ return mask_refined
157
+
158
+
159
+ def refine_mask(img: np.ndarray, pred_mask: np.ndarray, blk_list: List[TextBlock], refine_mode: int = REFINEMASK_INPAINT) -> np.ndarray:
160
+ mask_refined = np.zeros_like(pred_mask)
161
+ for blk in blk_list:
162
+ bx1, by1, bx2, by2 = expand_textwindow(img.shape, blk.xyxy, expand_r=16)
163
+ im = np.ascontiguousarray(img[by1: by2, bx1: bx2])
164
+ msk = np.ascontiguousarray(pred_mask[by1: by2, bx1: bx2])
165
+ mask_list = get_topk_masklist(im, msk)
166
+ mask_list += get_otsuthresh_masklist(im, msk, per_channel=False)
167
+ mask_merged = merge_mask_list(mask_list, msk, blk=blk, text_window=[bx1, by1, bx2, by2], refine_mode=refine_mode)
168
+ mask_refined[by1: by2, bx1: bx2] = cv2.bitwise_or(mask_refined[by1: by2, bx1: bx2], mask_merged)
169
+ return mask_refined
170
+
171
+ # def extract_textballoon(img, pred_textmsk=None, global_mask=None):
172
+ # if len(img.shape) > 2 and img.shape[2] == 3:
173
+ # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
174
+ # im_h, im_w = img.shape[0], img.shape[1]
175
+ # hyp_textmsk = np.zeros((im_h, im_w), np.uint8)
176
+ # thresh_val, threshed = cv2.threshold(img, 1, 255, cv2.THRESH_OTSU+cv2.THRESH_BINARY)
177
+ # xormap_sum = cv2.bitwise_xor(threshed, pred_textmsk).sum()
178
+ # neg_threshed = 255 - threshed
179
+ # neg_xormap_sum = cv2.bitwise_xor(neg_threshed, pred_textmsk).sum()
180
+ # neg_thresh = neg_xormap_sum < xormap_sum
181
+ # if neg_thresh:
182
+ # threshed = neg_threshed
183
+ # thresh_info = {'thresh_val': thresh_val,'neg_thresh': neg_thresh}
184
+ # connectivity = 8
185
+ # num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(threshed, connectivity, cv2.CV_16U)
186
+ # label_unchanged = np.copy(labels)
187
+ # if global_mask is not None:
188
+ # labels[np.where(global_mask==0)] = 0
189
+ # text_labels = []
190
+ # if pred_textmsk is not None:
191
+ # text_score_thresh = 0.5
192
+ # textbbox_map = np.zeros_like(pred_textmsk)
193
+ # for label_index, stat, centroid in zip(range(num_labels), stats, centroids):
194
+ # if label_index != 0: # skip background label
195
+ # x, y, w, h, area = stat
196
+ # area *= 255
197
+ # x1, y1, x2, y2 = x, y, x+w, y+h
198
+ # label_local = labels[y1: y2, x1: x2]
199
+ # label_coordinates = np.where(label_local==label_index)
200
+ # tmp_merged = np.zeros((h, w), np.uint8)
201
+ # tmp_merged[label_coordinates] = 255
202
+ # andmap = cv2.bitwise_and(tmp_merged, pred_textmsk[y1: y2, x1: x2])
203
+ # text_score = andmap.sum() / area
204
+ # if text_score > text_score_thresh:
205
+ # text_labels.append(label_index)
206
+ # hyp_textmsk[y1: y2, x1: x2][label_coordinates] = 255
207
+ # labels = label_unchanged
208
+ # bubble_msk = np.zeros((img.shape[0], img.shape[1]), np.uint8)
209
+ # bubble_msk[np.where(labels==0)] = 255
210
+ # # if lang == LANG_JPN:
211
+ # bubble_msk = cv2.erode(bubble_msk, (3, 3), iterations=1)
212
+ # line_thickness = 2
213
+ # cv2.rectangle(bubble_msk, (0, 0), (im_w, im_h), BLACK, line_thickness, cv2.LINE_8)
214
+ # contours, hiers = cv2.findContours(bubble_msk, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
215
+
216
+ # brect_area_thresh = im_h * im_w * 0.4
217
+ # min_brect_area = np.inf
218
+ # ballon_index = -1
219
+ # maximum_pixsum = -1
220
+ # for ii, contour in enumerate(contours):
221
+ # brect = cv2.boundingRect(contours[ii])
222
+ # brect_area = brect[2] * brect[3]
223
+ # if brect_area > brect_area_thresh and brect_area < min_brect_area:
224
+ # tmp_ballonmsk = np.zeros_like(bubble_msk)
225
+ # tmp_ballonmsk = cv2.drawContours(tmp_ballonmsk, contours, ii, WHITE, cv2.FILLED)
226
+ # andmap_sum = cv2.bitwise_and(tmp_ballonmsk, hyp_textmsk).sum()
227
+ # if andmap_sum > maximum_pixsum:
228
+ # maximum_pixsum = andmap_sum
229
+ # min_brect_area = brect_area
230
+ # ballon_index = ii
231
+ # if ballon_index != -1:
232
+ # bubble_msk = np.zeros_like(bubble_msk)
233
+ # bubble_msk = cv2.drawContours(bubble_msk, contours, ballon_index, WHITE, cv2.FILLED)
234
+ # hyp_textmsk = cv2.bitwise_and(hyp_textmsk, bubble_msk)
235
+ # return hyp_textmsk, bubble_msk, thresh_info, (num_labels, label_unchanged, stats, centroids, text_labels)
236
+
237
+ # def extract_textballoon_channelwise(img, pred_textmsk, test_grey=True, global_mask=None):
238
+ # c_list = [img[:, :, i] for i in range(3)]
239
+ # if test_grey:
240
+ # c_list.append(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
241
+ # best_xorpix_sum = np.inf
242
+ # best_cindex = best_hyptextmsk = best_bubblemsk = best_thresh_info = best_component_stats = None
243
+ # for c_index, channel in enumerate(c_list):
244
+ # hyp_textmsk, bubble_msk, thresh_info, component_stats = extract_textballoon(channel, pred_textmsk, global_mask=global_mask)
245
+ # pixor_sum = cv2.bitwise_xor(hyp_textmsk, pred_textmsk).sum()
246
+ # if pixor_sum < best_xorpix_sum:
247
+ # best_xorpix_sum = pixor_sum
248
+ # best_cindex = c_index
249
+ # best_hyptextmsk, best_bubblemsk, best_thresh_info, best_component_stats = hyp_textmsk, bubble_msk, thresh_info, component_stats
250
+ # return best_hyptextmsk, best_bubblemsk, best_component_stats
251
+
252
+ # def refine_textmask(img, pred_mask, channel_wise=True, find_leaveouts=True, global_mask=None):
253
+ # hyp_textmsk, bubble_msk, component_stats = extract_textballoon_channelwise(img, pred_mask, global_mask=global_mask)
254
+ # num_labels, labels, stats, centroids, text_labels = component_stats
255
+ # stats = np.array(stats)
256
+ # text_stats = stats[text_labels]
257
+ # if find_leaveouts and len(text_stats) > 0:
258
+ # median_h = np.median(text_stats[:, 3])
259
+ # for label, label_h in zip(range(num_labels), stats[:, 3]):
260
+ # if label == 0 or label in text_labels:
261
+ # continue
262
+ # if label_h > 0.5 * median_h and label_h < 1.5 * median_h:
263
+ # hyp_textmsk[np.where(labels==label)] = 255
264
+ # hyp_textmsk = cv2.bitwise_and(hyp_textmsk, bubble_msk)
265
+ # if global_mask is not None:
266
+ # hyp_textmsk = cv2.bitwise_and(hyp_textmsk, global_mask)
267
+ # return hyp_textmsk, bubble_msk
utils/weight_init.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+
4
+ def constant_init(module, val, bias=0):
5
+ nn.init.constant_(module.weight, val)
6
+ if hasattr(module, 'bias') and module.bias is not None:
7
+ nn.init.constant_(module.bias, bias)
8
+
9
+ def xavier_init(module, gain=1, bias=0, distribution='normal'):
10
+ assert distribution in ['uniform', 'normal']
11
+ if distribution == 'uniform':
12
+ nn.init.xavier_uniform_(module.weight, gain=gain)
13
+ else:
14
+ nn.init.xavier_normal_(module.weight, gain=gain)
15
+ if hasattr(module, 'bias') and module.bias is not None:
16
+ nn.init.constant_(module.bias, bias)
17
+
18
+
19
+ def normal_init(module, mean=0, std=1, bias=0):
20
+ nn.init.normal_(module.weight, mean, std)
21
+ if hasattr(module, 'bias') and module.bias is not None:
22
+ nn.init.constant_(module.bias, bias)
23
+
24
+
25
+ def uniform_init(module, a=0, b=1, bias=0):
26
+ nn.init.uniform_(module.weight, a, b)
27
+ if hasattr(module, 'bias') and module.bias is not None:
28
+ nn.init.constant_(module.bias, bias)
29
+
30
+
31
+ def kaiming_init(module,
32
+ a=0,
33
+ is_rnn=False,
34
+ mode='fan_in',
35
+ nonlinearity='leaky_relu',
36
+ bias=0,
37
+ distribution='normal'):
38
+ assert distribution in ['uniform', 'normal']
39
+ if distribution == 'uniform':
40
+ if is_rnn:
41
+ for name, param in module.named_parameters():
42
+ if 'bias' in name:
43
+ nn.init.constant_(param, bias)
44
+ elif 'weight' in name:
45
+ nn.init.kaiming_uniform_(param,
46
+ a=a,
47
+ mode=mode,
48
+ nonlinearity=nonlinearity)
49
+ else:
50
+ nn.init.kaiming_uniform_(module.weight,
51
+ a=a,
52
+ mode=mode,
53
+ nonlinearity=nonlinearity)
54
+
55
+ else:
56
+ if is_rnn:
57
+ for name, param in module.named_parameters():
58
+ if 'bias' in name:
59
+ nn.init.constant_(param, bias)
60
+ elif 'weight' in name:
61
+ nn.init.kaiming_normal_(param,
62
+ a=a,
63
+ mode=mode,
64
+ nonlinearity=nonlinearity)
65
+ else:
66
+ nn.init.kaiming_normal_(module.weight,
67
+ a=a,
68
+ mode=mode,
69
+ nonlinearity=nonlinearity)
70
+
71
+ if not is_rnn and hasattr(module, 'bias') and module.bias is not None:
72
+ nn.init.constant_(module.bias, bias)
73
+
74
+
75
+ def bilinear_kernel(in_channels, out_channels, kernel_size):
76
+ factor = (kernel_size + 1) // 2
77
+ if kernel_size % 2 == 1:
78
+ center = factor - 1
79
+ else:
80
+ center = factor - 0.5
81
+ og = (torch.arange(kernel_size).reshape(-1, 1),
82
+ torch.arange(kernel_size).reshape(1, -1))
83
+ filt = (1 - torch.abs(og[0] - center) / factor) * \
84
+ (1 - torch.abs(og[1] - center) / factor)
85
+ weight = torch.zeros((in_channels, out_channels,
86
+ kernel_size, kernel_size))
87
+ weight[range(in_channels), range(out_channels), :, :] = filt
88
+ return weight
89
+
90
+
91
+ def init_weights(m):
92
+ # for m in modules:
93
+
94
+ if isinstance(m, nn.Conv2d):
95
+ kaiming_init(m)
96
+ elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
97
+ constant_init(m, 1)
98
+ elif isinstance(m, nn.Linear):
99
+ xavier_init(m)
100
+ elif isinstance(m, (nn.LSTM, nn.LSTMCell)):
101
+ kaiming_init(m, is_rnn=True)
102
+ # elif isinstance(m, nn.ConvTranspose2d):
103
+ # m.weight.data.copy_(bilinear_kernel(m.in_channels, m.out_channels, 4));
utils/yolov5_utils.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ import pkg_resources as pkg
5
+ import torch.nn.functional as F
6
+ import cv2
7
+ import numpy as np
8
+ import time
9
+ import torchvision
10
+
11
+ def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
12
+ # scales img(bs,3,y,x) by ratio constrained to gs-multiple
13
+ if ratio == 1.0:
14
+ return img
15
+ else:
16
+ h, w = img.shape[2:]
17
+ s = (int(h * ratio), int(w * ratio)) # new size
18
+ img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
19
+ if not same_shape: # pad/crop img
20
+ h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w))
21
+ return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
22
+
23
+ def fuse_conv_and_bn(conv, bn):
24
+ # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
25
+ fusedconv = nn.Conv2d(conv.in_channels,
26
+ conv.out_channels,
27
+ kernel_size=conv.kernel_size,
28
+ stride=conv.stride,
29
+ padding=conv.padding,
30
+ groups=conv.groups,
31
+ bias=True).requires_grad_(False).to(conv.weight.device)
32
+
33
+ # prepare filters
34
+ w_conv = conv.weight.clone().view(conv.out_channels, -1)
35
+ w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
36
+ fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
37
+
38
+ # prepare spatial bias
39
+ b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
40
+ b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
41
+ fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
42
+
43
+ return fusedconv
44
+
45
+ def check_anchor_order(m):
46
+ # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
47
+ a = m.anchors.prod(-1).view(-1) # anchor area
48
+ da = a[-1] - a[0] # delta a
49
+ ds = m.stride[-1] - m.stride[0] # delta s
50
+ if da.sign() != ds.sign(): # same order
51
+ m.anchors[:] = m.anchors.flip(0)
52
+
53
+ def initialize_weights(model):
54
+ for m in model.modules():
55
+ t = type(m)
56
+ if t is nn.Conv2d:
57
+ pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
58
+ elif t is nn.BatchNorm2d:
59
+ m.eps = 1e-3
60
+ m.momentum = 0.03
61
+ elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
62
+ m.inplace = True
63
+
64
+ def make_divisible(x, divisor):
65
+ # Returns nearest x divisible by divisor
66
+ if isinstance(divisor, torch.Tensor):
67
+ divisor = int(divisor.max()) # to int
68
+ return math.ceil(x / divisor) * divisor
69
+
70
+ def intersect_dicts(da, db, exclude=()):
71
+ # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
72
+ return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
73
+
74
+ def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False):
75
+ # Check version vs. required version
76
+ current, minimum = (pkg.parse_version(x) for x in (current, minimum))
77
+ result = (current == minimum) if pinned else (current >= minimum) # bool
78
+ if hard: # assert min requirements met
79
+ assert result, f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed'
80
+ else:
81
+ return result
82
+
83
+ class Colors:
84
+ # Ultralytics color palette https://ultralytics.com/
85
+ def __init__(self):
86
+ # hex = matplotlib.colors.TABLEAU_COLORS.values()
87
+ hex = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
88
+ '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
89
+ self.palette = [self.hex2rgb('#' + c) for c in hex]
90
+ self.n = len(self.palette)
91
+
92
+ def __call__(self, i, bgr=False):
93
+ c = self.palette[int(i) % self.n]
94
+ return (c[2], c[1], c[0]) if bgr else c
95
+
96
+ @staticmethod
97
+ def hex2rgb(h): # rgb order (PIL)
98
+ return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
99
+
100
+ def box_iou(box1, box2):
101
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
102
+ """
103
+ Return intersection-over-union (Jaccard index) of boxes.
104
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
105
+ Arguments:
106
+ box1 (Tensor[N, 4])
107
+ box2 (Tensor[M, 4])
108
+ Returns:
109
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
110
+ IoU values for every element in boxes1 and boxes2
111
+ """
112
+
113
+ def box_area(box):
114
+ # box = 4xn
115
+ return (box[2] - box[0]) * (box[3] - box[1])
116
+
117
+ area1 = box_area(box1.T)
118
+ area2 = box_area(box2.T)
119
+
120
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
121
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
122
+ return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
123
+
124
+ def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
125
+ labels=(), max_det=300):
126
+ """Runs Non-Maximum Suppression (NMS) on inference results
127
+
128
+ Returns:
129
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls]
130
+ """
131
+
132
+ if isinstance(prediction, np.ndarray):
133
+ prediction = torch.from_numpy(prediction)
134
+
135
+ nc = prediction.shape[2] - 5 # number of classes
136
+ xc = prediction[..., 4] > conf_thres # candidates
137
+
138
+ # Checks
139
+ assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'
140
+ assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'
141
+
142
+ # Settings
143
+ min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
144
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
145
+ time_limit = 10.0 # seconds to quit after
146
+ redundant = True # require redundant detections
147
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
148
+ merge = False # use merge-NMS
149
+
150
+ t = time.time()
151
+ output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
152
+ for xi, x in enumerate(prediction): # image index, image inference
153
+ # Apply constraints
154
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
155
+ x = x[xc[xi]] # confidence
156
+
157
+ # Cat apriori labels if autolabelling
158
+ if labels and len(labels[xi]):
159
+ l = labels[xi]
160
+ v = torch.zeros((len(l), nc + 5), device=x.device)
161
+ v[:, :4] = l[:, 1:5] # box
162
+ v[:, 4] = 1.0 # conf
163
+ v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
164
+ x = torch.cat((x, v), 0)
165
+
166
+ # If none remain process next image
167
+ if not x.shape[0]:
168
+ continue
169
+
170
+ # Compute conf
171
+ x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
172
+
173
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
174
+ box = xywh2xyxy(x[:, :4])
175
+
176
+ # Detections matrix nx6 (xyxy, conf, cls)
177
+ if multi_label:
178
+ i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
179
+ x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
180
+ else: # best class only
181
+ conf, j = x[:, 5:].max(1, keepdim=True)
182
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
183
+
184
+ # Filter by class
185
+ if classes is not None:
186
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
187
+
188
+ # Apply finite constraint
189
+ # if not torch.isfinite(x).all():
190
+ # x = x[torch.isfinite(x).all(1)]
191
+
192
+ # Check shape
193
+ n = x.shape[0] # number of boxes
194
+ if not n: # no boxes
195
+ continue
196
+ elif n > max_nms: # excess boxes
197
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
198
+
199
+ # Batched NMS
200
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
201
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
202
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
203
+ if i.shape[0] > max_det: # limit detections
204
+ i = i[:max_det]
205
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
206
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
207
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
208
+ weights = iou * scores[None] # box weights
209
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
210
+ if redundant:
211
+ i = i[iou.sum(1) > 1] # require redundancy
212
+
213
+ output[xi] = x[i]
214
+ if (time.time() - t) > time_limit:
215
+ print(f'WARNING: NMS time limit {time_limit}s exceeded')
216
+ break # time limit exceeded
217
+
218
+ return output
219
+
220
+ def xywh2xyxy(x):
221
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
222
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
223
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
224
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
225
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
226
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
227
+ return y
228
+
229
+ DEFAULT_LANG_LIST = ['eng', 'ja']
230
+ def draw_bbox(pred, img, lang_list=None):
231
+ if lang_list is None:
232
+ lang_list = DEFAULT_LANG_LIST
233
+ lw = max(round(sum(img.shape) / 2 * 0.003), 2) # line width
234
+ pred = pred.astype(np.int32)
235
+ colors = Colors()
236
+ img = np.copy(img)
237
+ for ii, obj in enumerate(pred):
238
+ p1, p2 = (obj[0], obj[1]), (obj[2], obj[3])
239
+ label = lang_list[obj[-1]] + str(ii+1)
240
+ cv2.rectangle(img, p1, p2, colors(obj[-1], bgr=True), lw, lineType=cv2.LINE_AA)
241
+ t_w, t_h = cv2.getTextSize(label, 0, fontScale=lw / 3, thickness=lw)[0]
242
+ cv2.putText(img, label, (p1[0], p1[1] + t_h + 2), 0, lw / 3, colors(obj[-1], bgr=True), max(lw-1, 1), cv2.LINE_AA)
243
+ return img