├── LICENSE
├── README.md
├── main.py
├── requirements.txt
└── src
├── calculate_metrics.py
├── camera.py
├── detect.py
├── train.py
└── xml_to_txt.py
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # YOLO Train and Detect App “Complete Your Learning and Detection Seamlessly on This GUI”
3 |
4 | 🎉 **NEW: 2025/05/29 ** We now support YOLOv12! Train and detect with the latest YOLO version. 🎉
5 |
6 | 
7 |
8 | This application is a user-friendly GUI tool built with PyTorch, Ultralytics library, and CustomTkinter. It allows you to easily develop and train models such as YOLOv12, and perform object detection on images, videos, and webcam feeds using the trained models. The detection results can be saved for further analysis.
9 |
10 | ↓ Please watch the instructional video (in English) uploaded on YouTube to check out the specific operation.
11 | [](https://youtu.be/Jk-JkBn4Na0?si=hMqGkJ4YAjnaKbQW)
12 |
13 | ## Environment Setup
14 |
15 | ### Using venv
16 |
17 | 1. Clone this repository:
18 | ```bash
19 | git clone https://github.com/SpreadKnowledge/YOLO_train_detection_GUI.git
20 | ```
21 | 2. Navigate to the project directory:
22 | ```bash
23 | cd your-repository
24 | ```
25 | 3. Create a virtual environment:
26 | ```bash
27 | python -m venv venv
28 | ```
29 | 4. Activate the virtual environment:
30 | - For Windows:
31 | ```
32 | venv\Scripts\activate
33 | ```
34 | - For macOS and Linux:
35 | ```
36 | source venv/bin/activate
37 | ```
38 |
39 | 5. Install the required dependencies:
40 | ```bash
41 | pip install -r requirements.txt
42 | ```
43 |
44 | ### Using Anaconda
45 |
46 | 1. Clone this repository:
47 | ```bash
48 | git clone https://github.com/SpreadKnowledge/YOLO_train_detection_GUI.git
49 | ```
50 | 2. Navigate to the project directory:
51 | ```bash
52 | cd your-repository
53 | ```
54 | 3. Create a new Anaconda environment:
55 | ```bash
56 | conda create --name yolo-app python=3.12
57 | ```
58 | 4. Activate the Anaconda environment:
59 | ```bash
60 | conda activate yolo-app
61 | ```
62 | 5. Install the required dependencies:
63 | ```bash
64 | pip install -r requirements.txt
65 | ```
66 |
67 | ## Preparing Training Data
68 |
69 | Before training your YOLO model, you need to prepare the training data in the YOLO format. For each image, you should have a corresponding text file with the same name containing the object annotations. The text file should follow the format:
70 | ```plaintext
71 |
72 | ```
73 | - ``: Integer representing the class ID of the object.
74 | - ``, ``: Floating-point values representing the center coordinates of the object bounding box, normalized by the image width and height.
75 | - ``, ``: Floating-point values representing the width and height of the object bounding box, normalized by the image width and height.
76 |
77 | Place the image files and their corresponding annotation text files in the same directory.
78 |
79 | ## Running the Application
80 |
81 | To run the YOLO Train and Detect App, execute the following command:
82 | ```bash
83 | python main.py
84 | ```
85 |
86 | ## Application Features
87 |
88 | ### Train Tab
89 |
90 | In the Train tab, you can train your own YOLO model:
91 |
92 | 1. Enter a project name (alphanumeric only).
93 | 2. Select the directory containing your training data (images and annotation text files).
94 | 3. Choose the directory where you want to save the trained model.
95 | 4. Select the model size for YOLOv9 (Compact or Enhanced) or YOLOv8 (Nano, Small, Medium, Large, or ExtraLarge).
96 | 5. Specify the input size for the CNN (e.g., 640).
97 | 6. Set the number of epochs for training (e.g., 100).
98 | 7. Enter the batch size for training (e.g., 16).
99 | 8. Input the class names, one per line, in the provided text box.
100 | 9. Click the "Start Training!" button to begin the training process.
101 |
102 | Note: Make sure to provide all the required information, or the training process will not start.
103 |
104 | ### Image/Video Tab
105 |
106 | In the Image/Video tab, you can perform object detection on images or videos:
107 |
108 | 1. Select the folder containing the images or videos you want to process.
109 | 2. Choose the trained YOLO model file (.pt) for detection.
110 | 3. Click the "Start Detection!" button to initiate the detection process.
111 | 4. The detection results will be displayed in the application window.
112 | 5. Use the navigation buttons (◀ and ▶) to browse through the processed images or video frames.
113 |
114 | Note: Ensure that you have selected the correct folders and model file, or the detection process will not work.
115 |
116 | ### Camera Tab
117 |
118 | In the Camera tab, you can perform real-time object detection using a webcam:
119 |
120 | 1. Select the trained YOLO model file (.pt) for detection.
121 | 2. Choose the directory where you want to save the detection results.
122 | 3. Enter the camera ID (e.g., 0 for the default webcam).
123 | 4. Click the "START" button to begin the real-time detection.
124 | 5. The live camera feed with object detection will be displayed in the application window.
125 | 6. Press the "ENTER" key to capture and save the current frame and its detection results.
126 | 7. Click the "STOP" button to stop the real-time detection.
127 |
128 | Note: Make sure that you have selected the correct model file and save directory, and entered a valid camera ID, or the real-time detection will not function properly.
129 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | # version 0.1.1
2 |
3 | import os
4 | import cv2
5 | import customtkinter as ctk
6 | import tkinter as tk
7 | from tkinter import filedialog, IntVar, Label, messagebox
8 | from PIL import Image, ImageTk
9 | import ctypes
10 | import threading
11 | import subprocess
12 | import datetime
13 | import locale
14 | import mimetypes
15 | from pathlib import Path
16 | from queue import Queue, Empty
17 | from src.train import create_yaml
18 | from src.detect import detect_images, is_valid_image
19 | from src.camera import CameraDetection
20 |
21 | # Initialize mimetypes
22 | mimetypes.init()
23 |
24 | project_name = ""
25 | train_data_path = ""
26 | model_save_path = ""
27 | selected_model_size = ""
28 | input_size = ""
29 | epochs = ""
30 | class_names = []
31 | image_paths = []
32 | current_image_index = 0
33 | image_label = None
34 | selected_model_var = None
35 |
36 | global start_train_button, detection_progress_bar, image_index_label, camera_detection, detection_model_path, detection_save_dir, camera_id_entry
37 |
38 | def get_screen_size():
39 | user32 = ctypes.windll.user32
40 | screen_width = user32.GetSystemMetrics(0)
41 | screen_height = user32.GetSystemMetrics(1)
42 | return screen_width, screen_height
43 |
44 | def clear_frame(frame):
45 | for widget in frame.winfo_children():
46 | widget.destroy()
47 |
48 | def read_output(process, queue):
49 | for line in iter(process.stdout.readline, b''):
50 | queue.put(line.decode('utf-8'))
51 | process.stdout.close()
52 |
53 | def on_sidebar_select(window_title):
54 | clear_frame(main_frame)
55 | if window_title == "Train":
56 | show_ai_train_window()
57 | elif window_title == "Image/Video":
58 | show_image_detection_window()
59 | elif window_title == "Camera Detection":
60 | show_camera_detection_window()
61 |
62 | output_queue = Queue()
63 |
64 | def enqueue_output(out, queue):
65 | for line in iter(out.readline, ''):
66 | queue.put(line)
67 | out.close()
68 |
69 | def update_output_textbox():
70 | try:
71 | line = output_queue.get_nowait()
72 | output_textbox.insert("end", line)
73 | output_textbox.yview_moveto(1)
74 | except Empty:
75 | pass
76 | finally:
77 | root.after(100, update_output_textbox)
78 |
79 | def update_image():
80 | global current_image_index, image_label, image_paths, image_index_label
81 | if image_paths:
82 | image_index_text = f"{current_image_index + 1}/{len(image_paths)}"
83 | image_index_label.configure(text=image_index_text)
84 | img = Image.open(image_paths[current_image_index])
85 | img_w, img_h = img.size
86 | max_w, max_h = image_label.winfo_width(), image_label.winfo_height() # Use the size of the image_label widget
87 | scale_w = max_w / img_w
88 | scale_h = max_h / img_h
89 | scale = min(scale_w, scale_h)
90 | img = img.resize((int(img_w * scale), int(img_h * scale)), Image.Resampling.LANCZOS)
91 | photo = ImageTk.PhotoImage(img)
92 | image_label.config(image=photo)
93 | image_label.image = photo
94 |
95 | def show_next_image():
96 | global current_image_index, image_paths
97 | if image_paths:
98 | current_image_index = (current_image_index + 1) % len(image_paths)
99 | update_image()
100 |
101 | def show_prev_image():
102 | global current_image_index, image_paths
103 | if image_paths:
104 | current_image_index = (current_image_index - 1) % len(image_paths)
105 | update_image()
106 |
107 | def start_training_and_capture_output(yaml_path, selected_model_size):
108 | global project_name, class_names, input_size, batch_size, epochs, model_save_path
109 |
110 | def run_training():
111 | nonlocal process
112 | if not all([project_name, train_data_path, class_names, model_save_path, selected_model_size, input_size, epochs, batch_size]):
113 | print("Error: One or more required parameters are missing.")
114 | return
115 |
116 | cmd_args = [
117 | 'python', 'src/train.py',
118 | project_name, train_data_path, ','.join(class_names),
119 | model_save_path, selected_model_size, str(input_size),
120 | str(epochs), yaml_path, str(batch_size)
121 | ]
122 |
123 | process = subprocess.Popen(
124 | cmd_args,
125 | stdout=subprocess.PIPE,
126 | stderr=subprocess.STDOUT,
127 | text=True,
128 | encoding='utf-8',
129 | errors='replace'
130 | )
131 | threading.Thread(target=enqueue_output, args=(process.stdout, output_queue), daemon=True).start()
132 | process.wait()
133 | progress_bar.stop()
134 |
135 | process = None
136 | threading.Thread(target=run_training, daemon=True).start()
137 | progress_bar.start()
138 |
139 | def show_ai_train_window():
140 | global project_name_entry, input_size_entry, epochs_entry, batch_size_entry, class_names_text, progress_bar, output_textbox, start_train_button, selected_model_var
141 |
142 | main_frame.pack_forget()
143 | main_frame.pack(fill="both", expand=True)
144 |
145 | # プロジェクト名入力
146 | ctk.CTkLabel(master=main_frame, text="Project Name: プロジェクト名(半角英数)", font=("Roboto Medium", 18)).place(relx=0.2, rely=0.03, anchor=ctk.CENTER)
147 | project_name_entry = ctk.CTkEntry(master=main_frame, placeholder_text="Project Name", width=250, height=50, font=("Roboto Medium", 18))
148 | project_name_entry.place(relx=0.2, rely=0.06, relwidth=0.3, relheight=0.04, anchor=ctk.CENTER)
149 |
150 | # トレーニングデータ選択ボタン
151 | ctk.CTkLabel(master=main_frame, text="Select Train data: 学習データの選択", font=("Roboto Medium", 18)).place(relx=0.2, rely=0.10, anchor=ctk.CENTER)
152 | train_data_button = ctk.CTkButton(master=main_frame, text="Select Train Data", command=select_train_data, border_color='black', border_width=2, font=("Roboto Medium", 24), text_color='white')
153 | train_data_button.place(relx=0.2, rely=0.13, relwidth=0.3, relheight=0.04, anchor=ctk.CENTER)
154 |
155 | # モデル保存先選択ボタン
156 | ctk.CTkLabel(master=main_frame, text="Select Save Folder: モデルの保存先の選択", font=("Roboto Medium", 18)).place(relx=0.2, rely=0.17, anchor=ctk.CENTER)
157 | model_save_button = ctk.CTkButton(master=main_frame, text="Select Model's Save Folder", command=select_model_save_folder, border_color='black', border_width=2, font=("Roboto Medium", 24), text_color='white')
158 | model_save_button.place(relx=0.2, rely=0.2, relwidth=0.3, relheight=0.04, anchor=ctk.CENTER)
159 |
160 | # モデル選択ドロップダウン
161 | ctk.CTkLabel(master=main_frame, text="Select YOLO Model: YOLOのモデル選択", font=("Roboto Medium", 18)).place(relx=0.2, rely=0.26, anchor=ctk.CENTER)
162 | model_options = ["YOLOv8-Nano", "YOLOv8-Small", "YOLOv8-Medium", "YOLOv8-Large", "YOLOv8-ExtraLarge",
163 | "YOLOv9-Compact", "YOLOv9-Enhanced",
164 | "YOLOv10-Nano", "YOLOv10-Small", "YOLOv10-Medium", "YOLOv10-Balanced", "YOLOv10-Large", "YOLOv10-ExtraLarge",
165 | "YOLOv11-Nano", "YOLOv11-Small", "YOLOv11-Medium","YOLOv11-Large","YOLOv11-ExtraLarge",
166 | "YOLOv12-Nano", "YOLOv12-Small", "YOLOv12-Medium","YOLOv12-Large","YOLOv12-ExtraLarge"]
167 | selected_model_var = ctk.StringVar(value=model_options[0])
168 | border_frame = ctk.CTkFrame(master=main_frame, fg_color="black", width=254, height=44)
169 | border_frame.place(relx=0.2, rely=0.29, anchor=ctk.CENTER)
170 | model_menu = ctk.CTkOptionMenu(
171 | master=border_frame,
172 | variable=selected_model_var,
173 | values=model_options,
174 | font=("Roboto Medium", 18),
175 | dropdown_font=("Roboto Medium", 18),
176 | button_color="white",
177 | button_hover_color="lightgray",
178 | dropdown_hover_color="lightgray",
179 | width=250,
180 | height=40,
181 | )
182 | model_menu.place(relx=0.5, rely=0.5, anchor=ctk.CENTER)
183 |
184 | # CNNの入力層のサイズ指定
185 | ctk.CTkLabel(master=main_frame, text="CNN Input Size: CNNの入力層のサイズ 【Ex: 640】", font=("Roboto Medium", 18)).place(relx=0.2, rely=0.39, anchor=ctk.CENTER)
186 | input_size_entry = ctk.CTkEntry(master=main_frame, placeholder_text="Input Size", font=("Roboto Medium", 18))
187 | input_size_entry.place(relx=0.2, rely=0.42, relwidth=0.3, relheight=0.04, anchor=ctk.CENTER)
188 |
189 | # エポック数
190 | ctk.CTkLabel(master=main_frame, text="Epochs: エポック数 【Ex: 100】", font=("Roboto Medium", 18)).place(relx=0.2, rely=0.46, anchor=ctk.CENTER)
191 | epochs_entry = ctk.CTkEntry(master=main_frame, placeholder_text="Epochs", font=("Roboto Medium", 18))
192 | epochs_entry.place(relx=0.2, rely=0.49, relwidth=0.3, relheight=0.04, anchor=ctk.CENTER)
193 |
194 | # バッチサイズ
195 | ctk.CTkLabel(master=main_frame, text="Batch Size: バッチサイズ 【Ex: 16】", font=("Roboto Medium", 18)).place(relx=0.2, rely=0.53, anchor=ctk.CENTER)
196 | batch_size_entry = ctk.CTkEntry(master=main_frame, placeholder_text="Batch size", font=("Roboto Medium", 18))
197 | batch_size_entry.place(relx=0.2, rely=0.56, relwidth=0.3, relheight=0.04, anchor=ctk.CENTER)
198 |
199 | # クラス名入力ウィンドウ
200 | ctk.CTkLabel(master=main_frame, text="Class name: クラス名", font=("Roboto Medium", 18)).place(relx=0.2, rely=0.60, anchor=ctk.CENTER)
201 | class_names_text = ctk.CTkTextbox(master=main_frame, font=("Roboto Medium", 18))
202 | class_names_text.place(relx=0.2, rely=0.7, relwidth=0.3, relheight=0.17, anchor=ctk.CENTER)
203 |
204 | # 学習開始ボタン
205 | start_train_button = ctk.CTkButton(master=main_frame, text="Start Training!", command=start_training, fg_color="chocolate1",border_color='black', border_width=3, font=("Roboto Medium", 44, "bold"), text_color='white')
206 | start_train_button.place(relx=0.2, rely=0.84, relwidth=0.4, relheight=0.08, anchor=ctk.CENTER)
207 |
208 | # トレーニング進捗表示ウィンドウ
209 | output_textbox = ctk.CTkTextbox(master=main_frame, corner_radius=20, font=("Roboto Medium", 14))
210 | output_textbox.place(relx=0.7, rely=0.45, relwidth=0.58, relheight=0.86, anchor=ctk.CENTER)
211 |
212 | # プログレスバー
213 | progress_bar = ctk.CTkProgressBar(master=main_frame, progress_color='limegreen', mode='indeterminate', indeterminate_speed=0.7)
214 | progress_bar.place(relx=0.5, rely=0.94, relwidth=0.7, anchor=ctk.CENTER)
215 |
216 | def show_image_detection_window():
217 | global detection_images_folder_path, detection_model_path, image_label, detection_progress_bar, image_index_label
218 | clear_frame(main_frame)
219 | main_frame.pack(fill="both", expand=True)
220 |
221 | # 検出画像表示ウィンドウの設定
222 | image_label = Label(main_frame)
223 | image_label.place(relx=0.5, rely=0.44, relwidth=0.9, relheight=0.84, anchor=ctk.CENTER)
224 |
225 | # 画像フォルダの指定ボタンの設定
226 | select_images_folder_button = ctk.CTkButton(
227 | master=main_frame,
228 | text="Select Image Folder",
229 | command=select_detection_images_folder,
230 | border_color='black',
231 | border_width=2,
232 | font=("Roboto Medium", 22),
233 | text_color='white',
234 | )
235 | select_images_folder_button.place(relx=0.05, rely=0.9, relwidth=0.15, relheight=0.05)
236 |
237 | # モデル選択ボタンの設定
238 | select_model_button = ctk.CTkButton(
239 | master=main_frame,
240 | text="Select Model",
241 | command=select_detection_model,
242 | border_color='black',
243 | border_width=2,
244 | font=("Roboto Medium", 22),
245 | text_color='white',
246 | )
247 | select_model_button.place(relx=0.22, rely=0.9, relwidth=0.15, relheight=0.05)
248 |
249 | # 物体検出開始ボタンの設定
250 | start_detection_button = ctk.CTkButton(
251 | master=main_frame,
252 | text="Start Detection!",
253 | command=lambda: [detection_progress_bar.start(), start_image_detection()],
254 | fg_color="chocolate1",
255 | border_color='black',
256 | border_width=2,
257 | font=("Roboto Medium", 34),
258 | text_color='white',
259 | )
260 | start_detection_button.place(relx=0.42, rely=0.89, relwidth=0.18, relheight=0.07)
261 |
262 | # 「前へ」ボタンの設定
263 | prev_button = ctk.CTkButton(master=main_frame, text="◀", command=show_prev_image, fg_color="DeepSkyBlue2", border_color='black', border_width=2, font=("Roboto Medium", 40), text_color='white')
264 | prev_button.place(relx=0.65, rely=0.9, relwidth=0.08, relheight=0.05)
265 |
266 | # 「次へ」ボタンの設定
267 | next_button = ctk.CTkButton(master=main_frame, text="▶", command=show_next_image, fg_color="DeepSkyBlue2", border_color='black', border_width=2, font=("Roboto Medium", 40), text_color='white')
268 | next_button.place(relx=0.75, rely=0.9, relwidth=0.08, relheight=0.05)
269 |
270 | # 画像インデックスを表示するラベルの初期化と配置
271 | image_index_label = ctk.CTkLabel(master=main_frame, text=" ", font=("Roboto Medium", 34))
272 | image_index_label.place(relx=0.85, rely=0.9, relwidth=0.1, relheight=0.05)
273 |
274 | # プログレスバーの設定
275 | detection_progress_bar = ctk.CTkProgressBar(master=main_frame, progress_color='limegreen', mode='indeterminate')
276 | detection_progress_bar.place(relx=0.5, rely=0.98, relwidth=0.7, anchor=ctk.CENTER)
277 |
278 | def show_camera_detection_window():
279 | global camera_detection, detection_model_path, detection_save_dir, camera_id_entry, start_detection_button, image_label
280 |
281 | clear_frame(main_frame)
282 | main_frame.pack(fill="both", expand=True)
283 |
284 | camera_detection = None
285 |
286 | # Camera Stream Display
287 | image_label = Label(main_frame)
288 | image_label.place(relx=0.5, rely=0.48, relwidth=0.99, relheight=0.94, anchor=ctk.CENTER)
289 |
290 | # Select Model Button
291 | select_model_button = ctk.CTkButton(
292 | master=main_frame,
293 | text="Select Model",
294 | command=select_detection_model,
295 | border_color='black',
296 | border_width=2,
297 | font=("Roboto Medium", 20),
298 | text_color='white',
299 | )
300 | select_model_button.place(relx=0.04, rely=0.96, relwidth=0.12, relheight=0.03)
301 |
302 | # Select Save Folder Button
303 | select_save_folder_button = ctk.CTkButton(
304 | master=main_frame,
305 | text="Select Save Folder",
306 | command=select_camera_save_folder,
307 | border_color='black',
308 | border_width=2,
309 | font=("Roboto Medium", 20),
310 | text_color='white',
311 | )
312 | select_save_folder_button.place(relx=0.175, rely=0.96, relwidth=0.12, relheight=0.03)
313 |
314 | # Camera ID Entry
315 | camera_id_entry = ctk.CTkEntry(master=main_frame, placeholder_text="Camera ID (Ex: 0)", font=("Roboto Medium", 18))
316 | camera_id_entry.place(relx=0.32, rely=0.96, relwidth=0.12, relheight=0.03)
317 |
318 | # Start Detection Button
319 | start_detection_button = ctk.CTkButton(
320 | master=main_frame,
321 | text="START",
322 | command=start_camera_detection,
323 | fg_color="green",
324 | border_color='black',
325 | border_width=2,
326 | font=("Roboto Medium", 28),
327 | text_color='white',
328 | )
329 | start_detection_button.place(relx=0.8, rely=0.96, relwidth=0.15, relheight=0.03)
330 |
331 | instructions_label = ctk.CTkLabel(
332 | master=main_frame,
333 | text="Press ENTER to capture and save detection result.",
334 | font=("Roboto Medium", 14)
335 | )
336 | instructions_label.place(relx=0.6, rely=0.98, anchor=ctk.CENTER)
337 |
338 | root.bind('', lambda event: save_callback())
339 |
340 | image_label.update_idletasks()
341 | image_label.update()
342 |
343 | def normalize_path(path):
344 | if not path:
345 | return path
346 | return str(Path(path).resolve())
347 |
348 | def select_train_data():
349 | global train_data_path
350 | train_data_path = normalize_path(filedialog.askdirectory())
351 |
352 | def select_model_save_folder():
353 | global model_save_path
354 | model_save_path = normalize_path(filedialog.askdirectory())
355 |
356 | def select_detection_images_folder():
357 | global detection_images_folder_path
358 | detection_images_folder_path = normalize_path(filedialog.askdirectory())
359 | if detection_images_folder_path:
360 | print(f"Selected folder: {detection_images_folder_path}")
361 |
362 | def select_detection_model():
363 | global detection_model_path
364 | detection_model_path = normalize_path(filedialog.askopenfilename(filetypes=[("YOLOv8 Model", "*.pt")]))
365 | if detection_model_path:
366 | print(f"Selected model: {detection_model_path}")
367 |
368 | def select_camera_save_folder():
369 | global detection_save_dir
370 | detection_save_dir = normalize_path(filedialog.askdirectory())
371 | if detection_save_dir and camera_detection:
372 | camera_detection.set_save_directory(detection_save_dir)
373 | print(f"Selected save folder: {detection_save_dir}")
374 |
375 | def select_detection_yaml():
376 | global detection_yaml_path
377 | detection_yaml_path = filedialog.askopenfilename(filetypes=[("YAML Files", "*.yaml")])
378 | if detection_yaml_path:
379 | print(f"Selected YAML: {detection_yaml_path}")
380 |
381 | def animate_progress_bar(progress, step):
382 | if progress >= 100 or progress <= 0:
383 | step = -step
384 |
385 | progress_bar.set(progress)
386 | root.after(50, animate_progress_bar, progress + step, step)
387 |
388 | def model_name_to_type(model_name):
389 | model_map = {
390 | "YOLOv8-Nano": "yolov8n", "YOLOv8-Small": "yolov8s", "YOLOv8-Medium": "yolov8m", "YOLOv8-Large": "yolov8l", "YOLOv8-ExtraLarge": "yolov8x",
391 | "YOLOv9-Compact": "yolov9c", "YOLOv9-Enhanced": "yolov9e",
392 | "YOLOv10-Nano": "yolov10n", "YOLOv10-Small": "yolov10s", "YOLOv10-Medium": "yolov10m", "YOLOv10-Balanced": "yolov10b", "YOLOv10-Large": "yolov10l", "YOLOv10-ExtraLarge": "yolov10x",
393 | "YOLOv11-Nano": "yolo11n", "YOLOv11-Small": "yolo11s", "YOLOv11-Medium": "yolo11m", "YOLOv11-Large": "yolo11l", "YOLOv11-ExtraLarge": "yolo11x",
394 | "YOLOv12-Nano": "yolo12n", "YOLOv12-Small": "yolo12s", "YOLOv12-Medium": "yolo12m", "YOLOv12-Large": "yolo12l", "YOLOv12-ExtraLarge": "yolo12x",
395 | }
396 | return model_map.get(model_name, "")
397 |
398 | def start_training():
399 | global project_name, train_data_path, model_save_path, selected_model_var, input_size, epochs, batch_size, class_names
400 | project_name = project_name_entry.get()
401 | input_size = input_size_entry.get()
402 | epochs = epochs_entry.get()
403 | batch_size = batch_size_entry.get()
404 | class_names = class_names_text.get("1.0", "end-1c").split('\n')
405 | class_names = [name for name in class_names if name.strip() != '']
406 |
407 | selected_model_size = model_name_to_type(selected_model_var.get())
408 |
409 | if not all([project_name, train_data_path, model_save_path, selected_model_size, input_size, epochs, batch_size, class_names]):
410 | print("Error: One or more required parameters are missing.")
411 | return
412 |
413 | yaml_path = create_yaml(project_name, train_data_path, class_names, model_save_path)
414 | start_training_and_capture_output(yaml_path, selected_model_size)
415 |
416 | def start_image_detection():
417 | global detection_images_folder_path, detection_model_path
418 | threading.Thread(target=detect_images, args=(detection_images_folder_path, detection_model_path, update_image_list), daemon=True).start()
419 |
420 | def update_image_list(results_dir):
421 | global image_paths, current_image_index, detection_progress_bar
422 |
423 | # Find all valid images in the results directory
424 | image_paths = []
425 | for file_path in Path(results_dir).iterdir():
426 | if file_path.is_file() and is_valid_image(str(file_path)):
427 | image_paths.append(str(file_path))
428 |
429 | current_image_index = 0
430 | update_image()
431 | detection_progress_bar.stop()
432 |
433 | def start_camera_detection():
434 | global camera_detection, camera_id_entry, start_detection_button, image_label
435 |
436 | start_detection_button.configure(text="STOP", fg_color="red", command=stop_camera_detection)
437 | root.update()
438 |
439 | camera_id = int(camera_id_entry.get())
440 | try:
441 | camera_detection = CameraDetection(detection_model_path)
442 | camera_detection.start_camera(camera_id)
443 | camera_detection.show_camera_stream(image_label)
444 | except ValueError as e:
445 | image_label.config(text="No Camera", fg_color="red")
446 | start_detection_button.configure(text="START", fg_color="green", command=start_camera_detection)
447 |
448 | def stop_camera_detection():
449 | global camera_detection, start_detection_button
450 | camera_detection.stop()
451 | start_detection_button.configure(text="START", fg_color="green", command=start_camera_detection)
452 |
453 | def save_callback():
454 | if camera_detection:
455 | if detection_save_dir:
456 | camera_detection.set_save_directory(detection_save_dir)
457 | camera_detection.capture_frame()
458 | else:
459 | print("Camera detection not started")
460 |
461 | def capture_frame(self):
462 | if not self.cap:
463 | return
464 |
465 | ret, frame = self.cap.read()
466 | if not ret:
467 | return
468 |
469 | self.scene_id += 1
470 | timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
471 | base_filename = f"{timestamp}_{self.scene_id:04d}"
472 |
473 | # Use pathlib for path handling
474 | save_dir_path = Path(self.save_dir)
475 | origin_image_path = str(save_dir_path / f"{base_filename}_origin.jpg")
476 | cv2.imwrite(origin_image_path, frame)
477 |
478 | results = self.model(frame)
479 | self._draw_bounding_boxes(frame, results)
480 |
481 | detection_image_path = str(save_dir_path / f"{base_filename}_detection.jpg")
482 | cv2.imwrite(detection_image_path, frame)
483 |
484 | txt_path = str(save_dir_path / f"{base_filename}_detection.txt")
485 | with open(txt_path, 'w', encoding='utf-8') as f:
486 | for result in results[0].boxes:
487 | if result.conf[0] >= self.conf_threshold:
488 | x1, y1, x2, y2 = map(int, result.xyxy[0])
489 | label = self.model.names[int(result.cls[0])]
490 | confidence = result.conf[0]
491 | f.write(f"{label} {confidence:.2f} {x1} {y1} {x2} {y2}\n")
492 |
493 | return origin_image_path, detection_image_path, txt_path
494 |
495 | def change_appearance_mode(new_appearance_mode):
496 | ctk.set_appearance_mode(new_appearance_mode)
497 |
498 | screen_width, screen_height = get_screen_size()
499 | ctk.set_appearance_mode("light")
500 | ctk.set_default_color_theme("blue")
501 |
502 | root = ctk.CTk()
503 | root.title('YOLO Train and Detect App')
504 | root.geometry(f"{screen_width}x{screen_height}")
505 |
506 | model_size_var = IntVar(value=1)
507 |
508 | sidebar = ctk.CTkFrame(master=root, width=380, corner_radius=0)
509 | sidebar.pack(side="left", fill="y")
510 |
511 | main_frame = ctk.CTkFrame(master=root)
512 | main_frame.pack(fill="both", expand=True, padx=10, pady=10)
513 |
514 | ai_creation_button = ctk.CTkButton(master=sidebar, text="Train", command=lambda: on_sidebar_select("Train"), fg_color="dodgerblue", text_color="white", border_color='black', border_width=2, font=("Roboto Medium", 24))
515 | ai_creation_button.pack(pady=10)
516 |
517 | object_detection_button = ctk.CTkButton(master=sidebar, text="Image/Video", command=lambda: on_sidebar_select("Image/Video"), fg_color="chocolate1", text_color="white", border_color='black', border_width=2, font=("Roboto Medium", 20))
518 | object_detection_button.pack(pady=10)
519 |
520 | camera_detection_button = ctk.CTkButton(master=sidebar, text="Camera", command=lambda: on_sidebar_select("Camera Detection"), fg_color="chocolate1", text_color="white", border_color='black', border_width=2, font=("Roboto Medium", 20))
521 | camera_detection_button.pack(pady=10)
522 |
523 | app_name_label = ctk.CTkLabel(master=sidebar, text="YOLOv12", font=("Roboto Medium", 16))
524 | app_name_label.pack(pady=1)
525 | app_name_label = ctk.CTkLabel(master=sidebar, text="&", font=("Roboto Medium", 16))
526 | app_name_label.pack(pady=1)
527 | app_name_label = ctk.CTkLabel(master=sidebar, text="YOLOv11", font=("Roboto Medium", 16))
528 | app_name_label.pack(pady=1)
529 | app_name_label = ctk.CTkLabel(master=sidebar, text="&", font=("Roboto Medium", 16))
530 | app_name_label.pack(pady=1)
531 | app_name_label = ctk.CTkLabel(master=sidebar, text="YOLOv10", font=("Roboto Medium", 16))
532 | app_name_label.pack(pady=1)
533 | app_name_label = ctk.CTkLabel(master=sidebar, text="&", font=("Roboto Medium", 16))
534 | app_name_label.pack(pady=1)
535 | app_name_label = ctk.CTkLabel(master=sidebar, text="YOLOv9", font=("Roboto Medium", 16))
536 | app_name_label.pack(pady=1)
537 | app_name_label = ctk.CTkLabel(master=sidebar, text="&", font=("Roboto Medium", 16))
538 | app_name_label.pack(pady=1)
539 | app_name_label = ctk.CTkLabel(master=sidebar, text="YOLOv8", font=("Roboto Medium", 16))
540 | app_name_label.pack(pady=1)
541 |
542 | empty_space = ctk.CTkLabel(master=sidebar, text="")
543 | empty_space.pack(fill=tk.BOTH, expand=True)
544 |
545 | appearance_mode_var = ctk.StringVar(value="Light")
546 | appearance_mode_label = ctk.CTkLabel(master=sidebar, text="Appearance Mode", font=("Roboto Medium", 12))
547 | appearance_mode_label.pack(padx=10, pady=(0, 5), anchor='w')
548 |
549 | light_mode_radio = ctk.CTkRadioButton(master=sidebar, text="Light", variable=appearance_mode_var, value="Light", command=lambda: change_appearance_mode("Light"))
550 | light_mode_radio.pack(padx=10, pady=(0, 5), anchor='w')
551 |
552 | dark_mode_radio = ctk.CTkRadioButton(master=sidebar, text="Dark", variable=appearance_mode_var, value="Dark", command=lambda: change_appearance_mode("Dark"))
553 | dark_mode_radio.pack(padx=10, pady=(0, 10), anchor='w')
554 |
555 | signature_label = ctk.CTkLabel(master=sidebar, text="© SpreadKnowledge 2024", text_color="white", font=("Roboto Medium", 10))
556 | signature_label.pack(side=tk.BOTTOM, fill=tk.X, padx=5, pady=5, anchor='w')
557 |
558 | if __name__ == "__main__":
559 | root.after(100, update_output_textbox)
560 | root.mainloop()
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | customtkinter
2 | Pillow
3 | torch==2.2.1
4 | ultralytics
--------------------------------------------------------------------------------
/src/calculate_metrics.py:
--------------------------------------------------------------------------------
1 | """Precision、Recall、F値の算出コード
2 | """
3 |
4 | import os
5 | from pathlib import Path
6 | import shutil
7 | import csv
8 | from ultralytics import YOLO
9 | import numpy as np
10 | import cv2
11 | import random
12 | from typing import Dict, List, Tuple
13 |
14 | # 評価用のパラメータ設定
15 | DATASET_DIR = r"C:\Users\he81t\ubuntu\images\green_soybeans\shonai1_test_data" # データセットのディレクトリ
16 | MODEL_PATH = r"C:\Users\he81t\ubuntu\images\green_soybeans\shonai3_models\weights\best.pt" # YOLOモデルのパス
17 | CONF_THRESHOLD = 0.5 # 確信度のしきい値
18 |
19 | def create_output_dirs():
20 | """出力用のディレクトリを作成"""
21 | base_dir = Path(DATASET_DIR) / "test_results"
22 | detect_dir = base_dir / "detection_images"
23 |
24 | base_dir.mkdir(exist_ok=True)
25 | detect_dir.mkdir(exist_ok=True)
26 |
27 | return base_dir, detect_dir
28 |
29 | def generate_colors(num_classes: int) -> Dict[int, Tuple[int, int, int]]:
30 | """分類クラスごとに固定のRGBカラーを生成"""
31 | random.seed(42)
32 | colors = {}
33 | for i in range(num_classes):
34 | colors[i] = (
35 | random.randint(0, 255),
36 | random.randint(0, 255),
37 | random.randint(0, 255)
38 | )
39 | return colors
40 |
41 | def calculate_iou(box1, box2):
42 | """2つのバウンディングボックス間のIoUを計算"""
43 | # Convert to (x1, y1, x2, y2) format
44 | b1_x1, b1_y1 = box1[0] - box1[2]/2, box1[1] - box1[3]/2
45 | b1_x2, b1_y2 = box1[0] + box1[2]/2, box1[1] + box1[3]/2
46 | b2_x1, b2_y1 = box2[0] - box2[2]/2, box2[1] - box2[3]/2
47 | b2_x2, b2_y2 = box2[0] + box2[2]/2, box2[1] + box2[3]/2
48 |
49 | # Intersection area
50 | inter_x1 = max(b1_x1, b2_x1)
51 | inter_y1 = max(b1_y1, b2_y1)
52 | inter_x2 = min(b1_x2, b2_x2)
53 | inter_y2 = min(b1_y2, b2_y2)
54 |
55 | if inter_x2 < inter_x1 or inter_y2 < inter_y1:
56 | return 0.0
57 |
58 | inter_area = (inter_x2 - inter_x1) * (inter_y2 - inter_y1)
59 |
60 | # Union area
61 | b1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)
62 | b2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)
63 |
64 | return inter_area / (b1_area + b2_area - inter_area)
65 |
66 | def evaluate_detection(gt_boxes, gt_classes, pred_boxes, pred_classes, iou_threshold=0.5):
67 | """検出結果の評価を行い、Precision、Recall、F値を計算"""
68 | if len(pred_boxes) == 0:
69 | if len(gt_boxes) == 0:
70 | return 1.0, 1.0, 1.0
71 | return 0.0, 0.0, 0.0
72 |
73 | if len(gt_boxes) == 0:
74 | return 0.0, 0.0, 0.0
75 |
76 | true_positives = 0
77 | used_gt = set()
78 |
79 | for pred_idx, pred in enumerate(pred_boxes):
80 | best_iou = 0
81 | best_gt_idx = -1
82 |
83 | for i, gt in enumerate(gt_boxes):
84 | if i in used_gt:
85 | continue
86 |
87 | iou = calculate_iou(pred, gt)
88 | # クラスが一致し、かつIoUが閾値以上の場合のみ考慮
89 | if iou > best_iou and pred_classes[pred_idx] == gt_classes[i]:
90 | best_iou = iou
91 | best_gt_idx = i
92 |
93 | if best_iou >= iou_threshold:
94 | true_positives += 1
95 | used_gt.add(best_gt_idx)
96 |
97 | precision = true_positives / len(pred_boxes)
98 | recall = true_positives / len(gt_boxes)
99 |
100 | if precision + recall == 0:
101 | f_value = 0.0
102 | else:
103 | f_value = 2 * precision * recall / (precision + recall)
104 |
105 | return precision, recall, f_value
106 |
107 | def main():
108 | model = YOLO(MODEL_PATH)
109 | num_classes = len(model.names)
110 | class_colors = generate_colors(num_classes)
111 | class_names = model.names
112 |
113 | base_dir, detect_dir = create_output_dirs()
114 | image_files = [f for f in os.listdir(DATASET_DIR) if f.endswith(('.jpg', '.jpeg', '.png'))]
115 |
116 | # 検出数カウント用のデータフレーム作成
117 | detection_counts = []
118 |
119 | total_precision = 0
120 | total_recall = 0
121 | total_f_value = 0
122 |
123 | for img_file in image_files:
124 | img_path = os.path.join(DATASET_DIR, img_file)
125 | label_path = os.path.join(DATASET_DIR, os.path.splitext(img_file)[0] + '.txt')
126 |
127 | if not os.path.exists(label_path):
128 | continue
129 |
130 | gt_boxes = []
131 | gt_classes = []
132 | with open(label_path, 'r') as f:
133 | for line in f:
134 | class_id, x, y, w, h = map(float, line.strip().split())
135 | gt_boxes.append([x, y, w, h])
136 | gt_classes.append(int(class_id))
137 |
138 | results = model(img_path, conf=CONF_THRESHOLD)[0]
139 | img = cv2.imread(img_path)
140 | pred_boxes = []
141 | pred_classes = []
142 |
143 | # 各クラスの検出数をカウント
144 | class_counts = {i: 0 for i in range(num_classes)}
145 |
146 | for box in results.boxes:
147 | if float(box.conf[0]) < CONF_THRESHOLD:
148 | continue
149 |
150 | x, y, w, h = box.xywh[0].tolist()
151 | class_id = int(box.cls[0])
152 | conf = float(box.conf[0])
153 | color = class_colors[class_id]
154 |
155 | # 検出数カウント
156 | class_counts[class_id] += 1
157 |
158 | norm_x = x / img.shape[1]
159 | norm_y = y / img.shape[0]
160 | norm_w = w / img.shape[1]
161 | norm_h = h / img.shape[0]
162 | pred_boxes.append([norm_x, norm_y, norm_w, norm_h])
163 | pred_classes.append(class_id)
164 |
165 | cv2.rectangle(img,
166 | (int(x-w/2), int(y-h/2)),
167 | (int(x+w/2), int(y+h/2)),
168 | color,
169 | 2)
170 |
171 | label = f"{model.names[class_id]} {conf:.2f}"
172 | cv2.putText(img,
173 | label,
174 | (int(x-w/2), int(y-h/2)-10),
175 | cv2.FONT_HERSHEY_SIMPLEX,
176 | 0.5,
177 | color,
178 | 2)
179 |
180 | # 検出数カウントをリストに追加
181 | detection_count = [img_file] + [class_counts[i] for i in range(num_classes)]
182 | detection_counts.append(detection_count)
183 |
184 | precision, recall, f_value = evaluate_detection(gt_boxes, gt_classes, pred_boxes, pred_classes)
185 |
186 | total_precision += precision
187 | total_recall += recall
188 | total_f_value += f_value
189 |
190 | output_img_path = str(detect_dir / f"{os.path.splitext(img_file)[0]}_det.jpg")
191 | cv2.imwrite(output_img_path, img)
192 |
193 | result_txt = detect_dir / f"{os.path.splitext(img_file)[0]}_det.txt"
194 | with open(result_txt, 'w') as f:
195 | for i, box in enumerate(pred_boxes):
196 | f.write(f"{pred_classes[i]} {' '.join(map(str, box))}\n")
197 |
198 | # 検出数をCSVに保存
199 | detection_csv_path = base_dir / "num_of_detections.csv"
200 | with open(detection_csv_path, 'w', newline='') as f:
201 | writer = csv.writer(f)
202 | header = ['filename'] + [class_names[i] for i in range(num_classes)]
203 | writer.writerow(header)
204 | writer.writerows(detection_counts)
205 |
206 | n_images = len(image_files)
207 | avg_precision = total_precision / n_images
208 | avg_recall = total_recall / n_images
209 | avg_f_value = total_f_value / n_images
210 |
211 | # csv_path = base_dir / "evaluation_results.csv"
212 | # with open(csv_path, 'w', newline='') as f:
213 | # writer = csv.writer(f)
214 | # writer.writerow(['Metric', 'Value'])
215 | # writer.writerow(['Average Precision', avg_precision])
216 | # writer.writerow(['Average Recall', avg_recall])
217 | # writer.writerow(['Average F-value', avg_f_value])
218 |
219 | txt_path = base_dir / "precision_recall_f-value.txt"
220 | with open(txt_path, 'w') as f:
221 | f.write(f"Average Precision: {avg_precision:.4f}\n")
222 | f.write(f"Average Recall: {avg_recall:.4f}\n")
223 | f.write(f"Average F-value: {avg_f_value:.4f}\n")
224 |
225 | if __name__ == "__main__":
226 | main()
--------------------------------------------------------------------------------
/src/camera.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import threading
3 | import time
4 | import os
5 | from pathlib import Path
6 | from ultralytics import YOLO
7 | import torch
8 | from datetime import datetime
9 | from PIL import Image, ImageTk
10 |
11 | def normalize_path(path):
12 | if not path:
13 | return path
14 | return str(Path(path).resolve())
15 |
16 | class CameraDetection:
17 | def __init__(self, model_path, conf_threshold=0.5):
18 | self.model = YOLO(model_path)
19 | self.conf_threshold = conf_threshold
20 | self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
21 | self.model.to(self.device)
22 | self.cap = None
23 | self.running = False
24 | self.save_dir = ""
25 | self.scene_id = 0
26 |
27 | def start_camera(self, camera_id):
28 | self.cap = cv2.VideoCapture(camera_id)
29 | if not self.cap.isOpened():
30 | raise ValueError("Unable to open camera")
31 |
32 | self.original_width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
33 | self.original_height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
34 |
35 | def stop_camera(self):
36 | if self.cap:
37 | self.cap.release()
38 | self.cap = None
39 |
40 | def set_save_directory(self, directory):
41 | self.save_dir = directory
42 |
43 | def show_camera_stream(self, display_label):
44 | self.running = True
45 | threading.Thread(target=self._update_stream, args=(display_label,), daemon=True).start()
46 |
47 | def _update_stream(self, display_label):
48 | while self.running:
49 | ret, frame = self.cap.read()
50 | if not ret:
51 | break
52 |
53 | results = self.model(frame)
54 | detection_frame = frame.copy()
55 | self._draw_bounding_boxes(detection_frame, results)
56 |
57 | img = cv2.cvtColor(detection_frame, cv2.COLOR_BGR2RGB)
58 | img = self._resize_image_to_fit(img, display_label.winfo_width(), display_label.winfo_height())
59 | img = Image.fromarray(img)
60 |
61 | img = ImageTk.PhotoImage(image=img)
62 | display_label.config(image=img)
63 | display_label.image = img
64 |
65 | display_label.update_idletasks()
66 | display_label.update()
67 |
68 | time.sleep(0.03)
69 |
70 | def _resize_image_to_fit(self, image, max_width, max_height):
71 | height, width = image.shape[:2]
72 | aspect_ratio = width / height
73 |
74 | if aspect_ratio > max_width / max_height:
75 | new_width = max_width
76 | new_height = int(new_width / aspect_ratio)
77 | else:
78 | new_height = max_height
79 | new_width = int(new_height * aspect_ratio)
80 |
81 | resized_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_AREA)
82 | return resized_image
83 |
84 | def _draw_bounding_boxes(self, frame, results):
85 | colors = {}
86 | for result in results[0].boxes:
87 | if result.conf[0] >= self.conf_threshold:
88 | x1, y1, x2, y2 = map(int, result.xyxy[0])
89 | label = self.model.names[int(result.cls[0])]
90 | confidence = result.conf[0]
91 |
92 | if label not in colors:
93 | colors[label] = (int(hash(label) % 255), int((hash(label) * 2) % 255), int((hash(label) * 3) % 255))
94 |
95 | color = colors[label]
96 | cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
97 | text = f"{label}: {confidence:.2f}"
98 | cv2.putText(frame, text, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
99 |
100 | def capture_frame(self):
101 | if not self.cap:
102 | return
103 |
104 | ret, frame = self.cap.read()
105 | if not ret:
106 | return
107 |
108 | self.scene_id += 1
109 | timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
110 | base_filename = f"{timestamp}_{self.scene_id:04d}"
111 |
112 | # Use pathlib for path handling
113 | save_dir_path = Path(self.save_dir)
114 |
115 | # オリジナル画像を保存(PNG形式で保存してクオリティを維持)
116 | origin_image_path = str(save_dir_path / f"{base_filename}_origin.png")
117 | cv2.imwrite(origin_image_path, frame, [cv2.IMWRITE_PNG_COMPRESSION, 9])
118 |
119 | # 検出結果を描画
120 | results = self.model(frame)
121 | self._draw_bounding_boxes(frame, results)
122 |
123 | # 検出結果画像を保存(JPEG形式で容量を抑える)
124 | detection_image_path = str(save_dir_path / f"{base_filename}_detection.jpg")
125 | cv2.imwrite(detection_image_path, frame, [cv2.IMWRITE_JPEG_QUALITY, 95])
126 |
127 | # 検出結果のテキストを保存
128 | txt_path = str(save_dir_path / f"{base_filename}_detection.txt")
129 | with open(txt_path, 'w', encoding='utf-8') as f:
130 | for result in results[0].boxes:
131 | if result.conf[0] >= self.conf_threshold:
132 | x1, y1, x2, y2 = map(int, result.xyxy[0])
133 | label = self.model.names[int(result.cls[0])]
134 | confidence = result.conf[0]
135 | f.write(f"{label} {confidence:.2f} {x1} {y1} {x2} {y2}\n")
136 |
137 | return origin_image_path, detection_image_path, txt_path
138 |
139 | def stop(self):
140 | self.running = False
141 | self.stop_camera()
--------------------------------------------------------------------------------
/src/detect.py:
--------------------------------------------------------------------------------
1 | import shutil
2 | import os
3 | import cv2
4 | import mimetypes
5 | from pathlib import Path
6 | from ultralytics import YOLO
7 | from typing import List, Union
8 | from datetime import datetime
9 |
10 | VALID_IMAGE_EXTENSIONS = {
11 | '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.ppm',
12 | '.JPG', '.JPEG', '.PNG', '.GIF', '.BMP', '.WEBP', '.TIFF', '.PPM'
13 | }
14 |
15 | VALID_VIDEO_EXTENSIONS = {
16 | '.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv',
17 | '.MP4', '.AVI', '.MOV', '.MKV', '.WMV', '.FLV'
18 | }
19 |
20 | def is_valid_image(file_path: Union[str, Path]) -> bool:
21 | """Check if a file is a valid image by examining both extension and mime type"""
22 | try:
23 | file_path = Path(file_path)
24 | # Check file extension
25 | if file_path.suffix.lower() not in {ext.lower() for ext in VALID_IMAGE_EXTENSIONS}:
26 | return False
27 |
28 | # Check mime type
29 | mime_type, _ = mimetypes.guess_type(str(file_path))
30 | if not mime_type or not mime_type.startswith('image/'):
31 | return False
32 |
33 | return True
34 | except Exception:
35 | return False
36 |
37 | def is_valid_video(file_path: Union[str, Path]) -> bool:
38 | """Check if a file is a valid video by examining both extension and mime type"""
39 | try:
40 | file_path = Path(file_path)
41 | # Check file extension
42 | if file_path.suffix.lower() not in {ext.lower() for ext in VALID_VIDEO_EXTENSIONS}:
43 | return False
44 |
45 | # Check mime type
46 | mime_type, _ = mimetypes.guess_type(str(file_path))
47 | if not mime_type or not mime_type.startswith('video/'):
48 | return False
49 |
50 | return True
51 | except Exception:
52 | return False
53 |
54 | def normalize_path(file_path: Union[str, Path]) -> Path:
55 | """Normalize path to handle Japanese characters and different path formats"""
56 | try:
57 | return Path(file_path).resolve()
58 | except Exception:
59 | raise ValueError(f"Invalid path: {file_path}")
60 |
61 | def get_media_files(directory: Union[str, Path]) -> tuple[List[Path], List[Path]]:
62 | """Recursively find all valid images and videos in a directory"""
63 | directory = normalize_path(directory)
64 | image_files = []
65 | video_files = []
66 |
67 | try:
68 | for file_path in directory.rglob('*'):
69 | if not file_path.is_file():
70 | continue
71 | if is_valid_image(file_path):
72 | image_files.append(file_path)
73 | elif is_valid_video(file_path):
74 | video_files.append(file_path)
75 | except Exception as e:
76 | print(f"Error scanning directory {directory}: {e}")
77 | return [], []
78 |
79 | return sorted(image_files), sorted(video_files)
80 |
81 | def process_video(video_path: Path, model, output_dir: Path, conf_threshold: float = 0.5):
82 | """Process a video file and save detection results"""
83 | cap = cv2.VideoCapture(str(video_path))
84 | if not cap.isOpened():
85 | print(f"Error opening video file: {video_path}")
86 | return None
87 |
88 | # Get video properties
89 | fps = cap.get(cv2.CAP_PROP_FPS)
90 | width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
91 | height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
92 | total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
93 |
94 | # Create output directory
95 | timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
96 | video_name = video_path.stem
97 | video_output_dir = output_dir / f"{timestamp}_{video_name}"
98 | video_output_dir.mkdir(parents=True, exist_ok=True)
99 |
100 | # Create video writer
101 | output_video_path = video_output_dir / f"{video_name}_detection.mp4"
102 | fourcc = cv2.VideoWriter_fourcc(*'mp4v')
103 | out = cv2.VideoWriter(str(output_video_path), fourcc, fps, (width, height))
104 |
105 | frame_count = 0
106 | detection_count = 0
107 |
108 | while True:
109 | ret, frame = cap.read()
110 | if not ret:
111 | break
112 |
113 | # Update progress (every 30 frames to avoid excessive printing)
114 | if frame_count % 30 == 0:
115 | progress = (frame_count / total_frames) * 100
116 | print(f"\rProcessing video: {progress:.1f}% ({frame_count}/{total_frames} frames)", end="")
117 |
118 | # Detect objects in frame
119 | results = model.predict(frame, save=False, conf=conf_threshold)
120 |
121 | # Only process frames with detections above threshold
122 | if len(results[0].boxes) > 0:
123 | # Draw bounding boxes
124 | annotated_frame = results[0].plot()
125 |
126 | # Save frame with detections
127 | frame_path = video_output_dir / f"frame_{detection_count:04d}.jpg"
128 | cv2.imwrite(str(frame_path), annotated_frame)
129 |
130 | # Save detection results to txt
131 | txt_path = video_output_dir / f"frame_{detection_count:04d}.txt"
132 | with open(txt_path, 'w', encoding='utf-8') as f:
133 | for box in results[0].boxes:
134 | if box.conf[0] >= conf_threshold:
135 | x1, y1, x2, y2 = map(int, box.xyxy[0])
136 | label = model.names[int(box.cls[0])]
137 | confidence = box.conf[0]
138 | f.write(f"{label} {confidence:.2f} {x1} {y1} {x2} {y2}\n")
139 |
140 | detection_count += 1
141 |
142 | # Write frame to output video
143 | out.write(annotated_frame)
144 | else:
145 | # Write original frame to video if no detections
146 | out.write(frame)
147 |
148 | frame_count += 1
149 |
150 | # Clean up
151 | cap.release()
152 | out.release()
153 |
154 | print(f"\nVideo processing complete. {detection_count} frames with detections saved.")
155 | print(f"Output video saved to: {output_video_path}")
156 |
157 | return video_output_dir
158 |
159 | def move_detection_results(source_dir, target_dir):
160 | source_dir = normalize_path(source_dir)
161 | target_dir = normalize_path(target_dir)
162 |
163 | # Create target directory if it doesn't exist
164 | target_dir.mkdir(parents=True, exist_ok=True)
165 |
166 | for file_path in source_dir.iterdir():
167 | target_file = target_dir / file_path.name
168 |
169 | # Remove existing file/directory if it exists
170 | if target_file.exists():
171 | if target_file.is_dir():
172 | shutil.rmtree(str(target_file))
173 | else:
174 | target_file.unlink()
175 |
176 | # Move the file
177 | if file_path.is_file():
178 | shutil.move(str(file_path), str(target_file))
179 | else:
180 | shutil.move(str(file_path), str(target_dir))
181 |
182 | # Clean up source directory
183 | shutil.rmtree(str(source_dir))
184 |
185 | def detect_images(images_folder, model_path, callback=None):
186 | model = YOLO(model_path)
187 |
188 | # Find all valid images and videos in the folder
189 | images_folder = normalize_path(images_folder)
190 | image_files, video_files = get_media_files(images_folder)
191 |
192 | if not image_files and not video_files:
193 | print("No valid media files found in the directory")
194 | return
195 |
196 | results_dir = Path(images_folder) / 'results'
197 | results_dir.mkdir(parents=True, exist_ok=True)
198 |
199 | # Process images
200 | if image_files:
201 | # Convert Path objects to strings for YOLO predict
202 | image_paths = [str(path) for path in image_files]
203 | results = model.predict(image_paths, save=True, save_txt=True, imgsz=640, conf=0.5)
204 |
205 | runs_dir = Path('runs/detect')
206 | latest_run_dir = max(runs_dir.glob('*'), key=lambda p: p.stat().st_mtime)
207 | move_detection_results(latest_run_dir, results_dir)
208 |
209 | # Process videos
210 | for video_file in video_files:
211 | process_video(video_file, model, results_dir)
212 |
213 | if callback:
214 | callback(str(results_dir))
--------------------------------------------------------------------------------
/src/train.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import torch
4 | import shutil
5 | import glob
6 | import random
7 | import mimetypes
8 | from pathlib import Path
9 | from ultralytics import YOLO
10 |
11 | VALID_IMAGE_EXTENSIONS = {
12 | '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.ppm',
13 | '.JPG', '.JPEG', '.PNG', '.GIF', '.BMP', '.WEBP', '.TIFF', '.PPM'
14 | }
15 |
16 | def is_valid_image(file_path):
17 | """Check if a file is a valid image by examining extension and mime type"""
18 | try:
19 | file_path = Path(file_path)
20 |
21 | # Check file extension
22 | if file_path.suffix.lower() not in {ext.lower() for ext in VALID_IMAGE_EXTENSIONS}:
23 | return False
24 |
25 | # Check mime type
26 | mime_type, _ = mimetypes.guess_type(str(file_path))
27 | return mime_type is not None and mime_type.startswith('image/')
28 | except Exception:
29 | return False
30 |
31 | def normalize_path(path):
32 | if not path:
33 | return path
34 | return str(Path(path).resolve())
35 |
36 | def prepare_data(train_data_path):
37 | train_data_path = normalize_path(train_data_path)
38 | train_path = Path(train_data_path)
39 | train_dir_exists = (train_path / 'train/images').exists() and (train_path / 'train/labels').exists()
40 | val_dir_exists = (train_path / 'val/images').exists() and (train_path / 'val/labels').exists()
41 |
42 | if train_dir_exists and val_dir_exists:
43 | print("Train and validation directories already exist. Skipping file preparation.")
44 | return
45 |
46 | for path in ['train/images', 'train/labels', 'val/images', 'val/labels']:
47 | (train_path / path).mkdir(parents=True, exist_ok=True)
48 |
49 | # Find all valid image files and their corresponding txt files
50 | paired_files = []
51 | for file_path in Path(train_data_path).iterdir():
52 | if file_path.is_file() and is_valid_image(str(file_path)):
53 | txt_file = file_path.with_suffix('.txt')
54 | if txt_file.exists():
55 | paired_files.append((file_path.name, txt_file.name))
56 |
57 | random.seed(0)
58 | random.shuffle(paired_files)
59 | split_idx = int(len(paired_files) * 0.8)
60 | train_files = paired_files[:split_idx]
61 | val_files = paired_files[split_idx:]
62 |
63 | move_files(train_files, train_data_path, 'train')
64 | move_files(val_files, train_data_path, 'val')
65 |
66 | def move_files(files, base_path, data_type):
67 | base_path = Path(base_path)
68 | for img_file, txt_file in files:
69 | # Move image file
70 | src_img = base_path / img_file
71 | dst_img = base_path / data_type / 'images' / img_file
72 | shutil.move(str(src_img), str(dst_img))
73 |
74 | # Move label file
75 | src_txt = base_path / txt_file
76 | dst_txt = base_path / data_type / 'labels' / txt_file
77 | shutil.move(str(src_txt), str(dst_txt))
78 |
79 | def create_symlinks(files, base_path, data_type):
80 | for img_file, txt_file in files:
81 | src_img_path = os.path.join(base_path, img_file)
82 | dst_img_path = os.path.join(base_path, data_type, 'images', img_file)
83 | os.symlink(src_img_path, dst_img_path)
84 |
85 | src_txt_path = os.path.join(base_path, txt_file)
86 | dst_txt_path = os.path.join(base_path, data_type, 'labels', txt_file)
87 | os.symlink(src_txt_path, dst_txt_path)
88 |
89 | def clean_up(train_data_path):
90 | for path in ['train', 'val']:
91 | shutil.rmtree(os.path.join(train_data_path, path), ignore_errors=True)
92 |
93 | def copy_and_remove_latest_run_files(model_save_path, project_name):
94 | model_save_path = Path(model_save_path)
95 | runs_path = Path('runs/detect') / project_name
96 | list_of_dirs = list(Path('runs/detect').glob(project_name))
97 |
98 | if not list_of_dirs:
99 | print(f"No 'runs/detect/{project_name}' directories found. Skipping copy and removal.")
100 | return
101 |
102 | latest_dir = max(list_of_dirs, key=lambda p: p.stat().st_mtime)
103 |
104 | if latest_dir.exists():
105 | for item in latest_dir.iterdir():
106 | dest = model_save_path / item.name
107 | if item.is_dir():
108 | shutil.copytree(str(item), str(dest), dirs_exist_ok=True)
109 | else:
110 | shutil.copy2(str(item), str(dest))
111 |
112 | runs_dir = Path('runs')
113 | if runs_dir.exists() and runs_dir.is_dir():
114 | shutil.rmtree(str(runs_dir))
115 |
116 | def create_yaml(project_name, train_data_path, class_names, save_directory):
117 | prepare_data(train_data_path)
118 |
119 | train_path = str(Path(train_data_path) / 'train')
120 | val_path = str(Path(train_data_path) / 'val')
121 |
122 | # Ensure proper path format for YAML
123 | train_path = train_path.replace('\\', '/')
124 | val_path = val_path.replace('\\', '/')
125 |
126 | yaml_content = f"""train: {train_path}
127 | val: {val_path}
128 | nc: {len(class_names)}
129 | names: [{', '.join(f"'{name}'" for name in class_names)}]
130 | """
131 | print(f"Project Name: {project_name}")
132 | yaml_path = str(Path(save_directory) / f'{project_name}.yaml')
133 | print(f"YAML Path: {yaml_path}")
134 |
135 | with open(yaml_path, 'w', encoding='utf-8') as file:
136 | file.write(yaml_content)
137 | return yaml_path
138 |
139 | def train_yolo(data_yaml, model_type, img_size, batch, epochs, model_save_path, project_name):
140 | device = 'cuda' if torch.cuda.is_available() else 'cpu'
141 | model = YOLO(f'{model_type}.pt').to(device)
142 | results = model.train(data=data_yaml, epochs=epochs, batch=batch, imgsz=img_size, name=project_name, save=True)
143 | copy_and_remove_latest_run_files(model_save_path, project_name)
144 | clean_up(os.path.dirname(data_yaml))
145 | return results
146 |
147 | def parse_args():
148 | project_name = sys.argv[1]
149 | train_data_path = sys.argv[2]
150 | class_names = sys.argv[3].split(',')
151 | model_save_path = sys.argv[4]
152 | model_type = sys.argv[5]
153 | img_size = int(sys.argv[6])
154 | epochs = int(sys.argv[7])
155 | yaml_path = sys.argv[8]
156 | batch_size = int(sys.argv[9])
157 |
158 | results = train_yolo(yaml_path, model_type, img_size, batch_size, epochs, model_save_path, project_name)
159 | print(f"Training completed. Model saved to {model_save_path}")
160 |
161 | if __name__ == '__main__':
162 | parse_args()
--------------------------------------------------------------------------------
/src/xml_to_txt.py:
--------------------------------------------------------------------------------
1 | """アノテーションデータをxml形式からtxt形式に変換する
2 | """
3 |
4 | import os
5 | import xml.etree.ElementTree as ET
6 |
7 |
8 | xml_dir = r"C:\Users\he81t\ubuntu\yamaguchi\fukuoka_chicken\original_data\Annotations_pascal_xml" # XMLファイルがあるディレクトリ
9 | txt_dir = r"C:\Users\he81t\ubuntu\yamaguchi\fukuoka_chicken\original_data\Annotations_yolo_txt" # YOLO形式のtxtファイルを出力するディレクトリ
10 |
11 | if not os.path.exists(txt_dir):
12 | os.makedirs(txt_dir)
13 |
14 | # クラス一覧を格納するリスト
15 | classes = []
16 |
17 | # xml_dir 内のファイルを走査
18 | for filename in os.listdir(xml_dir):
19 | # 拡張子が .xml のファイルだけ処理
20 | if filename.endswith(".xml"):
21 | # XMLファイルのパス
22 | xml_path = os.path.join(xml_dir, filename)
23 |
24 | # XMLをパース
25 | tree = ET.parse(xml_path)
26 | root = tree.getroot()
27 |
28 | # 画像サイズを取得
29 | size = root.find("size")
30 | if size is None:
31 | # sizeタグがない場合はスキップ
32 | continue
33 |
34 | width = float(size.find("width").text)
35 | height = float(size.find("height").text)
36 |
37 | # 出力テキストファイルのパス (.txtに置き換え)
38 | txt_filename = os.path.splitext(filename)[0] + ".txt"
39 | txt_path = os.path.join(txt_dir, txt_filename)
40 |
41 | # YOLO形式のアノテーションを書き込むためのリスト
42 | yolo_annotations = []
43 |
44 | # objectタグをすべて取得し、YOLO形式に変換
45 | for obj in root.findall("object"):
46 | # クラス名
47 | class_name = obj.find("name").text
48 | if class_name not in classes:
49 | classes.append(class_name)
50 | class_id = classes.index(class_name)
51 |
52 | # バウンディングボックス座標
53 | bndbox = obj.find("bndbox")
54 | xmin = float(bndbox.find("xmin").text)
55 | ymin = float(bndbox.find("ymin").text)
56 | xmax = float(bndbox.find("xmax").text)
57 | ymax = float(bndbox.find("ymax").text)
58 |
59 | # YOLO形式は (class_id, x_center, y_center, w, h) [正規化済み]
60 | x_center = (xmin + xmax) / 2.0 / width
61 | y_center = (ymin + ymax) / 2.0 / height
62 | w = (xmax - xmin) / width
63 | h = (ymax - ymin) / height
64 |
65 | # 小数点以下の桁数を整えて書き出す場合はここでformatを利用
66 | annotation_str = f"{class_id} {x_center:.6f} {y_center:.6f} {w:.6f} {h:.6f}"
67 | yolo_annotations.append(annotation_str)
68 |
69 | # テキストファイルに書き出し
70 | with open(txt_path, "w", encoding="utf-8") as f:
71 | for line in yolo_annotations:
72 | f.write(line + "\n")
73 |
74 | # 変換が終わった後、classesに格納されているクラス一覧を確認したい場合は、別途出力することもできます。
75 | print("クラス一覧:", classes)
--------------------------------------------------------------------------------