diff --git a/DroneCV/.gitignore b/DroneCV/.gitignore new file mode 100644 index 00000000..a42fd59a --- /dev/null +++ b/DroneCV/.gitignore @@ -0,0 +1,2 @@ +/.idea +.idea \ No newline at end of file diff --git a/DroneCV/LICENSE b/DroneCV/LICENSE new file mode 100644 index 00000000..0ad25db4 --- /dev/null +++ b/DroneCV/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/DroneCV/PyTorch_Objecttracking/README.md b/DroneCV/PyTorch_Objecttracking/README.md new file mode 100644 index 00000000..57bd97b3 --- /dev/null +++ b/DroneCV/PyTorch_Objecttracking/README.md @@ -0,0 +1,7 @@ + +Run the code + +`python3 detect.py` + +1. The input video is in 'videos' folder +2. YOLO configuration is in 'config' folder \ No newline at end of file diff --git a/DroneCV/PyTorch_Objecttracking/cfg/coco.names b/DroneCV/PyTorch_Objecttracking/cfg/coco.names new file mode 100644 index 00000000..16315f2b --- /dev/null +++ b/DroneCV/PyTorch_Objecttracking/cfg/coco.names @@ -0,0 +1,80 @@ +person +bicycle +car +motorbike +aeroplane +bus +train +truck +boat +traffic light +fire hydrant +stop sign +parking meter +bench +bird +cat +dog +horse +sheep +cow +elephant +bear +zebra +giraffe +backpack +umbrella +handbag +tie +suitcase +frisbee +skis +snowboard +sports ball +kite +baseball bat +baseball glove +skateboard +surfboard +tennis racket +bottle +wine glass +cup +fork +knife +spoon +bowl +banana +apple +sandwich +orange +broccoli +carrot +hot dog +pizza +donut +cake +chair +sofa +pottedplant +bed +diningtable +toilet +tvmonitor +laptop +mouse +remote +keyboard +cell phone +microwave +oven +toaster +sink +refrigerator +book +clock +vase +scissors +teddy bear +hair drier +toothbrush \ No newline at end of file diff --git a/DroneCV/PyTorch_Objecttracking/cfg/yolov3.cfg b/DroneCV/PyTorch_Objecttracking/cfg/yolov3.cfg new file mode 100644 index 00000000..938ffff2 --- /dev/null +++ b/DroneCV/PyTorch_Objecttracking/cfg/yolov3.cfg @@ -0,0 +1,789 @@ +[net] +# Testing +# batch=1 +# subdivisions=1 +# Training +batch=64 +subdivisions=16 +width=608 +height=608 +channels=3 +momentum=0.9 +decay=0.0005 +angle=0 +saturation = 1.5 +exposure = 1.5 +hue=.1 + +learning_rate=0.001 +burn_in=1000 +max_batches = 500200 +policy=steps +steps=400000,450000 +scales=.1,.1 + +[convolutional] +batch_normalize=1 +filters=32 +size=3 +stride=1 +pad=1 +activation=leaky + +# Downsample + +[convolutional] +batch_normalize=1 +filters=64 +size=3 +stride=2 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=32 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=64 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +# Downsample + +[convolutional] +batch_normalize=1 +filters=128 +size=3 +stride=2 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=64 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=128 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=64 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=128 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +# Downsample + +[convolutional] +batch_normalize=1 +filters=256 +size=3 +stride=2 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +# Downsample + +[convolutional] +batch_normalize=1 +filters=512 +size=3 +stride=2 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +# Downsample + +[convolutional] +batch_normalize=1 +filters=1024 +size=3 +stride=2 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=1024 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=512 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=1024 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=512 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=1024 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +[convolutional] +batch_normalize=1 +filters=512 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=1024 +size=3 +stride=1 +pad=1 +activation=leaky + +[shortcut] +from=-3 +activation=linear + +###################### + +[convolutional] +batch_normalize=1 +filters=512 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +size=3 +stride=1 +pad=1 +filters=1024 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +size=3 +stride=1 +pad=1 +filters=1024 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=512 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +size=3 +stride=1 +pad=1 +filters=1024 +activation=leaky + +[convolutional] +size=1 +stride=1 +pad=1 +filters=255 +activation=linear + + +[yolo] +mask = 6,7,8 +anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 +classes=80 +num=9 +jitter=.3 +ignore_thresh = .7 +truth_thresh = 1 +random=1 + + +[route] +layers = -4 + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[upsample] +stride=2 + +[route] +layers = -1, 61 + + + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +size=3 +stride=1 +pad=1 +filters=512 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +size=3 +stride=1 +pad=1 +filters=512 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=256 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +size=3 +stride=1 +pad=1 +filters=512 +activation=leaky + +[convolutional] +size=1 +stride=1 +pad=1 +filters=255 +activation=linear + + +[yolo] +mask = 3,4,5 +anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 +classes=80 +num=9 +jitter=.3 +ignore_thresh = .7 +truth_thresh = 1 +random=1 + + + +[route] +layers = -4 + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[upsample] +stride=2 + +[route] +layers = -1, 36 + + + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +size=3 +stride=1 +pad=1 +filters=256 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +size=3 +stride=1 +pad=1 +filters=256 +activation=leaky + +[convolutional] +batch_normalize=1 +filters=128 +size=1 +stride=1 +pad=1 +activation=leaky + +[convolutional] +batch_normalize=1 +size=3 +stride=1 +pad=1 +filters=256 +activation=leaky + +[convolutional] +size=1 +stride=1 +pad=1 +filters=255 +activation=linear + + +[yolo] +mask = 0,1,2 +anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 +classes=80 +num=9 +jitter=.3 +ignore_thresh = .7 +truth_thresh = 1 +random=1 + diff --git a/DroneCV/PyTorch_Objecttracking/cfg/yolov3.weights b/DroneCV/PyTorch_Objecttracking/cfg/yolov3.weights new file mode 100644 index 00000000..e69de29b diff --git a/DroneCV/PyTorch_Objecttracking/darknet.py b/DroneCV/PyTorch_Objecttracking/darknet.py new file mode 100644 index 00000000..742a37dc --- /dev/null +++ b/DroneCV/PyTorch_Objecttracking/darknet.py @@ -0,0 +1,317 @@ +from __future__ import division + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.autograd import Variable +import numpy as np +from util import * + + + +def get_test_input(): + img = cv2.imread("dog-cycle-car.png") + img = cv2.resize(img, (416,416)) #Resize to the input dimension + img_ = img[:,:,::-1].transpose((2,0,1)) # BGR -> RGB | H X W C -> C X H X W + img_ = img_[np.newaxis,:,:,:]/255.0 #Add a channel at 0 (for batch) | Normalise + img_ = torch.from_numpy(img_).float() #Convert to float + img_ = Variable(img_) # Convert to Variable + return img_ + +def parse_cfg(cfgfile): + """ + Takes a configuration file + + Returns a list of blocks. Each blocks describes a block in the neural + network to be built. Block is represented as a dictionary in the list + + """ + + file = open(cfgfile, 'r') + lines = file.read().split('\n') # store the lines in a list + lines = [x for x in lines if len(x) > 0] # get read of the empty lines + lines = [x for x in lines if x[0] != '#'] # get rid of comments + lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces + + block = {} + blocks = [] + + for line in lines: + if line[0] == "[": # This marks the start of a new block + if len(block) != 0: # If block is not empty, implies it is storing values of previous block. + blocks.append(block) # add it the blocks list + block = {} # re-init the block + block["type"] = line[1:-1].rstrip() + else: + key,value = line.split("=") + block[key.rstrip()] = value.lstrip() + blocks.append(block) + + return blocks + + +class EmptyLayer(nn.Module): + def __init__(self): + super(EmptyLayer, self).__init__() + + +class DetectionLayer(nn.Module): + def __init__(self, anchors): + super(DetectionLayer, self).__init__() + self.anchors = anchors + + + +def create_modules(blocks): + net_info = blocks[0] #Captures the information about the input and pre-processing + module_list = nn.ModuleList() + prev_filters = 3 + output_filters = [] + + for index, x in enumerate(blocks[1:]): + module = nn.Sequential() + + #check the type of block + #create a new module for the block + #append to module_list + + #If it's a convolutional layer + if (x["type"] == "convolutional"): + #Get the info about the layer + activation = x["activation"] + try: + batch_normalize = int(x["batch_normalize"]) + bias = False + except: + batch_normalize = 0 + bias = True + + filters= int(x["filters"]) + padding = int(x["pad"]) + kernel_size = int(x["size"]) + stride = int(x["stride"]) + + if padding: + pad = (kernel_size - 1) // 2 + else: + pad = 0 + + #Add the convolutional layer + conv = nn.Conv2d(prev_filters, filters, kernel_size, stride, pad, bias = bias) + module.add_module("conv_{0}".format(index), conv) + + #Add the Batch Norm Layer + if batch_normalize: + bn = nn.BatchNorm2d(filters) + module.add_module("batch_norm_{0}".format(index), bn) + + #Check the activation. + #It is either Linear or a Leaky ReLU for YOLO + if activation == "leaky": + activn = nn.LeakyReLU(0.1, inplace = True) + module.add_module("leaky_{0}".format(index), activn) + + #If it's an upsampling layer + #We use Bilinear2dUpsampling + elif (x["type"] == "upsample"): + stride = int(x["stride"]) + upsample = nn.Upsample(scale_factor = 2, mode = "nearest") + module.add_module("upsample_{}".format(index), upsample) + + #If it is a route layer + elif (x["type"] == "route"): + x["layers"] = x["layers"].split(',') + #Start of a route + start = int(x["layers"][0]) + #end, if there exists one. + try: + end = int(x["layers"][1]) + except: + end = 0 + #Positive anotation + if start > 0: + start = start - index + if end > 0: + end = end - index + route = EmptyLayer() + module.add_module("route_{0}".format(index), route) + if end < 0: + filters = output_filters[index + start] + output_filters[index + end] + else: + filters= output_filters[index + start] + + #shortcut corresponds to skip connection + elif x["type"] == "shortcut": + shortcut = EmptyLayer() + module.add_module("shortcut_{}".format(index), shortcut) + + #Yolo is the detection layer + elif x["type"] == "yolo": + mask = x["mask"].split(",") + mask = [int(x) for x in mask] + + anchors = x["anchors"].split(",") + anchors = [int(a) for a in anchors] + anchors = [(anchors[i], anchors[i+1]) for i in range(0, len(anchors),2)] + anchors = [anchors[i] for i in mask] + + detection = DetectionLayer(anchors) + module.add_module("Detection_{}".format(index), detection) + + module_list.append(module) + prev_filters = filters + output_filters.append(filters) + + return (net_info, module_list) + +class Darknet(nn.Module): + def __init__(self, cfgfile): + super(Darknet, self).__init__() + self.blocks = parse_cfg(cfgfile) + self.net_info, self.module_list = create_modules(self.blocks) + + def forward(self, x, CUDA): + modules = self.blocks[1:] + outputs = {} #We cache the outputs for the route layer + + write = 0 + for i, module in enumerate(modules): + module_type = (module["type"]) + + if module_type == "convolutional" or module_type == "upsample": + x = self.module_list[i](x) + + elif module_type == "route": + layers = module["layers"] + layers = [int(a) for a in layers] + + if (layers[0]) > 0: + layers[0] = layers[0] - i + + if len(layers) == 1: + x = outputs[i + (layers[0])] + + else: + if (layers[1]) > 0: + layers[1] = layers[1] - i + + map1 = outputs[i + layers[0]] + map2 = outputs[i + layers[1]] + x = torch.cat((map1, map2), 1) + + + elif module_type == "shortcut": + from_ = int(module["from"]) + x = outputs[i-1] + outputs[i+from_] + + elif module_type == 'yolo': + anchors = self.module_list[i][0].anchors + #Get the input dimensions + inp_dim = int (self.net_info["height"]) + + #Get the number of classes + num_classes = int (module["classes"]) + + #Transform + x = x.data + x = predict_transform(x, inp_dim, anchors, num_classes, CUDA) + if not write: #if no collector has been intialised. + detections = x + write = 1 + + else: + detections = torch.cat((detections, x), 1) + + outputs[i] = x + + return detections + + + def load_weights(self, weightfile): + #Open the weights file + fp = open(weightfile, "rb") + + #The first 5 values are header information + # 1. Major version number + # 2. Minor Version Number + # 3. Subversion number + # 4,5. Images seen by the network (during training) + header = np.fromfile(fp, dtype = np.int32, count = 5) + self.header = torch.from_numpy(header) + self.seen = self.header[3] + + weights = np.fromfile(fp, dtype = np.float32) + + ptr = 0 + for i in range(len(self.module_list)): + module_type = self.blocks[i + 1]["type"] + + #If module_type is convolutional load weights + #Otherwise ignore. + + if module_type == "convolutional": + model = self.module_list[i] + try: + batch_normalize = int(self.blocks[i+1]["batch_normalize"]) + except: + batch_normalize = 0 + + conv = model[0] + + + if (batch_normalize): + bn = model[1] + + #Get the number of weights of Batch Norm Layer + num_bn_biases = bn.bias.numel() + + #Load the weights + bn_biases = torch.from_numpy(weights[ptr:ptr + num_bn_biases]) + ptr += num_bn_biases + + bn_weights = torch.from_numpy(weights[ptr: ptr + num_bn_biases]) + ptr += num_bn_biases + + bn_running_mean = torch.from_numpy(weights[ptr: ptr + num_bn_biases]) + ptr += num_bn_biases + + bn_running_var = torch.from_numpy(weights[ptr: ptr + num_bn_biases]) + ptr += num_bn_biases + + #Cast the loaded weights into dims of model weights. + bn_biases = bn_biases.view_as(bn.bias.data) + bn_weights = bn_weights.view_as(bn.weight.data) + bn_running_mean = bn_running_mean.view_as(bn.running_mean) + bn_running_var = bn_running_var.view_as(bn.running_var) + + #Copy the data to model + bn.bias.data.copy_(bn_biases) + bn.weight.data.copy_(bn_weights) + bn.running_mean.copy_(bn_running_mean) + bn.running_var.copy_(bn_running_var) + + else: + #Number of biases + num_biases = conv.bias.numel() + + #Load the weights + conv_biases = torch.from_numpy(weights[ptr: ptr + num_biases]) + ptr = ptr + num_biases + + #reshape the loaded weights according to the dims of the model weights + conv_biases = conv_biases.view_as(conv.bias.data) + + #Finally copy the data + conv.bias.data.copy_(conv_biases) + + #Let us load the weights for the Convolutional layers + num_weights = conv.weight.numel() + + #Do the same as above for weights + conv_weights = torch.from_numpy(weights[ptr:ptr+num_weights]) + ptr = ptr + num_weights + + conv_weights = conv_weights.view_as(conv.weight.data) + conv.weight.data.copy_(conv_weights) + + diff --git a/DroneCV/PyTorch_Objecttracking/detect.py b/DroneCV/PyTorch_Objecttracking/detect.py new file mode 100644 index 00000000..88739ab8 --- /dev/null +++ b/DroneCV/PyTorch_Objecttracking/detect.py @@ -0,0 +1,157 @@ +# USAGE +# Reference: https://github.com/ayooshkathuria/YOLO_v3_tutorial_from_scratch +# python3 detect.py + +from __future__ import division + +import time +import torch +from torch.autograd import Variable +from util import * +import argparse +from darknet import Darknet +import pickle as pkl +import random +from cv2 import VideoWriter, VideoWriter_fourcc + + +# Parse Command Line Arguments +def arg_parse(): + """ + Parse arguments to the detect module + """ + parser = argparse.ArgumentParser(description='YOLO v3 Detection Module') + parser.add_argument("--bs", dest="bs", help="Batch size", default=1) + parser.add_argument("--confidence", dest="confidence", help="Object Confidence to filter predictions", default=0.5) + parser.add_argument("--nms_thresh", dest="nms_thresh", help="NMS Threshhold", default=0.4) + parser.add_argument("--cfg", dest = 'cfgfile', help= + "Config file", + default="cfg/yolov3.cfg", type=str) + parser.add_argument("--weights", dest='weightsfile', help= + "weightsfile", + default="cfg/yolov3.weights", type=str) + parser.add_argument("--reso", dest='reso', help= + "Input resolution of the network. Increase to increase accuracy. Decrease to increase speed", + default="416", type=str) + parser.add_argument("--video", dest="videofile", help="Video file to run detection on", default="videos/drone2.mp4", + type=str) + + return parser.parse_args() + + +args = arg_parse() +batch_size = int(args.bs) +confidence = float(args.confidence) +nms_thesh = float(args.nms_thresh) +start = 0 +CUDA = torch.cuda.is_available() + +num_classes = 80 +classes = load_classes("cfg/coco.names") + +# Set up the neural network +print("Loading network.....") +model = Darknet(args.cfgfile) +model.load_weights(args.weightsfile) +print("Network successfully loaded") + +model.net_info["height"] = args.reso +inp_dim = int(model.net_info["height"]) +assert inp_dim % 32 == 0 +assert inp_dim > 32 + +# Check if cuda is available and use it +if CUDA: + model.cuda() + +# Set the model in evaluation mode +model.eval() + +# Draw Rectangle +def write(x, results, contours): + c1 = tuple(x[1:3].int()) + c2 = tuple(x[3:5].int()) + img = results + color = random.choice(colors) + cv2.rectangle(img, c1, c2, color, 1) + + return img + +# define the lower and upper boundaries of the "green" +# ball in the HSV color space, then initialize the +# list of tracked points +greenLower = (161, 155, 84) +greenUpper = (179, 255, 255) + +# Detection phase +videofile = args.videofile # or path to the video file. +vs = cv2.VideoCapture(videofile) +out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480)) +start = time.time() +contours_rect = [] +# allow the camera or video file to warm up +time.sleep(2.0) + +fourcc = VideoWriter_fourcc(*'MP42') +video = VideoWriter('./detection.avi', fourcc, float(24), (1280, 720)) + +# keep looping +while True: + # grab the current frame + frame = vs.read() + + # handle the frame from VideoCapture or VideoStream + frame = frame[1] + # if we are viewing a video and we did not grab a frame, + # then we have reached the end of the video + if frame is None: + break + + + img = prep_image(frame, inp_dim) + im_dim = frame.shape[1], frame.shape[0] + im_dim = torch.FloatTensor(im_dim).repeat(1, 2) + + if CUDA: + im_dim = im_dim.cuda() + img = img.cuda() + + with torch.no_grad(): + output = model(Variable(img, volatile=True), CUDA) + output = write_results(output, confidence, num_classes, nms_conf=nms_thesh) + + if type(output) == int: + cv2.imshow("frame", frame) + key = cv2.waitKey(1) + if key & 0xFF == ord('q'): + break + continue + + im_dim = im_dim.repeat(output.size(0), 1) + scaling_factor = torch.min(416 / im_dim, 1)[0].view(-1, 1) + + output[:, [1, 3]] -= (inp_dim - scaling_factor * im_dim[:, 0].view(-1, 1)) / 2 + output[:, [2, 4]] -= (inp_dim - scaling_factor * im_dim[:, 1].view(-1, 1)) / 2 + + output[:, 1:5] /= scaling_factor + + for i in range(output.shape[0]): + output[i, [1, 3]] = torch.clamp(output[i, [1, 3]], 0.0, im_dim[i, 0]) + output[i, [2, 4]] = torch.clamp(output[i, [2, 4]], 0.0, im_dim[i, 1]) + + classes = load_classes('cfg/coco.names') + colors = pkl.load(open("pallete", "rb")) + list(map(lambda x: write(x, frame, contours_rect), output)) + + cv2.imshow("frame", frame) + + video.write(frame) + key = cv2.waitKey(10) + if key & 0xFF == ord('q'): + break + +vs.release() +video.release() + +# close all windows +cv2.destroyAllWindows() \ No newline at end of file diff --git a/DroneCV/PyTorch_Objecttracking/pallete b/DroneCV/PyTorch_Objecttracking/pallete new file mode 100644 index 00000000..e69de29b diff --git a/DroneCV/PyTorch_Objecttracking/util.py b/DroneCV/PyTorch_Objecttracking/util.py new file mode 100644 index 00000000..2ef4673e --- /dev/null +++ b/DroneCV/PyTorch_Objecttracking/util.py @@ -0,0 +1,215 @@ +from __future__ import division + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.autograd import Variable +import numpy as np +import cv2 + +def unique(tensor): + tensor_np = tensor.cpu().numpy() + unique_np = np.unique(tensor_np) + unique_tensor = torch.from_numpy(unique_np) + + tensor_res = tensor.new(unique_tensor.shape) + tensor_res.copy_(unique_tensor) + return tensor_res + + +def bbox_iou(box1, box2): + """ + Returns the IoU of two bounding boxes + + + """ + #Get the coordinates of bounding boxes + b1_x1, b1_y1, b1_x2, b1_y2 = box1[:,0], box1[:,1], box1[:,2], box1[:,3] + b2_x1, b2_y1, b2_x2, b2_y2 = box2[:,0], box2[:,1], box2[:,2], box2[:,3] + + #get the corrdinates of the intersection rectangle + inter_rect_x1 = torch.max(b1_x1, b2_x1) + inter_rect_y1 = torch.max(b1_y1, b2_y1) + inter_rect_x2 = torch.min(b1_x2, b2_x2) + inter_rect_y2 = torch.min(b1_y2, b2_y2) + + #Intersection area + inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=0) * torch.clamp(inter_rect_y2 - inter_rect_y1 + 1, min=0) + + #Union Area + b1_area = (b1_x2 - b1_x1 + 1)*(b1_y2 - b1_y1 + 1) + b2_area = (b2_x2 - b2_x1 + 1)*(b2_y2 - b2_y1 + 1) + + iou = inter_area / (b1_area + b2_area - inter_area) + + return iou + +def predict_transform(prediction, inp_dim, anchors, num_classes, CUDA = True): + + + batch_size = prediction.size(0) + stride = inp_dim // prediction.size(2) + grid_size = inp_dim // stride + bbox_attrs = 5 + num_classes + num_anchors = len(anchors) + + prediction = prediction.view(batch_size, bbox_attrs*num_anchors, grid_size*grid_size) + prediction = prediction.transpose(1,2).contiguous() + prediction = prediction.view(batch_size, grid_size*grid_size*num_anchors, bbox_attrs) + anchors = [(a[0]/stride, a[1]/stride) for a in anchors] + + #Sigmoid the centre_X, centre_Y. and object confidencce + prediction[:,:,0] = torch.sigmoid(prediction[:,:,0]) + prediction[:,:,1] = torch.sigmoid(prediction[:,:,1]) + prediction[:,:,4] = torch.sigmoid(prediction[:,:,4]) + + #Add the center offsets + grid = np.arange(grid_size) + a,b = np.meshgrid(grid, grid) + + x_offset = torch.FloatTensor(a).view(-1,1) + y_offset = torch.FloatTensor(b).view(-1,1) + + if CUDA: + x_offset = x_offset.cuda() + y_offset = y_offset.cuda() + + x_y_offset = torch.cat((x_offset, y_offset), 1).repeat(1,num_anchors).view(-1,2).unsqueeze(0) + + prediction[:,:,:2] += x_y_offset + + #log space transform height and the width + anchors = torch.FloatTensor(anchors) + + if CUDA: + anchors = anchors.cuda() + + anchors = anchors.repeat(grid_size*grid_size, 1).unsqueeze(0) + prediction[:,:,2:4] = torch.exp(prediction[:,:,2:4])*anchors + + prediction[:,:,5: 5 + num_classes] = torch.sigmoid((prediction[:,:, 5 : 5 + num_classes])) + + prediction[:,:,:4] *= stride + + return prediction + +def write_results(prediction, confidence, num_classes, nms_conf = 0.4): + conf_mask = (prediction[:,:,4] > confidence).float().unsqueeze(2) + prediction = prediction*conf_mask + + box_corner = prediction.new(prediction.shape) + box_corner[:,:,0] = (prediction[:,:,0] - prediction[:,:,2]/2) + box_corner[:,:,1] = (prediction[:,:,1] - prediction[:,:,3]/2) + box_corner[:,:,2] = (prediction[:,:,0] + prediction[:,:,2]/2) + box_corner[:,:,3] = (prediction[:,:,1] + prediction[:,:,3]/2) + prediction[:,:,:4] = box_corner[:,:,:4] + + batch_size = prediction.size(0) + + write = False + + + + for ind in range(batch_size): + image_pred = prediction[ind] #image Tensor + #confidence threshholding + #NMS + + max_conf, max_conf_score = torch.max(image_pred[:,5:5+ num_classes], 1) + max_conf = max_conf.float().unsqueeze(1) + max_conf_score = max_conf_score.float().unsqueeze(1) + seq = (image_pred[:,:5], max_conf, max_conf_score) + image_pred = torch.cat(seq, 1) + + non_zero_ind = (torch.nonzero(image_pred[:,4])) + try: + image_pred_ = image_pred[non_zero_ind.squeeze(),:].view(-1,7) + except: + continue + + if image_pred_.shape[0] == 0: + continue +# + + #Get the various classes detected in the image + img_classes = unique(image_pred_[:,-1]) # -1 index holds the class index + + + for cls in img_classes: + #perform NMS + + + #get the detections with one particular class + cls_mask = image_pred_*(image_pred_[:,-1] == cls).float().unsqueeze(1) + class_mask_ind = torch.nonzero(cls_mask[:,-2]).squeeze() + image_pred_class = image_pred_[class_mask_ind].view(-1,7) + + #sort the detections such that the entry with the maximum objectness + #confidence is at the top + conf_sort_index = torch.sort(image_pred_class[:,4], descending = True )[1] + image_pred_class = image_pred_class[conf_sort_index] + idx = image_pred_class.size(0) #Number of detections + + for i in range(idx): + #Get the IOUs of all boxes that come after the one we are looking at + #in the loop + try: + ious = bbox_iou(image_pred_class[i].unsqueeze(0), image_pred_class[i+1:]) + except ValueError: + break + + except IndexError: + break + + #Zero out all the detections that have IoU > treshhold + iou_mask = (ious < nms_conf).float().unsqueeze(1) + image_pred_class[i+1:] *= iou_mask + + #Remove the non-zero entries + non_zero_ind = torch.nonzero(image_pred_class[:,4]).squeeze() + image_pred_class = image_pred_class[non_zero_ind].view(-1,7) + + batch_ind = image_pred_class.new(image_pred_class.size(0), 1).fill_(ind) #Repeat the batch_id for as many detections of the class cls in the image + seq = batch_ind, image_pred_class + + if not write: + output = torch.cat(seq,1) + write = True + else: + out = torch.cat(seq,1) + output = torch.cat((output,out)) + + try: + return output + except: + return 0 + +def letterbox_image(img, inp_dim): + '''resize image with unchanged aspect ratio using padding''' + img_w, img_h = img.shape[1], img.shape[0] + w, h = inp_dim + new_w = int(img_w * min(w/img_w, h/img_h)) + new_h = int(img_h * min(w/img_w, h/img_h)) + resized_image = cv2.resize(img, (new_w,new_h), interpolation = cv2.INTER_CUBIC) + + canvas = np.full((inp_dim[1], inp_dim[0], 3), 128) + + canvas[(h-new_h)//2:(h-new_h)//2 + new_h,(w-new_w)//2:(w-new_w)//2 + new_w, :] = resized_image + + return canvas + +def prep_image(img, inp_dim): + """ + Prepare image for inputting to the neural network. + + Returns a Variable + """ + img = (letterbox_image(img, (inp_dim, inp_dim))) + img = img[:,:,::-1].transpose((2,0,1)).copy() + img = torch.from_numpy(img).float().div(255.0).unsqueeze(0) + return img + +def load_classes(namesfile): + fp = open(namesfile, "r") + names = fp.read().split("\n")[:-1] + return names diff --git a/DroneCV/README.md b/DroneCV/README.md new file mode 100644 index 00000000..9d3ec691 --- /dev/null +++ b/DroneCV/README.md @@ -0,0 +1,62 @@ +### DroneCV Project for Secure and Private AI Challenge (robotics, computer vision, deep learning) + +![](https://github.com/jess-s/SPAIC-DroneCV/blob/master/images/drone.jpg) + +# SPAIC-DroneCV +How can you use a drone to track objects or people and what would be the use case for this implementation? +Throughout the weeks the team of the Drone Tracking study group have researched use cases, implemented tutorials and tried to find information how to integrate federated learning and differential privacy with a drone. + +### Key Accomplishments + +* Object tracking with OpenCV +* Colour tracking +* Object tracking with PyTorch +* Added code to a drone for object detection +* Authored articles & tutorials for Computer Vision with Drones + +### Use Case +Our team considered many possible use cases for a drone that could follow a target, which are discussed in the wiki page "Use Cases" within this github repo. Initially, we considered the safety benefits of a drone following a person with a health condition such as epilepsy, dementia, or a serious heart condition as they move through public space. We also considered the benefits for atheletes to have a drone follow them as they train, possibly recording data about the route, pace, terrain, and performance to develop personalize training programs. But, ultimately, we decided to focus on the use case of Rescue at Sea because it holds great potential for positive impact. + +Our team has unique insight into this dangerous situation... + +### Drone CV- Rescue at Sea (Helena's insights) + +Having worked at sea as a mechanic for the first part of my professional life I have been trained in safety at sea. +When we started working with our DroneCV project we thought of different use cases for a drone that could track people or an object. One of the use cases was: + +“A drone could be helpful to follow and localize people at sea. A drone connected to a ship or sailboat could be helpful in case of emergency and keep track of people falling overboard or/and detect them if the ship sinks.” + +If ships had rescue drones onboard these could be used in case of man overboard. Even a calm day with almost no waves it is very hard to detect someone that has fallen overboard from a ship. If someone fell overboard a rescue drone could be sent out to track that person in the water and function as a beacon for the rescue crew. It could also drop a life west or a float for the person in the water. +This rescue drone could also be used from shore. It could work as an additional help for life guards along the beaches. + +We have demonstrated the tracking of people (superheroes) in water through this YouTube video with real drone footage: +- [Drone tracking a ship and people (superheroes) overboard](https://youtu.be/MBKmas-Z4_c) (no superheroes were harmed in the making of this video) + +The object tracking is implemented in PyTorch and the code can be found [here](https://github.com/jess-s/SPAIC-DroneCV/tree/master/PyTorch_Objecttracking) + +The drone used for the video is a [Heron Drone](https://www.kjell.com/se/produkter/hem-kontor-fritid/fritid/dronare-quadrocopter/dronare-med-kamera/heron-dronare-med-kamera-p51107?gclid=CjwKCAjw7uPqBRBlEiwAYDsr12AkBzrjregM2xXXO8sEZm3WuRMCH2uPEM7TDnVz154f1I0E8ZwcrRoCKwsQAvD_BwE&gclsrc=aw.ds) +*** +During research after selecting this use case, we discovered that it had been selected as an [AI for Social Good Workshop at neurIPS](https://aiforsocialgood.github.io/2018/pdfs/track2/50_aisg_neurips2018.pdf) in 2018 which supports the value of this use case. + +### Team Members +- [Jess](https://github.com/jess-s) (@Jess) +- [Helena Barmer](https://github.com/helenabarmer) (@Helena Barmer) +- [Shashi Gharti](https://github.com/shashigharti) (@Shashi Gharti) +- [Arunn Thevapalan](https://github.com/arunn-thevapalan) (@Arunn) +- [Shashank Jain](https://github.com/Shashankjain12) (@Shashank Jain) +- [Temitope Oladokun](https://github.com/TemitopeOladokun) (@Temitope Oladokun) + + +### Wiki pages + +Please make sure to read the wiki page where we have written articles and shared resources: +- [Article: Drones- Track athletes outdoor activities and medically resuscitate](https://github.com/jess-s/SPAIC-DroneCV/wiki/Article:-Drones--Track-athletes-outdoor-activities-and-medically-resuscitate-(Temitope-Oladokun)) +- [Article: Real Time Object Detection at a Glance](https://github.com/jess-s/SPAIC-DroneCV/wiki/Article:-Real-Time-Object-Detection-at-a-Glance-(Temitope-Oladokun)) +- [Article: What is Real Time Object Detection?](https://github.com/jess-s/SPAIC-DroneCV/wiki/Article:-What-is-Real-Time-Object-Detection%3F-(Jess)) +- [Future implementations](https://github.com/jess-s/SPAIC-DroneCV/wiki/Future-implementations) +- [Links and resources](https://github.com/jess-s/SPAIC-DroneCV/wiki/Links-and-resources) +- [Resources: Federated Learning and Drones)](https://github.com/jess-s/SPAIC-DroneCV/wiki/Resources:-Federated-Learning-and-Drones-(Jess)) +- [Resources: Object tracking in PyTorch](https://github.com/jess-s/SPAIC-DroneCV/wiki/Resources:-Object-tracking-in-PyTorch-(Helena)) +- [Tutorial: Computer Vision with Jetson Nano](https://github.com/jess-s/SPAIC-DroneCV/wiki/Tutorial:-Computer-Vision-with-Jetson-Nano-(Jess)) +- [Use Cases](https://github.com/jess-s/SPAIC-DroneCV/wiki/Use-Cases) +- [Virtual Meetups summary](https://github.com/jess-s/SPAIC-DroneCV/wiki/Virtual-Meetups-summary-(Helena)) diff --git a/DroneCV/Red colour object tracking b/DroneCV/Red colour object tracking new file mode 100644 index 00000000..3a631f45 --- /dev/null +++ b/DroneCV/Red colour object tracking @@ -0,0 +1,46 @@ +import cv2 +import numpy as np +from cv2 import VideoWriter, VideoWriter_fourcc + +# Capture from video +cap = cv2.VideoCapture("videos/VideoII.mp4") + +# Capture from webcam +#cap = cv2.VideoCapture(0) +fourcc = VideoWriter_fourcc(*'MP42') +video = VideoWriter('./detection.avi', fourcc, float(24), (1280, 720)) + +while True: + ret, frame = cap.read() + + # if we are viewing a video and we did not grab a frame, + # then we have reached the end of the video + if frame is None: + break + + blurred_frame = cv2.GaussianBlur(frame, (5, 5), 0) + hsv = cv2.cvtColor(blurred_frame, cv2.COLOR_BGR2HSV) + + # Red color + low_red = np.array([161, 155, 84]) + high_red = np.array([179, 255, 255]) + mask = cv2.inRange(hsv, low_red, high_red) + # red = cv2.bitwise_and(frame, frame, mask=red_mask) + + contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) + + for contour in contours: + cv2.drawContours(frame, contour, -1, (0, 255, 0), 3) + mframe = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB) + rMask = cv2.resize(mframe, (400, 400), interpolation=cv2.INTER_AREA) + + cv2.imshow("Frame", frame) + cv2.imshow("Mask", rMask) + video.write(mframe) + key = cv2.waitKey(25) + if key == 27: + break + +cap.release() +video.release() +cv2.destroyAllWindows() diff --git a/DroneCV/Shashank_objecttrack/obj_track.mp4 b/DroneCV/Shashank_objecttrack/obj_track.mp4 new file mode 100644 index 00000000..9389034e Binary files /dev/null and b/DroneCV/Shashank_objecttrack/obj_track.mp4 differ diff --git a/DroneCV/Shashank_objecttrack/object_tracking.py b/DroneCV/Shashank_objecttrack/object_tracking.py new file mode 100644 index 00000000..0f0538e0 --- /dev/null +++ b/DroneCV/Shashank_objecttrack/object_tracking.py @@ -0,0 +1,41 @@ + +import cv2 +from imutils.video import FPS +tracker=cv2.TrackerCSRT_create() +#initialize the bounding box +initbb=None +fps=None + +cap=cv2.VideoCapture(0) +while True: + _,frame=cap.read() + #frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) + frame=cv2.resize(frame,(640, 480)) + (H,W) =frame.shape[:2] + if initbb is not None: + (sucess,box)=tracker.update(frame) + if sucess: + (x,y,w,h)=[int(v) for v in box] + cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2) + fps.update() + fps.stop() + info=[("Tracker","CSRT"), + ("Success", "yes" if sucess else "No"), + ("FPS", "{:.2f}".format(fps.fps())),] + # loop over the info tuples and draw them on our frame + for (i, (k, v)) in enumerate(info): + text="{}:{}".format(k,v) + cv2.putText(frame,text,(10, H - ((i * 20) + 20)), + cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2) + + cv2.imshow("Frame",frame) + key = cv2.waitKey(1) & 0xFF + if key==ord("s"): + initbb=cv2.selectROI("Frame",frame,fromCenter=False,showCrosshair=True) + tracker.init(frame,initbb) + fps = FPS().start() + + elif key==ord('q'): + break + +cv2.destroyAllWindows() diff --git a/DroneCV/detect-and-track-drone/detect-and-track-from-drone.py b/DroneCV/detect-and-track-drone/detect-and-track-from-drone.py new file mode 100644 index 00000000..606cc928 --- /dev/null +++ b/DroneCV/detect-and-track-drone/detect-and-track-from-drone.py @@ -0,0 +1,92 @@ +# IMPLEMENTATION OF THE DRONE OBJECT DETECTION AND TRACKING DEMO +# python detect-and-track-from-drone.py --video FlightDemo.mp4 + +# import the necessary packages +import argparse +import imutils +import cv2 + +# construct the argument parse and parse the arguments +ap = argparse.ArgumentParser() +ap.add_argument("-v", "--video", help="path to the video file") +args = vars(ap.parse_args()) + +# load the video +camera = cv2.VideoCapture(args["video"]) + +# keep looping +while True: + # grab the current frame and initialize the status text + (grabbed, frame) = camera.read() + status = "No Targets" + + # check to see if we have reached the end of the + # video + if not grabbed: + break + + # convert the frame to grayscale, blur it, and detect edges + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + blurred = cv2.GaussianBlur(gray, (7, 7), 0) + edged = cv2.Canny(blurred, 50, 150) + + # find contours in the edge map + cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, + cv2.CHAIN_APPROX_SIMPLE) + cnts = imutils.grab_contours(cnts) + + # loop over the contours + for c in cnts: + # approximate the contour + peri = cv2.arcLength(c, True) + approx = cv2.approxPolyDP(c, 0.01 * peri, True) + + # ensure that the approximated contour is "roughly" rectangular + if len(approx) >= 4 and len(approx) <= 6: + # compute the bounding box of the approximated contour and + # use the bounding box to compute the aspect ratio + (x, y, w, h) = cv2.boundingRect(approx) + aspectRatio = w / float(h) + + # compute the solidity of the original contour + area = cv2.contourArea(c) + hullArea = cv2.contourArea(cv2.convexHull(c)) + solidity = area / float(hullArea) + + # compute whether or not the width and height, solidity, and + # aspect ratio of the contour falls within appropriate bounds + keepDims = w > 25 and h > 25 + keepSolidity = solidity > 0.9 + keepAspectRatio = aspectRatio >= 0.8 and aspectRatio <= 1.2 + + # ensure that the contour passes all our tests + if keepDims and keepSolidity and keepAspectRatio: + # draw an outline around the target and update the status + # text + cv2.drawContours(frame, [approx], -1, (0, 0, 255), 4) + status = "Target(s) Acquired" + + # compute the center of the contour region and draw the + # crosshairs + M = cv2.moments(approx) + (cX, cY) = (int(M["m10"] // M["m00"]), int(M["m01"] // M["m00"])) + (startX, endX) = (int(cX - (w * 0.15)), int(cX + (w * 0.15))) + (startY, endY) = (int(cY - (h * 0.15)), int(cY + (h * 0.15))) + cv2.line(frame, (startX, cY), (endX, cY), (0, 0, 255), 3) + cv2.line(frame, (cX, startY), (cX, endY), (0, 0, 255), 3) + + # draw the status text on the frame + cv2.putText(frame, status, (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, + (0, 0, 255), 2) + + # show the frame and record if a key is pressed + cv2.imshow("Frame", frame) + key = cv2.waitKey(1) & 0xFF + + # if the 'q' key is pressed, stop the loop + if key == ord("q"): + break + +# cleanup the camera and close any open windows +camera.release() +cv2.destroyAllWindows() diff --git a/DroneCV/images/20190818_134626(1).jpg b/DroneCV/images/20190818_134626(1).jpg new file mode 100644 index 00000000..cd4b3dcb Binary files /dev/null and b/DroneCV/images/20190818_134626(1).jpg differ diff --git a/DroneCV/images/drone.jpg b/DroneCV/images/drone.jpg new file mode 100644 index 00000000..8ab15a0e Binary files /dev/null and b/DroneCV/images/drone.jpg differ diff --git a/DroneCV/videos/20190818_134626(1).jpg b/DroneCV/videos/20190818_134626(1).jpg new file mode 100644 index 00000000..cd4b3dcb Binary files /dev/null and b/DroneCV/videos/20190818_134626(1).jpg differ diff --git a/DroneCV/videos/readme.md b/DroneCV/videos/readme.md new file mode 100644 index 00000000..fb9c98be --- /dev/null +++ b/DroneCV/videos/readme.md @@ -0,0 +1,5 @@ +## Real-time Computer Vision from our Drone + +[Drone Tracking Ship and Superheroes Overboard](https://youtu.be/MBKmas-Z4_c) + +[Object Tracking with Example](https://github.com/jess-s/SPAIC-DroneCV/blob/master/Shashank_objecttrack/obj_track.mp4) diff --git a/Sajjad Manal/aerial-cactus-classification/aerial-cactus-classification-using-pytorch.ipynb b/Sajjad Manal/aerial-cactus-classification/aerial-cactus-classification-using-pytorch.ipynb new file mode 100644 index 00000000..13838105 --- /dev/null +++ b/Sajjad Manal/aerial-cactus-classification/aerial-cactus-classification-using-pytorch.ipynb @@ -0,0 +1,487 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19", + "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['test', 'train', 'train.csv', 'sample_submission.csv']\n" + ] + } + ], + "source": [ + "# This Python 3 environment comes with many helpful analytics libraries installed\n", + "# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n", + "# For example, here's several helpful packages to load in \n", + "\n", + "import numpy as np\n", + "import pandas as pd \n", + "import matplotlib.pyplot as plt\n", + "import matplotlib.image as Image\n", + "# Input data files are available in the \"../input/\" directory.\n", + "# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n", + "\n", + "import os\n", + "print(os.listdir(\"../input\"))\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import Dataset, DataLoader\n", + "import torchvision.transforms as transforms\n", + "\n", + "# Any results you write to the current directory are saved as output." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "_cell_guid": "79c7e3d0-c299-4dcb-8224-4455121ee9b0", + "_uuid": "d629ff2d2480ee46fbb7e2d37f6b5fab8052498a" + }, + "outputs": [], + "source": [ + "data_dir = \"../input\"\n", + "train_dir = data_dir + \"/train/train\"\n", + "test_dir = data_dir + \"/test/test\"" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
idhas_cactus
00004be2cfeaba1c0361d39e2b000257b.jpg1
1000c8a36845c0208e833c79c1bffedd1.jpg1
2000d1e9a533f62e55c289303b072733d.jpg1
30011485b40695e9138e92d0b3fb55128.jpg1
40014d7a11e90b62848904c1418fc8cf2.jpg1
\n", + "
" + ], + "text/plain": [ + " id has_cactus\n", + "0 0004be2cfeaba1c0361d39e2b000257b.jpg 1\n", + "1 000c8a36845c0208e833c79c1bffedd1.jpg 1\n", + "2 000d1e9a533f62e55c289303b072733d.jpg 1\n", + "3 0011485b40695e9138e92d0b3fb55128.jpg 1\n", + "4 0014d7a11e90b62848904c1418fc8cf2.jpg 1" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "labels = pd.read_csv(data_dir + \"/train.csv\")\n", + "labels.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1 13136\n", + "0 4364\n", + "Name: has_cactus, dtype: int64" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "balance = labels['has_cactus'].value_counts()\n", + "balance" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "train, valid = train_test_split(labels, stratify=labels.has_cactus, test_size=0.2)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "device(type='cuda', index=0)" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# define hyper-params\n", + "num_epochs = 25\n", + "num_classes = 2\n", + "batch_size = 128\n", + "learning_rate = 0.0001\n", + "device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n", + "device" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "class cactData(Dataset):\n", + " def __init__(self, split_data, data_root = './', transform=None):\n", + " super().__init__()\n", + " self.df = split_data.values\n", + " self.data_root = data_root\n", + " self.transform = transform\n", + "\n", + " def __len__(self):\n", + " return len(self.df)\n", + " \n", + " def __getitem__(self, index):\n", + " img_name,label = self.df[index]\n", + " img_path = os.path.join(self.data_root, img_name)\n", + " image = Image.imread(img_path)\n", + " if self.transform is not None:\n", + " image = self.transform(image)\n", + " return image, label\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Transform Images" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "mean = [0.5, 0.5, 0.5]\n", + "std = [0.5, 0.5, 0.5]\n", + "\n", + "train_transf = transforms.Compose([transforms.ToPILImage(),\n", + "# transforms.Normalize(mean, std),\n", + "# transforms.RandomCrop(20),\n", + " transforms.ToTensor()\n", + " ])\n", + "\n", + "valid_transf = transforms.Compose([transforms.ToPILImage(),\n", + " transforms.ToTensor()])" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "train_data = cactData(train, train_dir, train_transf)\n", + "valid_data = cactData(valid, train_dir, valid_transf)\n", + "\n", + "train_loader = DataLoader(dataset=train_data, batch_size=batch_size, shuffle=True, num_workers=0)\n", + "\n", + "valid_loader = DataLoader(dataset=valid_data, batch_size=batch_size//2, shuffle=False, num_workers=0)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "### image dimension for each layer = (width - kernel_size + 2 * padding)/stride + 1\n", + "class CactCNN(nn.Module):\n", + " def __init__(self):\n", + " super(CactCNN, self).__init__()\n", + " self.conv1 = nn.Sequential(\n", + " nn.Conv2d(3, 32, 4, 2, 0),\n", + " nn.BatchNorm2d(32),\n", + " nn.ReLU()\n", + " )\n", + " # 1 + (32 - 4 + 0)/2 = 15\n", + " # 32 * 15 * 15\n", + " self.conv2 = nn.Sequential(\n", + " nn.Conv2d(32, 64, 3, 2, 0),\n", + " nn.BatchNorm2d(64),\n", + " nn.ReLU()\n", + " )\n", + " # 1 + (15 - 3 + 0)/2 = 7\n", + " # 64 * 7 * 7\n", + " self.conv3 = nn.Sequential(\n", + " nn.Conv2d(64, 128, 3, 2, 0),\n", + " nn.BatchNorm2d(128),\n", + " nn.ReLU()\n", + " )\n", + " # 1 + (7 - 3 + 0)/2 = 3\n", + " # 128 * 3 * 3\n", + " self.conv4 = nn.Sequential(\n", + " nn.Conv2d(128, 256, 3, 2, 0),\n", + " nn.BatchNorm2d(256),\n", + " nn.ReLU()\n", + " )\n", + " # 1 + (3 - 3 + 0)/2 = 1\n", + " # 256 * 1 * 1\n", + " \n", + " self.fc = nn.Sequential(\n", + " nn.Linear(256*1*1, 1024),\n", + " nn.ReLU(),\n", + " nn.Dropout(p=0.2),\n", + " nn.Linear(1024,2)\n", + " )\n", + " def forward(self, x):\n", + " x = self.conv1(x)\n", + "\n", + " x = self.conv2(x)\n", + "\n", + " x = self.conv3(x)\n", + "\n", + " x = self.conv4(x)\n", + "\n", + " x = x.view(x.shape[0],-1)\n", + " x = self.fc(x)\n", + " return x" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "cuda:0\n" + ] + } + ], + "source": [ + "model = CactCNN().to(device)\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n", + "print(device)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Epoch: 1/25, Loss: 0.025072911754250526\n", + "Epoch: 2/25, Loss: 0.17733657360076904\n", + "Epoch: 3/25, Loss: 0.0014047473669052124\n", + "Epoch: 4/25, Loss: 0.037795573472976685\n", + "Epoch: 5/25, Loss: 0.10043737292289734\n", + "Epoch: 6/25, Loss: 0.0002894103527069092\n", + "Epoch: 7/25, Loss: 0.001063227653503418\n", + "Epoch: 8/25, Loss: 0.006667168345302343\n", + "Epoch: 9/25, Loss: 0.001863032579421997\n", + "Epoch: 10/25, Loss: 0.0013552954187616706\n", + "Epoch: 11/25, Loss: 0.014680641703307629\n", + "Epoch: 12/25, Loss: 0.007233674172312021\n", + "Epoch: 13/25, Loss: 0.01016581617295742\n", + "Epoch: 14/25, Loss: 0.0035864003002643585\n", + "Epoch: 15/25, Loss: 0.005976095795631409\n", + "Epoch: 16/25, Loss: 0.04689909517765045\n", + "Epoch: 17/25, Loss: 0.07321375608444214\n", + "Epoch: 18/25, Loss: 2.7229389161220752e-05\n", + "Epoch: 19/25, Loss: 0.0032678768038749695\n", + "Epoch: 20/25, Loss: 4.9253303586738184e-05\n", + "Epoch: 21/25, Loss: 0.017891816794872284\n", + "Epoch: 22/25, Loss: 9.959936141967773e-05\n", + "Epoch: 23/25, Loss: 0.08233936876058578\n", + "Epoch: 24/25, Loss: 1.2119611483285553e-06\n", + "Epoch: 25/25, Loss: 0.01408046018332243\n" + ] + } + ], + "source": [ + "for epoch in range(num_epochs):\n", + " for i, (images, labels) in enumerate(train_loader):\n", + " images = images.to(device)\n", + " labels = labels.to(device)\n", + "# print(images[0].shape)\n", + " \n", + " out = model(images)\n", + " loss = criterion(out, labels)\n", + " \n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + " print('Epoch: {}/{}, Loss: {}'.format(epoch+1, num_epochs, loss.item()))" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Test Accuracy: 97.8 %\n" + ] + } + ], + "source": [ + "model.eval()\n", + "with torch.no_grad():\n", + " correct = 0\n", + " total = 0\n", + " for images, labels in valid_loader:\n", + " images = images.to(device)\n", + " labels = labels.to(device)\n", + " outputs = model(images)\n", + " _, predicted = torch.max(outputs.data, 1)\n", + " total += labels.size(0)\n", + " correct += (predicted == labels).sum().item()\n", + " print('Test Accuracy: {} %'.format(100 * correct / total))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# For Submission" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "submit = pd.read_csv(data_dir + '/sample_submission.csv')\n", + "test_data = cactData(split_data = submit, data_root = test_dir, transform = valid_transf)\n", + "test_loader = DataLoader(dataset = test_data, batch_size=32, shuffle=False, num_workers=0)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "model.eval()\n", + "predict = []\n", + "for batch_i, (data, target) in enumerate(test_loader):\n", + " data, target = data.to(device), target.to(device)\n", + " output = model(data)\n", + "\n", + " pr = output[:,1].detach().cpu().numpy()\n", + " for i in pr:\n", + " predict.append(i)\n", + "\n", + "submit['has_cactus'] = predict\n", + "submit.to_csv('submission.csv', index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Sajjad Manal/aerial-cactus-classification/readme.md b/Sajjad Manal/aerial-cactus-classification/readme.md new file mode 100644 index 00000000..b40076c0 --- /dev/null +++ b/Sajjad Manal/aerial-cactus-classification/readme.md @@ -0,0 +1,4 @@ +# Aerial Cactus Classification +This repository contains the notebook submitted for Kaggle competition. +
+The final accuracy achieved on est dataset by Kaggle was 99.27% which can be found at [Final Submission](https://www.kaggle.com/sajjadmanal/kernel19546b3b89?scriptVersionId=18140030)