Full Code of RiccardoGrin/darknet for AI

master a0f951e233a6 cached
130 files
1.1 MB
336.6k tokens
1053 symbols
1 requests
Download .txt
Showing preview only (1,145K chars total). Download the full file or copy to clipboard to get everything.
Repository: RiccardoGrin/darknet
Branch: master
Commit: a0f951e233a6
Files: 130
Total size: 1.1 MB

Directory structure:
gitextract_6ruq8af_/

├── .gitignore
├── Licenses/
│   ├── LICENSE
│   ├── LICENSE.fuck
│   ├── LICENSE.gen
│   ├── LICENSE.gpl
│   ├── LICENSE.meta
│   ├── LICENSE.mit
│   └── LICENSE.v1
├── Makefile
├── README.md
├── examples/
│   ├── art.c
│   ├── attention.c
│   ├── captcha.c
│   ├── cifar.c
│   ├── classifier.c
│   ├── coco.c
│   ├── darknet.c
│   ├── detector.c
│   ├── detector.py
│   ├── dice.c
│   ├── go.c
│   ├── lsd.c
│   ├── nightmare.c
│   ├── regressor.c
│   ├── rnn.c
│   ├── rnn_vid.c
│   ├── segmenter.c
│   ├── super.c
│   ├── swag.c
│   ├── tag.c
│   ├── voxel.c
│   ├── writing.c
│   └── yolo.c
├── include/
│   └── darknet.h
├── python/
│   ├── darknet.py
│   └── proverbot.py
└── src/
    ├── activation_kernels.cu
    ├── activation_layer.c
    ├── activation_layer.h
    ├── activations.c
    ├── activations.h
    ├── avgpool_layer.c
    ├── avgpool_layer.h
    ├── avgpool_layer_kernels.cu
    ├── batchnorm_layer.c
    ├── batchnorm_layer.h
    ├── blas.c
    ├── blas.h
    ├── blas_kernels.cu
    ├── box.c
    ├── box.h
    ├── classifier.h
    ├── col2im.c
    ├── col2im.h
    ├── col2im_kernels.cu
    ├── compare.c
    ├── connected_layer.c
    ├── connected_layer.h
    ├── convolutional_kernels.cu
    ├── convolutional_layer.c
    ├── convolutional_layer.h
    ├── cost_layer.c
    ├── cost_layer.h
    ├── crnn_layer.c
    ├── crnn_layer.h
    ├── crop_layer.c
    ├── crop_layer.h
    ├── crop_layer_kernels.cu
    ├── cuda.c
    ├── cuda.h
    ├── data.c
    ├── data.h
    ├── deconvolutional_kernels.cu
    ├── deconvolutional_layer.c
    ├── deconvolutional_layer.h
    ├── demo.c
    ├── demo.h
    ├── detection_layer.c
    ├── detection_layer.h
    ├── dropout_layer.c
    ├── dropout_layer.h
    ├── dropout_layer_kernels.cu
    ├── gemm.c
    ├── gemm.h
    ├── gru_layer.c
    ├── gru_layer.h
    ├── im2col.c
    ├── im2col.h
    ├── im2col_kernels.cu
    ├── image.c
    ├── image.h
    ├── layer.c
    ├── layer.h
    ├── list.c
    ├── list.h
    ├── local_layer.c
    ├── local_layer.h
    ├── lstm_layer.c
    ├── lstm_layer.h
    ├── matrix.c
    ├── matrix.h
    ├── maxpool_layer.c
    ├── maxpool_layer.h
    ├── maxpool_layer_kernels.cu
    ├── network.c
    ├── network.h
    ├── normalization_layer.c
    ├── normalization_layer.h
    ├── option_list.c
    ├── option_list.h
    ├── parser.c
    ├── parser.h
    ├── region_layer.c
    ├── region_layer.h
    ├── reorg_layer.c
    ├── reorg_layer.h
    ├── rnn_layer.c
    ├── rnn_layer.h
    ├── route_layer.c
    ├── route_layer.h
    ├── shortcut_layer.c
    ├── shortcut_layer.h
    ├── softmax_layer.c
    ├── softmax_layer.h
    ├── stb_image.h
    ├── stb_image_write.h
    ├── tree.c
    ├── tree.h
    ├── utils.c
    └── utils.h

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
*.o
*.dSYM
*.csv
*.out
*.png
*.jpg
*.pyc
*.weights
*.a
*.so
*.23
scripts/
data/
images/
labels/
backup/
cfg/
darknet
.fuse*

# OS Generated #
.DS_Store*
ehthumbs.db
Icon?
Thumbs.db
*.swp


================================================
FILE: Licenses/LICENSE
================================================
                                  YOLO LICENSE
                             Version 2, July 29 2016

THIS SOFTWARE LICENSE IS PROVIDED "ALL CAPS" SO THAT YOU KNOW IT IS SUPER
SERIOUS AND YOU DON'T MESS AROUND WITH COPYRIGHT LAW BECAUSE YOU WILL GET IN
TROUBLE HERE ARE SOME OTHER BUZZWORDS COMMONLY IN THESE THINGS WARRANTIES
LIABILITY CONTRACT TORT LIABLE CLAIMS RESTRICTION MERCHANTABILITY. NOW HERE'S
THE REAL LICENSE:

0. Darknet is public domain.
1. Do whatever you want with it.
2. Stop emailing me about it!


================================================
FILE: Licenses/LICENSE.fuck
================================================
           DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                   Version 2, December 2004

Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.

           DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
  TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

 0. You just DO WHAT THE FUCK YOU WANT TO.


================================================
FILE: Licenses/LICENSE.gen
================================================
RNN LICENSE Version 3, June 21 2017

Copyright (c) 1990, 1989, 1999 Free87337 May 48 THIRD PARTIES OR ANY OTHER THE
COMPLAIN OR CONSEQUENTIAL DAMAGES AND REGARDLESS OF WHETHER IN CONTRACT, TO THE
EXTENT REPAIR OR AGENTS (NOT THE IN ANY EVENT). THE SOFTWARE WILL BE
UNINTERRUPTED OR ERROR-FREE OR ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF ALL THE WORK (GOVERNED CODE) HIM RESPONSES, OR OF FINES,
SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR ANY OTHER OR OTHER HARL UNDER NO
CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE),
PATENT PERMITTED BY THE INSTAGRAM PARENT STATE OR TORT (INCLUDING NEGLIGENCE),
PRODUCT LIABILITY OR OTHERWISE, ARISING OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR ANYTHING PROVIDED IN THIS PRODUCT, COMMIS AND SERVICES
ARE LICENSED SOFTWARE AND ANY RESULE OR ANY OTHER THE COPYRIGHT HOLDERS BE
LIABLE FOR ANY SPECIAL, INCIDENTAL, CASE, SUCH WARRANTIES, EXPRESS OR IMPLIED,
INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COPYRIGHT HOLDERS AND/OR ANY
PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY
EXPRESS OR DISTRIBUTE THAT ALL CLAIMS ARE SHALL CREATE DERAVE BE LIABLE TO YOU
WILL HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

6\. TERMINATION. TO THE EXTENT PERMITTED BY LAW, NO USE OF THE COVERED CODE IS
WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
SERVICING, REPAIR OR COULT OR IN ANY WAY OUT OF THE USE OF THE WEBSITES OR
SERVICE WILL BE CONSEQUENTIAL DAMAGES OF ANY KIND HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.


This paragraph Agreement constitutes the entire agreement between the parties
with respect to the Work licensed here. However, if you place the name of the
fact that the arbitration was the consultation of the parties as a "patent is".
Subject to the terms and conditions of this License, Contributor has knowledge
that a license under a third party may also be used to endorse or promote
products derived from the Work, and there is no warranty on the Software and
Science Fees. For the purposes of this Agreement, attach the following
disclaimers (without liabilities of written notice to the Subject Software) in a
manner that a product is under common control with you. The Free Software
Foundation may publish revised and/or new versions of the License for the
Modifications made by the applicable terms. The Recipient shall promptly retain
the covered works for any reason be entered in any federal or state or login
Restricted Laws appearing in the United States or any of its own information
that is not disabled from a derivative work except as expressly permitted in
this License, to the extent that they are in receiving the Software and Source
Code or any exercise of the rights granted to You by this License or a
Contributor made by the Licensor or are authorized to make a reasonable
retirement by the courts of the courts located in Santa Clara County, California
printed and related to the Work or “Company” and Apache Software Foundation. If
the Licensor shall be entitled to reflect your rights to use the Software and
the Software to exercise the rights granted to the recipient without a
requirement to exercise the rights granted by the Agreement to the provision
will begin will appear in such cases, you will use such information without such
corporation shall be an officer with respect to any part of the Software or any
portion thereof. Capitalized terms are included in the Initial Contributor and
under no circumstances will license the Service at any time and for any direct,
indirect, special, incidental, or consequential damages of or assist in
connection with any Services or the registration purposes only to the extent
that it includes any or all means including the processing of which you download
any derivative work. Any of the purchases’ transmission purposes are made
available, if any, in other circumstances, we may review the copyright notice.
In the event that this Agreement is required to give us strict content. The
inclusion of the other party hereunder may also notify you Intellectual Property
Rights to any third party. This means that the Source Code exists of the Work
will not charge a program available to you at any time. You must include a
prominent statement that the Software is governed under a particular version of
this Agreement. You must include a provision to the extent that there is no
warranty for the content of others. You agree that the Recipient was appointed
as a Contributor, (c) are effective until terminated by hereunder, then the
registration are not disabled and not limited to, submit any Customer Data
without the updated use of the Software and that no fee is released. You grant
to Use Other Arbitration Rules for Diagnostic or Services may use or modify the
Apple Software and Consolidated Apple Software or Services. The Company may have
full risk as a product of the Compatible Source. A Contribution by the Licensor
or by the updated Software under the following conditions we can redistribute
any General Provision of this Agreement. If the Program is used in accordance
with the terms of this Agreement, Customer may provide advertisements from your
devices that clause you can your employer or a transaction or country that has
been controlled by the arbitrator, that they will be useful of this Agreement.
The term "Open Source Software is available in connection with the program, and
you may not protect the combination of the Covered Code. You should like to
select a user's rights to charge a copy of this License. I are Contributor's
confidentiality of the exercise of the rights granted herein. Such a covered
work is released as a consequence, the Licensor shall be eligible for a purpose
or subcontractor of the person or entity to the user of the user, then the word
"Application" means having the original fee for any reason; and that no patent
license to more than fifty stated close of the license term. The terms of this
License will the license terms and conditions set forth in Section 2.2 (OPEC)
and You will not use the Software or any set of responsibility for any resulting
information that the Original Code warrants that you have the right to disclose
these information (or in the notification; or (iii) late use of the software or
any third party to the three (50) days before such belief to the extent that it
includes a court court obtains the rights granted by this License.


================================================
FILE: Licenses/LICENSE.gpl
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is 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.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  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.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  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 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. Use with the GNU Affero General Public License.

  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 Affero 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 special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU 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 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 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 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.

    {one line to give the program's name and a brief idea of what it does.}
    Copyright (C) {year}  {name of author}

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    {project}  Copyright (C) {year}  {fullname}
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  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 GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: Licenses/LICENSE.meta
================================================
                          META-LICENSE
                    Version 1, June 21 2017

Any and all licenses may be applied to the software either individually
or in concert. Any issues, ambiguities, paradoxes, or metaphysical quandries
arising from this combination should be discussed with a local faith leader,
hermit, or guru. The Oxford comma shall be used.



================================================
FILE: Licenses/LICENSE.mit
================================================
MIT License

Copyright (c) 2017 Joseph Redmon

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.



================================================
FILE: Licenses/LICENSE.v1
================================================
                                  YOLO LICENSE
                             Version 1, July 10 2015

THIS SOFTWARE LICENSE IS PROVIDED "ALL CAPS" SO THAT YOU KNOW IT IS SUPER
SERIOUS AND YOU DON'T MESS AROUND WITH COPYRIGHT LAW BECAUSE YOU WILL GET IN
TROUBLE HERE ARE SOME OTHER BUZZWORDS COMMONLY IN THESE THINGS WARRANTIES
LIABILITY CONTRACT TORT LIABLE CLAIMS RESTRICTION MERCHANTABILITY SUBJECT TO
THE FOLLOWING CONDITIONS:

1. #yolo
2. #swag
3. #blazeit



================================================
FILE: Makefile
================================================
GPU=1
CUDNN=1
OPENCV=0
OPENMP=0
DEBUG=0

ARCH= -gencode arch=compute_30,code=sm_30 \
      -gencode arch=compute_35,code=sm_35 \
      -gencode arch=compute_50,code=[sm_50,compute_50] \
      -gencode arch=compute_52,code=[sm_52,compute_52]
#      -gencode arch=compute_20,code=[sm_20,sm_21] \ This one is deprecated?

# This is what I use, uncomment if you know your arch and want to specify
# ARCH= -gencode arch=compute_52,code=compute_52

VPATH=./src/:./examples
SLIB=libdarknet.so
ALIB=libdarknet.a
EXEC=darknet
OBJDIR=./obj/

CC=gcc
NVCC=nvcc
AR=ar
ARFLAGS=rcs
OPTS=-Ofast
LDFLAGS= -lm -pthread
COMMON= -Iinclude/ -Isrc/
CFLAGS=-Wall -Wno-unknown-pragmas -Wfatal-errors -fPIC

ifeq ($(OPENMP), 1)
CFLAGS+= -fopenmp
endif

ifeq ($(DEBUG), 1)
OPTS=-O0 -g
endif

CFLAGS+=$(OPTS)

ifeq ($(OPENCV), 1)
COMMON+= -DOPENCV
CFLAGS+= -DOPENCV
LDFLAGS+= `pkg-config --libs opencv`
COMMON+= `pkg-config --cflags opencv`
endif

ifeq ($(GPU), 1)
COMMON+= -DGPU -I/usr/local/cuda/include/
CFLAGS+= -DGPU
LDFLAGS+= -L/usr/local/cuda/lib64 -lcuda -lcudart -lcublas -lcurand
endif

ifeq ($(CUDNN), 1)
COMMON+= -DCUDNN
CFLAGS+= -DCUDNN
LDFLAGS+= -lcudnn
endif

OBJ=gemm.o utils.o cuda.o deconvolutional_layer.o convolutional_layer.o list.o image.o activations.o im2col.o col2im.o blas.o crop_layer.o dropout_layer.o maxpool_layer.o softmax_layer.o data.o matrix.o network.o connected_layer.o cost_layer.o parser.o option_list.o detection_layer.o route_layer.o box.o normalization_layer.o avgpool_layer.o layer.o local_layer.o shortcut_layer.o activation_layer.o rnn_layer.o gru_layer.o crnn_layer.o demo.o batchnorm_layer.o region_layer.o reorg_layer.o tree.o  lstm_layer.o
<<<<<<< HEAD
EXECOBJA=captcha.o lsd.o super.o voxel.o art.o tag.o cifar.o go.o rnn.o rnn_vid.o compare.o segmenter.o regressor.o classifier.o coco.o dice.o yolo.o detector.o  writing.o nightmare.o swag.o darknet.o
ifeq ($(GPU), 1)
LDFLAGS+= -lstdc++
OBJ+=convolutional_kernels.o deconvolutional_kernels.o activation_kernels.o im2col_kernels.o col2im_kernels.o blas_kernels.o crop_layer_kernels.o dropout_layer_kernels.o maxpool_layer_kernels.o network_kernels.o avgpool_layer_kernels.o
=======
EXECOBJA=captcha.o lsd.o super.o art.o tag.o cifar.o go.o rnn.o segmenter.o regressor.o classifier.o coco.o yolo.o detector.o nightmare.o attention.o darknet.o
ifeq ($(GPU), 1) 
LDFLAGS+= -lstdc++ 
OBJ+=convolutional_kernels.o deconvolutional_kernels.o activation_kernels.o im2col_kernels.o col2im_kernels.o blas_kernels.o crop_layer_kernels.o dropout_layer_kernels.o maxpool_layer_kernels.o avgpool_layer_kernels.o
>>>>>>> upstream/master
endif

EXECOBJ = $(addprefix $(OBJDIR), $(EXECOBJA))
OBJS = $(addprefix $(OBJDIR), $(OBJ))
DEPS = $(wildcard src/*.h) Makefile include/darknet.h

#all: obj backup results $(SLIB) $(ALIB) $(EXEC)
all: obj  results $(SLIB) $(ALIB) $(EXEC)


$(EXEC): $(EXECOBJ) $(ALIB)
	$(CC) $(COMMON) $(CFLAGS) $^ -o $@ $(LDFLAGS) $(ALIB)

$(ALIB): $(OBJS)
	$(AR) $(ARFLAGS) $@ $^

$(SLIB): $(OBJS)
	$(CC) $(CFLAGS) -shared $^ -o $@ $(LDFLAGS)

$(OBJDIR)%.o: %.c $(DEPS)
	$(CC) $(COMMON) $(CFLAGS) -c $< -o $@

$(OBJDIR)%.o: %.cu $(DEPS)
	$(NVCC) $(ARCH) $(COMMON) --compiler-options "$(CFLAGS)" -c $< -o $@

obj:
	mkdir -p obj
backup:
	mkdir -p backup
results:
	mkdir -p results

.PHONY: clean

clean:
	rm -rf $(OBJS) $(SLIB) $(ALIB) $(EXEC) $(EXECOBJ)


================================================
FILE: README.md
================================================
# Darknet
Darknet is an open source neural network framework written in C and CUDA. It is fast, easy to install, and supports CPU and GPU computation.

For more information see the [Darknet project website](http://pjreddie.com/darknet).

For questions or issues please use the [Google Group](https://groups.google.com/forum/#!forum/darknet).

<p align="center"><img src="http://pjreddie.com/media/files/darknet-black-small.png" height="300"></p>



# Training
NOTE: I have started writing this guide for a thesis project, and not everything may be yet clear or complete. I will try to keep expanding on this, and make a very clear guide which will hopefully help out. 

I used the following to help me understand the training process:
- [How to train YOLOv2 to detect custom objects](https://timebutt.github.io/static/how-to-train-yolov2-to-detect-custom-objects/) by [Nils Tijtgat](https://github.com/timebutt)
- [Start Training YOLO with Our Own Data](http://guanghan.info/blog/en/my-works/train-yolo/) by [Guanghan](https://github.com/Guanghan)
- [Yolo-v2 Windows and Linux version](https://github.com/AlexeyAB/darknet) by [Alexey](https://github.com/AlexeyAB)

## Shortcuts
1. [Prerequisites](#prerequisites)
2. [Gathering data](#1---gather-data)
3. [Pre-processing](#2---pre-processing)
4. [Augmentation](#3---augmentation)
5. [Labelling](#4---labelling)
6. [Creating train/test sets](#5---creating-traintest-sets)
7. [Configuration files](#6---configuration-files)
8. [Training](#7---training)
9. [Testing](#8---testing)
10. [Additional Notes](#additional-notes)

## TO DO
- Better explanation of prerequisites and installattion instructions
- Better explanation of training multiple classes
- Add more solutions to common issues
- Add more example images

## Prerequisites
- Ubuntu 16.04 or other Linux distribution
- Linux gcc compiler and toolchain, acquired from development tools of your Linux distribution
- A GPU of compute capability 3.0 or higher, check with [NVIDIA](https://developer.nvidia.com/cuda-gpus)
- [Darknet](https://github.com/pjreddie/darknet)
- [CUDA](https://developer.nvidia.com/cuda-downloads) 8.0 or 9.0. Install [instructions](http://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html)
- [cuDNN v7.0 Runtime Library](https://developer.nvidia.com/rdp/cudnn-download), will require free NVIDIA dev team membership. Install [instructions](http://docs.nvidia.com/deeplearning/sdk/cudnn-install/index.html)
- [Anaconda](https://www.anaconda.com/download/#linux) for Python 2.7

NOTE: OpenCV can also be optionally installed.

## 1 - Gather Data
Though there are many image datasets/databases online, I could not find the images which I wanted, or these were part of a very large set, or the download was simply too large. Therefore, I just used my  phone to take photos. However the smallest photos I could take were 3264\*1836, and their names were not as desired. From research, apparently at least 250 different images are needed for each class. Taking 250 photos can take some time and creativity, therefore I took only half, and did some image augmentation (flipping, rotating, etc...) to get all 250 images. <br />
NOTE: Much better results will be achieved by get the 250 images or more, without applying any augmentation, as there will be more difference between the images. Thus image augmentation should only really be used to increase the set, to further improve the classification accuracy, though it will not be as large an increase as using original iamges.

Both Pre-processing and image augmentation steps will require Imagemagick, which is a free and open-source software suite used for formatting images. Install it using: `sudo apt-get install imagemagick`

## 2 - Pre-processing
Darknet requires the images to be in .jpg format, and of course, the smaller the images, the less computation is required. YOLO will resize your images to its input size of 416\*416, but its not a bad idea to resize it yourself to something around that size, again, to decrease computation time.

### 2.1 - Batch convert images format (eg .png to .jpg):
- Travel to folder with images to convert via terminal
- Convert image format: `mogrify -format jpg *.png`

### 2.2 - Batch resize:
- Travel to the folder containing all image to be resized using the terminal
- Resize keeping aspect ratio: `mogrify -resize 640x360 *.jpg`

### 2.3 - Batch rename:
- Install PyRenamer `sudo apt-get install pyrenamer`
- Open it: `pyrenamer`
- Travel to folder containng images from the left panel
- On the right preview panel, select/highlight all images by pressing `ctrl-a`
- In the "Original file name pattern" box, type ".jpg"
- In the "Renamed file name pattern" box, type "{num3}.jpg"
- Click on the Preview button to see changes to be made. This will rename all .jpg images to ascending numbers (000, 001, 002, etc...)
- Press the Rename button to complete

Here is an example of renaming with PyRenamer. There are other renaming methods that you can also use from the command line, but using a GUI can be quite useful.
<p align="center">
  <img src="readme_images/rename_exp.jpg" width="700"><br>
</p>

## 3 - Augmentation
Images may be augmented in order to expand the dataset with which you can work and train from. It might also be useful in creasting a validation or testing set, though as stated previously, it is always better to have new original images, rather than augmented ones. Not all the following steps are necessary, it depends on how many more images you want to create. 
NOTE: It is not always a great idea to flip images, as most thing are not usually found to be seen upside-down.

Copy and paste all images to be augmented in the same folder (these should be automatically renamed to img_name(copy).jpg). If you are intending to do multiple augmentations, images may need to be renamed to not have the '(copy)' text after their name.

### 3.1 - Batch flip:
- Flip all image copies from the terminal: `mogrify -flip *(copy).jpg`

### 3.2 - Batch flop:
- Flop all image copies from the terminal: `mogrify -flop *(copy).jpg`

### 3.3 - Batch rotate:
The angel can be changed from 90 degrees to whatever is desired. I believe the images get padded for non multiples of 90 degree rotations (not tested though).
- Rotate all image copies from the terminal by 90 degrees: `mogrify -rotate 90 *.jpg`


## 4 - Labelling
To make the process easier, I have changed the orginal [BBox-Label-Tool](https://github.com/puzzledqs/BBox-Label-Tool.git) by [puzzledqs](https://github.com/puzzledqs), so that images would not need to be shifted from fodler to folder to get all the different scripts to work. Also I have made it so that you can open a file with the name of the class in the images folder.
- In the home directory, clone the revised BBox-Label-Tool: `git clone https://github.com/RiccardoGrin/BBox-Label-Tool`
- Open `main.py` in an editor (I personally prefer Atom)
- Change lines 109 and 123 to point to your 'images' and 'labels' folders respectively
- Create a folder within the 'images' folder, for each class, with the class name
- Collect each image from each class and place it in their respective folder
- Create a folder within the 'labels' folder, for each class, with the class name
- Open main: `python main.py`
- Label every image (will take some time)

NOTE: If you cannot open 'main.py', check if python is opened as the default or Anaconda version by opening it from the terminal by typing `which python`. If it is the defaults version, open `.bachrc` from the home directory using an edition (Atom, nano, vim, etc...), and add at the very end `export PATH=~/anaconda2/bin:$PATH`, then in the command line type `source .bashrc`. Try to open 'main.py' again.

Here is a guided example of how to use the revised labelling tool.
<p align="center">
  <img src="readme_images/label_exp.jpg" width="700"><br>
</p>

### 4.1 - Converting labels
I have done some changes to the original [convert.py](https://github.com/Guanghan/darknet/tree/master/scripts), written by [Guanghan](https://github.com/Guanghan) while I was learning to use it.
- Download the revised version of [convert.py](https://github.com/RiccardoGrin/darknet/blob/master/scripts/convert.py)
- Move 'convert.py' to `darknet/scripts`
- Change the paths on lines 39, 40, and 45 to your own
- Add all your classes in the array on line 16
- Run `python convert.py` from the scripts directory

## 5 - Creating train/test sets
I have made some changes to the 'process.py' script, written by [Nils Tijtgat](https://github.com/timebutt)  as seen on his [guide](https://timebutt.github.io/static/how-to-train-yolov2-to-detect-custom-objects/). This script creates a 'train.txt' and 'test.txt' files required for training and validation. I have made some changes to the script to make it easier to use for multiple classes.
- Download the revised version of [process.py](https://github.com/RiccardoGrin/darknet/blob/master/scripts/process.py)
- Move 'process.py' to `darknet/scripts`
- Set the percentage of images to be set as testing images
- Update the directory in which to create the train and test files on lines 13, 14
- Update the image directory on line 17
- Add all your classes in the array on line 20 (similar to convert.py)
- Run `python process.py` from the scripts directory

## 6 - Configuration files
- In the 'data' directory, create a `obj.names` file, where every line should be a different class names
- In the 'cfg' directory, create a `obj.data` file with the following text (classes = number of classes/objects to train on):
  ```
  classes = 1  
  train = data/train.txt  
  valid = data/test.txt  
  names = data/obj.names  
  backup = backup/
  ```
- Duplicate `yolo-voc.cfg`, and change the name to `obj.cfg`
    - line 3: set `batch=64` (make sure your GPU can handle this, otherwise scale down)
    - line 4: set `subdivisions=8`
    - line 244: set `classes=1` (number of classes you are going to train on)
    - line 237: set `filters=30`, (calculated as `(classes + 5)*5`, eg. `(1+5)\*5 = 30`)
- Create a folder named `backup` in the main darknet directory
- Download [darknet19_488.conv.23](https://pjreddie.com/media/files/darknet19_448.conv.23), and save it into the 'cfg' directory

## 7 - Training
- Open the darknet Makefile and switch GPU and CUDNN to 1 (Make sure there are setup correctly, otherwise training will take forever)
- Run `make` if you have not done so already
- Run `./darknet detector train cfg/obj.data cfg/obj.cfg darknet19_448.conv.23`

This will save a `.weights` files within the backup folder, initially every 100 iterations, till 1000 (not included), and then every 10000 after that. This used to be every 1000 after the first 1000 interations but it was changed. To change it back, edit line 136 in `exemples/detector.c` from 10000 to 1000.

Make sure to read the [explanation](https://github.com/AlexeyAB/darknet#when-should-i-stop-training) by [Alexey](https://github.com/AlexeyAB) on when to stop training.

## 8 - Testing
Test your newly trained algorithm by running the following with a new image:
`./darknet detector test cfg/obj.data cfg/obj.cfg obj1000.weights images/image.jpg`

## Additional notes
1. If the training is ever interrupted at any point, it can be continued by substituting the last saved `.weights` file from the backup folder, with `darknet19_448.conv.23`, in the training command
2. If you get an error like: `darknet: ./src/cuda.c:36: check_error: Assertion '0' failed.`
You can fix it by changing your ARCH (architecture) in the make file, to be appropriate for your GPU. Another simple way I found to temporarely solve it, is to just turn your computer off and on again.

## Pre-trained model weights
YOLO and YOLO9000 require at least 4GB of GPU and RAM (around 190MB downloads)
- [yolo.weights](http://pjreddie.com/media/files/yolo.weights) for `yolo.cfg`
- [yolo-voc.weights](http://pjreddie.com/media/files/yolo-voc.weights) for `yolo-voc.cfg`
- [yolo9000.weights](http://pjreddie.com/media/files/yolo9000.weights) for `yolo9000.cfg`

Tiny YOLO requires at least 1GB of GPU and RAM (around 60MB downloads)
- [tiny-yolo.weights](http://pjreddie.com/media/files/tiny-yolo.weights) for `tiny-yolo.cfg`
- [tiny-yolo-voc.weights](http://pjreddie.com/media/files/tiny-yolo-voc.weights) for `tiny-yolo-voc.cfg`


================================================
FILE: examples/art.c
================================================
#include "darknet.h"

#include <sys/time.h>

void demo_art(char *cfgfile, char *weightfile, int cam_index)
{
#ifdef OPENCV
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);

    srand(2222222);
    CvCapture * cap;

    cap = cvCaptureFromCAM(cam_index);

    char *window = "ArtJudgementBot9000!!!";
    if(!cap) error("Couldn't connect to webcam.\n");
    cvNamedWindow(window, CV_WINDOW_NORMAL); 
    cvResizeWindow(window, 512, 512);
    int i;
    int idx[] = {37, 401, 434};
    int n = sizeof(idx)/sizeof(idx[0]);

    while(1){
        image in = get_image_from_stream(cap);
        image in_s = resize_image(in, net->w, net->h);
        show_image(in, window);

        float *p = network_predict(net, in_s.data);

        printf("\033[2J");
        printf("\033[1;1H");

        float score = 0;
        for(i = 0; i < n; ++i){
            float s = p[idx[i]];
            if (s > score) score = s;
        }
        score = score;
        printf("I APPRECIATE THIS ARTWORK: %10.7f%%\n", score*100);
        printf("[");
	int upper = 30;
        for(i = 0; i < upper; ++i){
            printf("%c", ((i+.5) < score*upper) ? 219 : ' ');
        }
        printf("]\n");

        free_image(in_s);
        free_image(in);

        cvWaitKey(1);
    }
#endif
}


void run_art(int argc, char **argv)
{
    int cam_index = find_int_arg(argc, argv, "-c", 0);
    char *cfg = argv[2];
    char *weights = argv[3];
    demo_art(cfg, weights, cam_index);
}



================================================
FILE: examples/attention.c
================================================
#include "darknet.h"

#include <sys/time.h>
#include <assert.h>

void train_attention(char *datacfg, char *cfgfile, char *weightfile, char *cfgfile2, char *weightfile2, int *gpus, int ngpus, int clear)
{
    int i;

    float avg_loss = -1;
    char *base = basecfg(cfgfile);
    printf("%s\n", base);
    printf("%d\n", ngpus);
    network **attnets = calloc(ngpus, sizeof(network*));
    network **clsnets = calloc(ngpus, sizeof(network*));

    srand(time(0));
    int seed = rand();
    for(i = 0; i < ngpus; ++i){
        srand(seed);
#ifdef GPU
        cuda_set_device(gpus[i]);
#endif
        attnets[i] = load_network(cfgfile, weightfile, clear);
        attnets[i]->learning_rate *= ngpus;
        clsnets[i] = load_network(cfgfile2, weightfile2, clear);
        clsnets[i]->learning_rate *= ngpus;
    }
    srand(time(0));
    network *net = attnets[0];
    //network *clsnet = clsnets[0];

    int imgs = net->batch * net->subdivisions * ngpus;

    printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
    list *options = read_data_cfg(datacfg);

    char *backup_directory = option_find_str(options, "backup", "/backup/");
    char *label_list = option_find_str(options, "labels", "data/labels.list");
    char *train_list = option_find_str(options, "train", "data/train.list");
    int classes = option_find_int(options, "classes", 2);

    char **labels = get_labels(label_list);
    list *plist = get_paths(train_list);
    char **paths = (char **)list_to_array(plist);
    printf("%d\n", plist->size);
    int N = plist->size;
    double time;

    load_args args = {0};
    args.w = 4*net->w;
    args.h = 4*net->h;
    args.size = 4*net->w;
    args.threads = 32;
    args.hierarchy = net->hierarchy;

    args.min = net->min_ratio*net->w;
    args.max = net->max_ratio*net->w;
    args.angle = net->angle;
    args.aspect = net->aspect;
    args.exposure = net->exposure;
    args.saturation = net->saturation;
    args.hue = net->hue;

    args.paths = paths;
    args.classes = classes;
    args.n = imgs;
    args.m = N;
    args.labels = labels;
    args.type = CLASSIFICATION_DATA;

    data train;
    data buffer;
    pthread_t load_thread;
    args.d = &buffer;
    load_thread = load_data(args);

    int epoch = (*net->seen)/N;
    while(get_current_batch(net) < net->max_batches || net->max_batches == 0){
        time = what_time_is_it_now();

        pthread_join(load_thread, 0);
        train = buffer;
        load_thread = load_data(args);
        data resized = resize_data(train, net->w, net->h);

        printf("Loaded: %lf seconds\n", what_time_is_it_now()-time);
        time = what_time_is_it_now();

        float loss = 0;
#ifdef GPU
        if(ngpus == 1){
            loss = train_network(net, train);
        } else {
            loss = train_networks(attnets, ngpus, train, 4);
        }
#else
        loss = train_network(net, train);
#endif
        free_data(resized);
        if(avg_loss == -1) avg_loss = loss;
        avg_loss = avg_loss*.9 + loss*.1;
        printf("%ld, %.3f: %f, %f avg, %f rate, %lf seconds, %ld images\n", get_current_batch(net), (float)(*net->seen)/N, loss, avg_loss, get_current_rate(net), what_time_is_it_now()-time, *net->seen);
        free_data(train);
        if(*net->seen/N > epoch){
            epoch = *net->seen/N;
            char buff[256];
            sprintf(buff, "%s/%s_%d.weights",backup_directory,base, epoch);
            save_weights(net, buff);
        }
        if(get_current_batch(net)%1000 == 0){
            char buff[256];
            sprintf(buff, "%s/%s.backup",backup_directory,base);
            save_weights(net, buff);
        }
    }
    char buff[256];
    sprintf(buff, "%s/%s.weights", backup_directory, base);
    save_weights(net, buff);
    pthread_join(load_thread, 0);

    free_network(net);
    free_ptrs((void**)labels, classes);
    free_ptrs((void**)paths, plist->size);
    free_list(plist);
    free(base);
}

void validate_attention_single(char *datacfg, char *filename, char *weightfile)
{
    int i, j;
    network *net = load_network(filename, weightfile, 0);
    set_batch_network(net, 1);
    srand(time(0));

    list *options = read_data_cfg(datacfg);

    char *label_list = option_find_str(options, "labels", "data/labels.list");
    char *leaf_list = option_find_str(options, "leaves", 0);
    if(leaf_list) change_leaves(net->hierarchy, leaf_list);
    char *valid_list = option_find_str(options, "valid", "data/train.list");
    int classes = option_find_int(options, "classes", 2);
    int topk = option_find_int(options, "top", 1);

    char **labels = get_labels(label_list);
    list *plist = get_paths(valid_list);

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    float avg_acc = 0;
    float avg_topk = 0;
    int *indexes = calloc(topk, sizeof(int));

    for(i = 0; i < m; ++i){
        int class = -1;
        char *path = paths[i];
        for(j = 0; j < classes; ++j){
            if(strstr(path, labels[j])){
                class = j;
                break;
            }
        }
        image im = load_image_color(paths[i], 0, 0);
        image resized = resize_min(im, net->w);
        image crop = crop_image(resized, (resized.w - net->w)/2, (resized.h - net->h)/2, net->w, net->h);
        //show_image(im, "orig");
        //show_image(crop, "cropped");
        //cvWaitKey(0);
        float *pred = network_predict(net, crop.data);
        if(net->hierarchy) hierarchy_predictions(pred, net->outputs, net->hierarchy, 1, 1);

        if(resized.data != im.data) free_image(resized);
        free_image(im);
        free_image(crop);
        top_k(pred, classes, topk, indexes);

        if(indexes[0] == class) avg_acc += 1;
        for(j = 0; j < topk; ++j){
            if(indexes[j] == class) avg_topk += 1;
        }

        printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1));
    }
}

void validate_attention_multi(char *datacfg, char *filename, char *weightfile)
{
    int i, j;
    network *net = load_network(filename, weightfile, 0);
    set_batch_network(net, 1);
    srand(time(0));

    list *options = read_data_cfg(datacfg);

    char *label_list = option_find_str(options, "labels", "data/labels.list");
    char *valid_list = option_find_str(options, "valid", "data/train.list");
    int classes = option_find_int(options, "classes", 2);
    int topk = option_find_int(options, "top", 1);

    char **labels = get_labels(label_list);
    list *plist = get_paths(valid_list);
    int scales[] = {224, 288, 320, 352, 384};
    int nscales = sizeof(scales)/sizeof(scales[0]);

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    float avg_acc = 0;
    float avg_topk = 0;
    int *indexes = calloc(topk, sizeof(int));

    for(i = 0; i < m; ++i){
        int class = -1;
        char *path = paths[i];
        for(j = 0; j < classes; ++j){
            if(strstr(path, labels[j])){
                class = j;
                break;
            }
        }
        float *pred = calloc(classes, sizeof(float));
        image im = load_image_color(paths[i], 0, 0);
        for(j = 0; j < nscales; ++j){
            image r = resize_min(im, scales[j]);
            resize_network(net, r.w, r.h);
            float *p = network_predict(net, r.data);
            if(net->hierarchy) hierarchy_predictions(p, net->outputs, net->hierarchy, 1 , 1);
            axpy_cpu(classes, 1, p, 1, pred, 1);
            flip_image(r);
            p = network_predict(net, r.data);
            axpy_cpu(classes, 1, p, 1, pred, 1);
            if(r.data != im.data) free_image(r);
        }
        free_image(im);
        top_k(pred, classes, topk, indexes);
        free(pred);
        if(indexes[0] == class) avg_acc += 1;
        for(j = 0; j < topk; ++j){
            if(indexes[j] == class) avg_topk += 1;
        }

        printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1));
    }
}

void predict_attention(char *datacfg, char *cfgfile, char *weightfile, char *filename, int top)
{
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    srand(2222222);

    list *options = read_data_cfg(datacfg);

    char *name_list = option_find_str(options, "names", 0);
    if(!name_list) name_list = option_find_str(options, "labels", "data/labels.list");
    if(top == 0) top = option_find_int(options, "top", 1);

    int i = 0;
    char **names = get_labels(name_list);
    clock_t time;
    int *indexes = calloc(top, sizeof(int));
    char buff[256];
    char *input = buff;
    while(1){
        if(filename){
            strncpy(input, filename, 256);
        }else{
            printf("Enter Image Path: ");
            fflush(stdout);
            input = fgets(input, 256, stdin);
            if(!input) return;
            strtok(input, "\n");
        }
        image im = load_image_color(input, 0, 0);
        image r = letterbox_image(im, net->w, net->h);
        //resize_network(&net, r.w, r.h);
        //printf("%d %d\n", r.w, r.h);

        float *X = r.data;
        time=clock();
        float *predictions = network_predict(net, X);
        if(net->hierarchy) hierarchy_predictions(predictions, net->outputs, net->hierarchy, 1, 1);
        top_k(predictions, net->outputs, top, indexes);
        fprintf(stderr, "%s: Predicted in %f seconds.\n", input, sec(clock()-time));
        for(i = 0; i < top; ++i){
            int index = indexes[i];
            //if(net->hierarchy) printf("%d, %s: %f, parent: %s \n",index, names[index], predictions[index], (net->hierarchy->parent[index] >= 0) ? names[net->hierarchy->parent[index]] : "Root");
            //else printf("%s: %f\n",names[index], predictions[index]);
            printf("%5.2f%%: %s\n", predictions[index]*100, names[index]);
        }
        if(r.data != im.data) free_image(r);
        free_image(im);
        if (filename) break;
    }
}


void run_attention(int argc, char **argv)
{
    if(argc < 4){
        fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]);
        return;
    }

    char *gpu_list = find_char_arg(argc, argv, "-gpus", 0);
    int ngpus;
    int *gpus = read_intlist(gpu_list, &ngpus, gpu_index);


    int top = find_int_arg(argc, argv, "-t", 0);
    int clear = find_arg(argc, argv, "-clear");
    char *data = argv[3];
    char *cfg = argv[4];
    char *weights = (argc > 5) ? argv[5] : 0;
    char *filename = (argc > 6) ? argv[6]: 0;
    char *layer_s = (argc > 7) ? argv[7]: 0;
    if(0==strcmp(argv[2], "predict")) predict_attention(data, cfg, weights, filename, top);
    else if(0==strcmp(argv[2], "train")) train_attention(data, cfg, weights, filename, layer_s, gpus, ngpus, clear);
    else if(0==strcmp(argv[2], "valid")) validate_attention_single(data, cfg, weights);
    else if(0==strcmp(argv[2], "validmulti")) validate_attention_multi(data, cfg, weights);
}




================================================
FILE: examples/captcha.c
================================================
#include "darknet.h"

void fix_data_captcha(data d, int mask)
{
    matrix labels = d.y;
    int i, j;
    for(i = 0; i < d.y.rows; ++i){
        for(j = 0; j < d.y.cols; j += 2){
            if (mask){
                if(!labels.vals[i][j]){
                    labels.vals[i][j] = SECRET_NUM;
                    labels.vals[i][j+1] = SECRET_NUM;
                }else if(labels.vals[i][j+1]){
                    labels.vals[i][j] = 0;
                }
            } else{
                if (labels.vals[i][j]) {
                    labels.vals[i][j+1] = 0;
                } else {
                    labels.vals[i][j+1] = 1;
                }
            }
        }
    }
}

void train_captcha(char *cfgfile, char *weightfile)
{
    srand(time(0));
    float avg_loss = -1;
    char *base = basecfg(cfgfile);
    printf("%s\n", base);
    network *net = load_network(cfgfile, weightfile, 0);
    printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
    int imgs = 1024;
    int i = *net->seen/imgs;
    int solved = 1;
    list *plist;
    char **labels = get_labels("/data/captcha/reimgs.labels.list");
    if (solved){
        plist = get_paths("/data/captcha/reimgs.solved.list");
    }else{
        plist = get_paths("/data/captcha/reimgs.raw.list");
    }
    char **paths = (char **)list_to_array(plist);
    printf("%d\n", plist->size);
    clock_t time;
    pthread_t load_thread;
    data train;
    data buffer;

    load_args args = {0};
    args.w = net->w;
    args.h = net->h;
    args.paths = paths;
    args.classes = 26;
    args.n = imgs;
    args.m = plist->size;
    args.labels = labels;
    args.d = &buffer;
    args.type = CLASSIFICATION_DATA;

    load_thread = load_data_in_thread(args);
    while(1){
        ++i;
        time=clock();
        pthread_join(load_thread, 0);
        train = buffer;
        fix_data_captcha(train, solved);

        /*
           image im = float_to_image(256, 256, 3, train.X.vals[114]);
           show_image(im, "training");
           cvWaitKey(0);
         */

        load_thread = load_data_in_thread(args);
        printf("Loaded: %lf seconds\n", sec(clock()-time));
        time=clock();
        float loss = train_network(net, train);
        if(avg_loss == -1) avg_loss = loss;
        avg_loss = avg_loss*.9 + loss*.1;
        printf("%d: %f, %f avg, %lf seconds, %ld images\n", i, loss, avg_loss, sec(clock()-time), *net->seen);
        free_data(train);
        if(i%100==0){
            char buff[256];
            sprintf(buff, "/home/pjreddie/imagenet_backup/%s_%d.weights",base, i);
            save_weights(net, buff);
        }
    }
}

void test_captcha(char *cfgfile, char *weightfile, char *filename)
{
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    srand(2222222);
    int i = 0;
    char **names = get_labels("/data/captcha/reimgs.labels.list");
    char buff[256];
    char *input = buff;
    int indexes[26];
    while(1){
        if(filename){
            strncpy(input, filename, 256);
        }else{
            //printf("Enter Image Path: ");
            //fflush(stdout);
            input = fgets(input, 256, stdin);
            if(!input) return;
            strtok(input, "\n");
        }
        image im = load_image_color(input, net->w, net->h);
        float *X = im.data;
        float *predictions = network_predict(net, X);
        top_predictions(net, 26, indexes);
        //printf("%s: Predicted in %f seconds.\n", input, sec(clock()-time));
        for(i = 0; i < 26; ++i){
            int index = indexes[i];
            if(i != 0) printf(", ");
            printf("%s %f", names[index], predictions[index]);
        }
        printf("\n");
        fflush(stdout);
        free_image(im);
        if (filename) break;
    }
}

void valid_captcha(char *cfgfile, char *weightfile, char *filename)
{
    char **labels = get_labels("/data/captcha/reimgs.labels.list");
    network *net = load_network(cfgfile, weightfile, 0);
    list *plist = get_paths("/data/captcha/reimgs.fg.list");
    char **paths = (char **)list_to_array(plist);
    int N = plist->size;
    int outputs = net->outputs;

    set_batch_network(net, 1);
    srand(2222222);
    int i, j;
    for(i = 0; i < N; ++i){
        if (i%100 == 0) fprintf(stderr, "%d\n", i);
        image im = load_image_color(paths[i], net->w, net->h);
        float *X = im.data;
        float *predictions = network_predict(net, X);
        //printf("%s: Predicted in %f seconds.\n", input, sec(clock()-time));
        int truth = -1;
        for(j = 0; j < 13; ++j){
            if (strstr(paths[i], labels[j])) truth = j;
        }
        if (truth == -1){
            fprintf(stderr, "bad: %s\n", paths[i]);
            return;
        }
        printf("%d, ", truth);
        for(j = 0; j < outputs; ++j){
            if (j != 0) printf(", ");
            printf("%f", predictions[j]);
        }
        printf("\n");
        fflush(stdout);
        free_image(im);
        if (filename) break;
    }
}

/*
   void train_captcha(char *cfgfile, char *weightfile)
   {
   float avg_loss = -1;
   srand(time(0));
   char *base = basecfg(cfgfile);
   printf("%s\n", base);
   network net = parse_network_cfg(cfgfile);
   if(weightfile){
   load_weights(&net, weightfile);
   }
   printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
   int imgs = 1024;
   int i = net->seen/imgs;
   list *plist = get_paths("/data/captcha/train.auto5");
   char **paths = (char **)list_to_array(plist);
   printf("%d\n", plist->size);
   clock_t time;
   while(1){
   ++i;
   time=clock();
   data train = load_data_captcha(paths, imgs, plist->size, 10, 200, 60);
   translate_data_rows(train, -128);
   scale_data_rows(train, 1./128);
   printf("Loaded: %lf seconds\n", sec(clock()-time));
   time=clock();
   float loss = train_network(net, train);
   net->seen += imgs;
   if(avg_loss == -1) avg_loss = loss;
   avg_loss = avg_loss*.9 + loss*.1;
   printf("%d: %f, %f avg, %lf seconds, %d images\n", i, loss, avg_loss, sec(clock()-time), net->seen);
   free_data(train);
   if(i%10==0){
   char buff[256];
   sprintf(buff, "/home/pjreddie/imagenet_backup/%s_%d.weights",base, i);
   save_weights(net, buff);
   }
   }
   }

   void decode_captcha(char *cfgfile, char *weightfile)
   {
   setbuf(stdout, NULL);
   srand(time(0));
   network net = parse_network_cfg(cfgfile);
   set_batch_network(&net, 1);
   if(weightfile){
   load_weights(&net, weightfile);
   }
   char filename[256];
   while(1){
   printf("Enter filename: ");
   fgets(filename, 256, stdin);
   strtok(filename, "\n");
   image im = load_image_color(filename, 300, 57);
   scale_image(im, 1./255.);
   float *X = im.data;
   float *predictions = network_predict(net, X);
   image out  = float_to_image(300, 57, 1, predictions);
   show_image(out, "decoded");
#ifdef OPENCV
cvWaitKey(0);
#endif
free_image(im);
}
}

void encode_captcha(char *cfgfile, char *weightfile)
{
float avg_loss = -1;
srand(time(0));
char *base = basecfg(cfgfile);
printf("%s\n", base);
network net = parse_network_cfg(cfgfile);
if(weightfile){
    load_weights(&net, weightfile);
}
printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
int imgs = 1024;
int i = net->seen/imgs;
list *plist = get_paths("/data/captcha/encode.list");
char **paths = (char **)list_to_array(plist);
printf("%d\n", plist->size);
clock_t time;
while(1){
    ++i;
    time=clock();
    data train = load_data_captcha_encode(paths, imgs, plist->size, 300, 57);
    scale_data_rows(train, 1./255);
    printf("Loaded: %lf seconds\n", sec(clock()-time));
    time=clock();
    float loss = train_network(net, train);
    net->seen += imgs;
    if(avg_loss == -1) avg_loss = loss;
    avg_loss = avg_loss*.9 + loss*.1;
    printf("%d: %f, %f avg, %lf seconds, %d images\n", i, loss, avg_loss, sec(clock()-time), net->seen);
    free_matrix(train.X);
    if(i%100==0){
        char buff[256];
        sprintf(buff, "/home/pjreddie/imagenet_backup/%s_%d.weights",base, i);
        save_weights(net, buff);
    }
}
}

void validate_captcha(char *cfgfile, char *weightfile)
{
    srand(time(0));
    char *base = basecfg(cfgfile);
    printf("%s\n", base);
    network net = parse_network_cfg(cfgfile);
    if(weightfile){
        load_weights(&net, weightfile);
    }
    int numchars = 37;
    list *plist = get_paths("/data/captcha/solved.hard");
    char **paths = (char **)list_to_array(plist);
    int imgs = plist->size;
    data valid = load_data_captcha(paths, imgs, 0, 10, 200, 60);
    translate_data_rows(valid, -128);
    scale_data_rows(valid, 1./128);
    matrix pred = network_predict_data(net, valid);
    int i, k;
    int correct = 0;
    int total = 0;
    int accuracy = 0;
    for(i = 0; i < imgs; ++i){
        int allcorrect = 1;
        for(k = 0; k < 10; ++k){
            char truth = int_to_alphanum(max_index(valid.y.vals[i]+k*numchars, numchars));
            char prediction = int_to_alphanum(max_index(pred.vals[i]+k*numchars, numchars));
            if (truth != prediction) allcorrect=0;
            if (truth != '.' && truth == prediction) ++correct;
            if (truth != '.' || truth != prediction) ++total;
        }
        accuracy += allcorrect;
    }
    printf("Word Accuracy: %f, Char Accuracy %f\n", (float)accuracy/imgs, (float)correct/total);
    free_data(valid);
}

void test_captcha(char *cfgfile, char *weightfile)
{
    setbuf(stdout, NULL);
    srand(time(0));
    //char *base = basecfg(cfgfile);
    //printf("%s\n", base);
    network net = parse_network_cfg(cfgfile);
    set_batch_network(&net, 1);
    if(weightfile){
        load_weights(&net, weightfile);
    }
    char filename[256];
    while(1){
        //printf("Enter filename: ");
        fgets(filename, 256, stdin);
        strtok(filename, "\n");
        image im = load_image_color(filename, 200, 60);
        translate_image(im, -128);
        scale_image(im, 1/128.);
        float *X = im.data;
        float *predictions = network_predict(net, X);
        print_letters(predictions, 10);
        free_image(im);
    }
}
    */
void run_captcha(int argc, char **argv)
{
    if(argc < 4){
        fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]);
        return;
    }

    char *cfg = argv[3];
    char *weights = (argc > 4) ? argv[4] : 0;
    char *filename = (argc > 5) ? argv[5]: 0;
    if(0==strcmp(argv[2], "train")) train_captcha(cfg, weights);
    else if(0==strcmp(argv[2], "test")) test_captcha(cfg, weights, filename);
    else if(0==strcmp(argv[2], "valid")) valid_captcha(cfg, weights, filename);
    //if(0==strcmp(argv[2], "test")) test_captcha(cfg, weights);
    //else if(0==strcmp(argv[2], "encode")) encode_captcha(cfg, weights);
    //else if(0==strcmp(argv[2], "decode")) decode_captcha(cfg, weights);
    //else if(0==strcmp(argv[2], "valid")) validate_captcha(cfg, weights);
}



================================================
FILE: examples/cifar.c
================================================
#include "darknet.h"

void train_cifar(char *cfgfile, char *weightfile)
{
    srand(time(0));
    float avg_loss = -1;
    char *base = basecfg(cfgfile);
    printf("%s\n", base);
    network *net = load_network(cfgfile, weightfile, 0);
    printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);

    char *backup_directory = "/home/pjreddie/backup/";
    int classes = 10;
    int N = 50000;

    char **labels = get_labels("data/cifar/labels.txt");
    int epoch = (*net->seen)/N;
    data train = load_all_cifar10();
    while(get_current_batch(net) < net->max_batches || net->max_batches == 0){
        clock_t time=clock();

        float loss = train_network_sgd(net, train, 1);
        if(avg_loss == -1) avg_loss = loss;
        avg_loss = avg_loss*.95 + loss*.05;
        printf("%ld, %.3f: %f, %f avg, %f rate, %lf seconds, %ld images\n", get_current_batch(net), (float)(*net->seen)/N, loss, avg_loss, get_current_rate(net), sec(clock()-time), *net->seen);
        if(*net->seen/N > epoch){
            epoch = *net->seen/N;
            char buff[256];
            sprintf(buff, "%s/%s_%d.weights",backup_directory,base, epoch);
            save_weights(net, buff);
        }
        if(get_current_batch(net)%100 == 0){
            char buff[256];
            sprintf(buff, "%s/%s.backup",backup_directory,base);
            save_weights(net, buff);
        }
    }
    char buff[256];
    sprintf(buff, "%s/%s.weights", backup_directory, base);
    save_weights(net, buff);

    free_network(net);
    free_ptrs((void**)labels, classes);
    free(base);
    free_data(train);
}

void train_cifar_distill(char *cfgfile, char *weightfile)
{
    srand(time(0));
    float avg_loss = -1;
    char *base = basecfg(cfgfile);
    printf("%s\n", base);
    network *net = load_network(cfgfile, weightfile, 0);
    printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);

    char *backup_directory = "/home/pjreddie/backup/";
    int classes = 10;
    int N = 50000;

    char **labels = get_labels("data/cifar/labels.txt");
    int epoch = (*net->seen)/N;

    data train = load_all_cifar10();
    matrix soft = csv_to_matrix("results/ensemble.csv");

    float weight = .9;
    scale_matrix(soft, weight);
    scale_matrix(train.y, 1. - weight);
    matrix_add_matrix(soft, train.y);

    while(get_current_batch(net) < net->max_batches || net->max_batches == 0){
        clock_t time=clock();

        float loss = train_network_sgd(net, train, 1);
        if(avg_loss == -1) avg_loss = loss;
        avg_loss = avg_loss*.95 + loss*.05;
        printf("%ld, %.3f: %f, %f avg, %f rate, %lf seconds, %ld images\n", get_current_batch(net), (float)(*net->seen)/N, loss, avg_loss, get_current_rate(net), sec(clock()-time), *net->seen);
        if(*net->seen/N > epoch){
            epoch = *net->seen/N;
            char buff[256];
            sprintf(buff, "%s/%s_%d.weights",backup_directory,base, epoch);
            save_weights(net, buff);
        }
        if(get_current_batch(net)%100 == 0){
            char buff[256];
            sprintf(buff, "%s/%s.backup",backup_directory,base);
            save_weights(net, buff);
        }
    }
    char buff[256];
    sprintf(buff, "%s/%s.weights", backup_directory, base);
    save_weights(net, buff);

    free_network(net);
    free_ptrs((void**)labels, classes);
    free(base);
    free_data(train);
}

void test_cifar_multi(char *filename, char *weightfile)
{
    network *net = load_network(filename, weightfile, 0);
    set_batch_network(net, 1);
    srand(time(0));

    float avg_acc = 0;
    data test = load_cifar10_data("data/cifar/cifar-10-batches-bin/test_batch.bin");

    int i;
    for(i = 0; i < test.X.rows; ++i){
        image im = float_to_image(32, 32, 3, test.X.vals[i]);

        float pred[10] = {0};

        float *p = network_predict(net, im.data);
        axpy_cpu(10, 1, p, 1, pred, 1);
        flip_image(im);
        p = network_predict(net, im.data);
        axpy_cpu(10, 1, p, 1, pred, 1);

        int index = max_index(pred, 10);
        int class = max_index(test.y.vals[i], 10);
        if(index == class) avg_acc += 1;
        free_image(im);
        printf("%4d: %.2f%%\n", i, 100.*avg_acc/(i+1));
    }
}

void test_cifar(char *filename, char *weightfile)
{
    network *net = load_network(filename, weightfile, 0);
    srand(time(0));

    clock_t time;
    float avg_acc = 0;
    float avg_top5 = 0;
    data test = load_cifar10_data("data/cifar/cifar-10-batches-bin/test_batch.bin");

    time=clock();

    float *acc = network_accuracies(net, test, 2);
    avg_acc += acc[0];
    avg_top5 += acc[1];
    printf("top1: %f, %lf seconds, %d images\n", avg_acc, sec(clock()-time), test.X.rows);
    free_data(test);
}

void extract_cifar()
{
char *labels[] = {"airplane","automobile","bird","cat","deer","dog","frog","horse","ship","truck"};
    int i;
    data train = load_all_cifar10();
    data test = load_cifar10_data("data/cifar/cifar-10-batches-bin/test_batch.bin");
    for(i = 0; i < train.X.rows; ++i){
        image im = float_to_image(32, 32, 3, train.X.vals[i]);
        int class = max_index(train.y.vals[i], 10);
        char buff[256];
        sprintf(buff, "data/cifar/train/%d_%s",i,labels[class]);
        save_image_png(im, buff);
    }
    for(i = 0; i < test.X.rows; ++i){
        image im = float_to_image(32, 32, 3, test.X.vals[i]);
        int class = max_index(test.y.vals[i], 10);
        char buff[256];
        sprintf(buff, "data/cifar/test/%d_%s",i,labels[class]);
        save_image_png(im, buff);
    }
}

void test_cifar_csv(char *filename, char *weightfile)
{
    network *net = load_network(filename, weightfile, 0);
    srand(time(0));

    data test = load_cifar10_data("data/cifar/cifar-10-batches-bin/test_batch.bin");

    matrix pred = network_predict_data(net, test);

    int i;
    for(i = 0; i < test.X.rows; ++i){
        image im = float_to_image(32, 32, 3, test.X.vals[i]);
        flip_image(im);
    }
    matrix pred2 = network_predict_data(net, test);
    scale_matrix(pred, .5);
    scale_matrix(pred2, .5);
    matrix_add_matrix(pred2, pred);

    matrix_to_csv(pred);
    fprintf(stderr, "Accuracy: %f\n", matrix_topk_accuracy(test.y, pred, 1));
    free_data(test);
}

void test_cifar_csvtrain(char *cfg, char *weights)
{
    network *net = load_network(cfg, weights, 0);
    srand(time(0));

    data test = load_all_cifar10();

    matrix pred = network_predict_data(net, test);

    int i;
    for(i = 0; i < test.X.rows; ++i){
        image im = float_to_image(32, 32, 3, test.X.vals[i]);
        flip_image(im);
    }
    matrix pred2 = network_predict_data(net, test);
    scale_matrix(pred, .5);
    scale_matrix(pred2, .5);
    matrix_add_matrix(pred2, pred);

    matrix_to_csv(pred);
    fprintf(stderr, "Accuracy: %f\n", matrix_topk_accuracy(test.y, pred, 1));
    free_data(test);
}

void eval_cifar_csv()
{
    data test = load_cifar10_data("data/cifar/cifar-10-batches-bin/test_batch.bin");

    matrix pred = csv_to_matrix("results/combined.csv");
    fprintf(stderr, "%d %d\n", pred.rows, pred.cols);

    fprintf(stderr, "Accuracy: %f\n", matrix_topk_accuracy(test.y, pred, 1));
    free_data(test);
    free_matrix(pred);
}


void run_cifar(int argc, char **argv)
{
    if(argc < 4){
        fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]);
        return;
    }

    char *cfg = argv[3];
    char *weights = (argc > 4) ? argv[4] : 0;
    if(0==strcmp(argv[2], "train")) train_cifar(cfg, weights);
    else if(0==strcmp(argv[2], "extract")) extract_cifar();
    else if(0==strcmp(argv[2], "distill")) train_cifar_distill(cfg, weights);
    else if(0==strcmp(argv[2], "test")) test_cifar(cfg, weights);
    else if(0==strcmp(argv[2], "multi")) test_cifar_multi(cfg, weights);
    else if(0==strcmp(argv[2], "csv")) test_cifar_csv(cfg, weights);
    else if(0==strcmp(argv[2], "csvtrain")) test_cifar_csvtrain(cfg, weights);
    else if(0==strcmp(argv[2], "eval")) eval_cifar_csv();
}




================================================
FILE: examples/classifier.c
================================================
#include "darknet.h"

#include <sys/time.h>
#include <assert.h>

float *get_regression_values(char **labels, int n)
{
    float *v = calloc(n, sizeof(float));
    int i;
    for(i = 0; i < n; ++i){
        char *p = strchr(labels[i], ' ');
        *p = 0;
        v[i] = atof(p+1);
    }
    return v;
}

void train_classifier(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear)
{
    int i;

    float avg_loss = -1;
    char *base = basecfg(cfgfile);
    printf("%s\n", base);
    printf("%d\n", ngpus);
    network **nets = calloc(ngpus, sizeof(network*));

    srand(time(0));
    int seed = rand();
    for(i = 0; i < ngpus; ++i){
        srand(seed);
#ifdef GPU
        cuda_set_device(gpus[i]);
#endif
        nets[i] = load_network(cfgfile, weightfile, clear);
        nets[i]->learning_rate *= ngpus;
    }
    srand(time(0));
    network *net = nets[0];

    int imgs = net->batch * net->subdivisions * ngpus;

    printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
    list *options = read_data_cfg(datacfg);

    char *backup_directory = option_find_str(options, "backup", "/backup/");
    char *label_list = option_find_str(options, "labels", "data/labels.list");
    char *train_list = option_find_str(options, "train", "data/train.list");
    int classes = option_find_int(options, "classes", 2);

    char **labels = get_labels(label_list);
    list *plist = get_paths(train_list);
    char **paths = (char **)list_to_array(plist);
    printf("%d\n", plist->size);
    int N = plist->size;
    double time;

    load_args args = {0};
    args.w = net->w;
    args.h = net->h;
    args.threads = 32;
    args.hierarchy = net->hierarchy;

    args.min = net->min_ratio*net->w;
    args.max = net->max_ratio*net->w;
    printf("%d %d\n", args.min, args.max);
    args.angle = net->angle;
    args.aspect = net->aspect;
    args.exposure = net->exposure;
    args.saturation = net->saturation;
    args.hue = net->hue;
    args.size = net->w;

    args.paths = paths;
    args.classes = classes;
    args.n = imgs;
    args.m = N;
    args.labels = labels;
    args.type = CLASSIFICATION_DATA;

    data train;
    data buffer;
    pthread_t load_thread;
    args.d = &buffer;
    load_thread = load_data(args);

    int count = 0;
    int epoch = (*net->seen)/N;
    while(get_current_batch(net) < net->max_batches || net->max_batches == 0){
        if(net->random && count++%40 == 0){
            printf("Resizing\n");
            int dim = (rand() % 11 + 4) * 32;
            //if (get_current_batch(net)+200 > net->max_batches) dim = 608;
            //int dim = (rand() % 4 + 16) * 32;
            printf("%d\n", dim);
            args.w = dim;
            args.h = dim;
            args.size = dim;
            args.min = net->min_ratio*dim;
            args.max = net->max_ratio*dim;
            printf("%d %d\n", args.min, args.max);

            pthread_join(load_thread, 0);
            train = buffer;
            free_data(train);
            load_thread = load_data(args);

            for(i = 0; i < ngpus; ++i){
                resize_network(nets[i], dim, dim);
            }
            net = nets[0];
        }
        time = what_time_is_it_now();

        pthread_join(load_thread, 0);
        train = buffer;
        load_thread = load_data(args);

        printf("Loaded: %lf seconds\n", what_time_is_it_now()-time);
        time = what_time_is_it_now();

        float loss = 0;
#ifdef GPU
        if(ngpus == 1){
            loss = train_network(net, train);
        } else {
            loss = train_networks(nets, ngpus, train, 4);
        }
#else
        loss = train_network(net, train);
#endif
        if(avg_loss == -1) avg_loss = loss;
        avg_loss = avg_loss*.9 + loss*.1;
        printf("%ld, %.3f: %f, %f avg, %f rate, %lf seconds, %ld images\n", get_current_batch(net), (float)(*net->seen)/N, loss, avg_loss, get_current_rate(net), what_time_is_it_now()-time, *net->seen);
        free_data(train);
        if(*net->seen/N > epoch){
            epoch = *net->seen/N;
            char buff[256];
            sprintf(buff, "%s/%s_%d.weights",backup_directory,base, epoch);
            save_weights(net, buff);
        }
        if(get_current_batch(net)%1000 == 0){
            char buff[256];
            sprintf(buff, "%s/%s.backup",backup_directory,base);
            save_weights(net, buff);
        }
    }
    char buff[256];
    sprintf(buff, "%s/%s.weights", backup_directory, base);
    save_weights(net, buff);
    pthread_join(load_thread, 0);

    free_network(net);
    free_ptrs((void**)labels, classes);
    free_ptrs((void**)paths, plist->size);
    free_list(plist);
    free(base);
}

void validate_classifier_crop(char *datacfg, char *filename, char *weightfile)
{
    int i = 0;
    network *net = load_network(filename, weightfile, 0);
    srand(time(0));

    list *options = read_data_cfg(datacfg);

    char *label_list = option_find_str(options, "labels", "data/labels.list");
    char *valid_list = option_find_str(options, "valid", "data/train.list");
    int classes = option_find_int(options, "classes", 2);
    int topk = option_find_int(options, "top", 1);

    char **labels = get_labels(label_list);
    list *plist = get_paths(valid_list);

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    clock_t time;
    float avg_acc = 0;
    float avg_topk = 0;
    int splits = m/1000;
    int num = (i+1)*m/splits - i*m/splits;

    data val, buffer;

    load_args args = {0};
    args.w = net->w;
    args.h = net->h;

    args.paths = paths;
    args.classes = classes;
    args.n = num;
    args.m = 0;
    args.labels = labels;
    args.d = &buffer;
    args.type = OLD_CLASSIFICATION_DATA;

    pthread_t load_thread = load_data_in_thread(args);
    for(i = 1; i <= splits; ++i){
        time=clock();

        pthread_join(load_thread, 0);
        val = buffer;

        num = (i+1)*m/splits - i*m/splits;
        char **part = paths+(i*m/splits);
        if(i != splits){
            args.paths = part;
            load_thread = load_data_in_thread(args);
        }
        printf("Loaded: %d images in %lf seconds\n", val.X.rows, sec(clock()-time));

        time=clock();
        float *acc = network_accuracies(net, val, topk);
        avg_acc += acc[0];
        avg_topk += acc[1];
        printf("%d: top 1: %f, top %d: %f, %lf seconds, %d images\n", i, avg_acc/i, topk, avg_topk/i, sec(clock()-time), val.X.rows);
        free_data(val);
    }
}

void validate_classifier_10(char *datacfg, char *filename, char *weightfile)
{
    int i, j;
    network *net = load_network(filename, weightfile, 0);
    set_batch_network(net, 1);
    srand(time(0));

    list *options = read_data_cfg(datacfg);

    char *label_list = option_find_str(options, "labels", "data/labels.list");
    char *valid_list = option_find_str(options, "valid", "data/train.list");
    int classes = option_find_int(options, "classes", 2);
    int topk = option_find_int(options, "top", 1);

    char **labels = get_labels(label_list);
    list *plist = get_paths(valid_list);

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    float avg_acc = 0;
    float avg_topk = 0;
    int *indexes = calloc(topk, sizeof(int));

    for(i = 0; i < m; ++i){
        int class = -1;
        char *path = paths[i];
        for(j = 0; j < classes; ++j){
            if(strstr(path, labels[j])){
                class = j;
                break;
            }
        }
        int w = net->w;
        int h = net->h;
        int shift = 32;
        image im = load_image_color(paths[i], w+shift, h+shift);
        image images[10];
        images[0] = crop_image(im, -shift, -shift, w, h);
        images[1] = crop_image(im, shift, -shift, w, h);
        images[2] = crop_image(im, 0, 0, w, h);
        images[3] = crop_image(im, -shift, shift, w, h);
        images[4] = crop_image(im, shift, shift, w, h);
        flip_image(im);
        images[5] = crop_image(im, -shift, -shift, w, h);
        images[6] = crop_image(im, shift, -shift, w, h);
        images[7] = crop_image(im, 0, 0, w, h);
        images[8] = crop_image(im, -shift, shift, w, h);
        images[9] = crop_image(im, shift, shift, w, h);
        float *pred = calloc(classes, sizeof(float));
        for(j = 0; j < 10; ++j){
            float *p = network_predict(net, images[j].data);
            if(net->hierarchy) hierarchy_predictions(p, net->outputs, net->hierarchy, 1, 1);
            axpy_cpu(classes, 1, p, 1, pred, 1);
            free_image(images[j]);
        }
        free_image(im);
        top_k(pred, classes, topk, indexes);
        free(pred);
        if(indexes[0] == class) avg_acc += 1;
        for(j = 0; j < topk; ++j){
            if(indexes[j] == class) avg_topk += 1;
        }

        printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1));
    }
}

void validate_classifier_full(char *datacfg, char *filename, char *weightfile)
{
    int i, j;
    network *net = load_network(filename, weightfile, 0);
    set_batch_network(net, 1);
    srand(time(0));

    list *options = read_data_cfg(datacfg);

    char *label_list = option_find_str(options, "labels", "data/labels.list");
    char *valid_list = option_find_str(options, "valid", "data/train.list");
    int classes = option_find_int(options, "classes", 2);
    int topk = option_find_int(options, "top", 1);

    char **labels = get_labels(label_list);
    list *plist = get_paths(valid_list);

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    float avg_acc = 0;
    float avg_topk = 0;
    int *indexes = calloc(topk, sizeof(int));

    int size = net->w;
    for(i = 0; i < m; ++i){
        int class = -1;
        char *path = paths[i];
        for(j = 0; j < classes; ++j){
            if(strstr(path, labels[j])){
                class = j;
                break;
            }
        }
        image im = load_image_color(paths[i], 0, 0);
        image resized = resize_min(im, size);
        resize_network(net, resized.w, resized.h);
        //show_image(im, "orig");
        //show_image(crop, "cropped");
        //cvWaitKey(0);
        float *pred = network_predict(net, resized.data);
        if(net->hierarchy) hierarchy_predictions(pred, net->outputs, net->hierarchy, 1, 1);

        free_image(im);
        free_image(resized);
        top_k(pred, classes, topk, indexes);

        if(indexes[0] == class) avg_acc += 1;
        for(j = 0; j < topk; ++j){
            if(indexes[j] == class) avg_topk += 1;
        }

        printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1));
    }
}


void validate_classifier_single(char *datacfg, char *filename, char *weightfile)
{
    int i, j;
    network *net = load_network(filename, weightfile, 0);
    set_batch_network(net, 1);
    srand(time(0));

    list *options = read_data_cfg(datacfg);

    char *label_list = option_find_str(options, "labels", "data/labels.list");
    char *leaf_list = option_find_str(options, "leaves", 0);
    if(leaf_list) change_leaves(net->hierarchy, leaf_list);
    char *valid_list = option_find_str(options, "valid", "data/train.list");
    int classes = option_find_int(options, "classes", 2);
    int topk = option_find_int(options, "top", 1);

    char **labels = get_labels(label_list);
    list *plist = get_paths(valid_list);

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    float avg_acc = 0;
    float avg_topk = 0;
    int *indexes = calloc(topk, sizeof(int));

    for(i = 0; i < m; ++i){
        int class = -1;
        char *path = paths[i];
        for(j = 0; j < classes; ++j){
            if(strstr(path, labels[j])){
                class = j;
                break;
            }
        }
        image im = load_image_color(paths[i], 0, 0);
        image resized = resize_min(im, net->w);
        image crop = crop_image(resized, (resized.w - net->w)/2, (resized.h - net->h)/2, net->w, net->h);
        //show_image(im, "orig");
        //show_image(crop, "cropped");
        //cvWaitKey(0);
        float *pred = network_predict(net, crop.data);
        if(net->hierarchy) hierarchy_predictions(pred, net->outputs, net->hierarchy, 1, 1);

        if(resized.data != im.data) free_image(resized);
        free_image(im);
        free_image(crop);
        top_k(pred, classes, topk, indexes);

        if(indexes[0] == class) avg_acc += 1;
        for(j = 0; j < topk; ++j){
            if(indexes[j] == class) avg_topk += 1;
        }

        printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1));
    }
}

void validate_classifier_multi(char *datacfg, char *cfg, char *weights)
{
    int i, j;
    network *net = load_network(cfg, weights, 0);
    set_batch_network(net, 1);
    srand(time(0));

    list *options = read_data_cfg(datacfg);

    char *label_list = option_find_str(options, "labels", "data/labels.list");
    char *valid_list = option_find_str(options, "valid", "data/train.list");
    int classes = option_find_int(options, "classes", 2);
    int topk = option_find_int(options, "top", 1);

    char **labels = get_labels(label_list);
    list *plist = get_paths(valid_list);
    //int scales[] = {224, 288, 320, 352, 384};
    int scales[] = {224, 256, 288, 320};
    int nscales = sizeof(scales)/sizeof(scales[0]);

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    float avg_acc = 0;
    float avg_topk = 0;
    int *indexes = calloc(topk, sizeof(int));

    for(i = 0; i < m; ++i){
        int class = -1;
        char *path = paths[i];
        for(j = 0; j < classes; ++j){
            if(strstr(path, labels[j])){
                class = j;
                break;
            }
        }
        float *pred = calloc(classes, sizeof(float));
        image im = load_image_color(paths[i], 0, 0);
        for(j = 0; j < nscales; ++j){
            image r = resize_min(im, scales[j]);
            resize_network(net, r.w, r.h);
            float *p = network_predict(net, r.data);
            if(net->hierarchy) hierarchy_predictions(p, net->outputs, net->hierarchy, 1 , 1);
            axpy_cpu(classes, 1, p, 1, pred, 1);
            flip_image(r);
            p = network_predict(net, r.data);
            axpy_cpu(classes, 1, p, 1, pred, 1);
            if(r.data != im.data) free_image(r);
        }
        free_image(im);
        top_k(pred, classes, topk, indexes);
        free(pred);
        if(indexes[0] == class) avg_acc += 1;
        for(j = 0; j < topk; ++j){
            if(indexes[j] == class) avg_topk += 1;
        }

        printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1));
    }
}

void try_classifier(char *datacfg, char *cfgfile, char *weightfile, char *filename, int layer_num)
{
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    srand(2222222);

    list *options = read_data_cfg(datacfg);

    char *name_list = option_find_str(options, "names", 0);
    if(!name_list) name_list = option_find_str(options, "labels", "data/labels.list");
    int top = option_find_int(options, "top", 1);

    int i = 0;
    char **names = get_labels(name_list);
    clock_t time;
    int *indexes = calloc(top, sizeof(int));
    char buff[256];
    char *input = buff;
    while(1){
        if(filename){
            strncpy(input, filename, 256);
        }else{
            printf("Enter Image Path: ");
            fflush(stdout);
            input = fgets(input, 256, stdin);
            if(!input) return;
            strtok(input, "\n");
        }
        image orig = load_image_color(input, 0, 0);
        image r = resize_min(orig, 256);
        image im = crop_image(r, (r.w - 224 - 1)/2 + 1, (r.h - 224 - 1)/2 + 1, 224, 224);
        float mean[] = {0.48263312050943, 0.45230225481413, 0.40099074308742};
        float std[] = {0.22590347483426, 0.22120921437787, 0.22103996251583};
        float var[3];
        var[0] = std[0]*std[0];
        var[1] = std[1]*std[1];
        var[2] = std[2]*std[2];

        normalize_cpu(im.data, mean, var, 1, 3, im.w*im.h);

        float *X = im.data;
        time=clock();
        float *predictions = network_predict(net, X);

        layer l = net->layers[layer_num];
        for(i = 0; i < l.c; ++i){
            if(l.rolling_mean) printf("%f %f %f\n", l.rolling_mean[i], l.rolling_variance[i], l.scales[i]);
        }
#ifdef GPU
        cuda_pull_array(l.output_gpu, l.output, l.outputs);
#endif
        for(i = 0; i < l.outputs; ++i){
            printf("%f\n", l.output[i]);
        }
        /*

           printf("\n\nWeights\n");
           for(i = 0; i < l.n*l.size*l.size*l.c; ++i){
           printf("%f\n", l.filters[i]);
           }

           printf("\n\nBiases\n");
           for(i = 0; i < l.n; ++i){
           printf("%f\n", l.biases[i]);
           }
         */

        top_predictions(net, top, indexes);
        printf("%s: Predicted in %f seconds.\n", input, sec(clock()-time));
        for(i = 0; i < top; ++i){
            int index = indexes[i];
            printf("%s: %f\n", names[index], predictions[index]);
        }
        free_image(im);
        if (filename) break;
    }
}

void predict_classifier(char *datacfg, char *cfgfile, char *weightfile, char *filename, int top)
{
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    srand(2222222);

    list *options = read_data_cfg(datacfg);

    char *name_list = option_find_str(options, "names", 0);
    if(!name_list) name_list = option_find_str(options, "labels", "data/labels.list");
    if(top == 0) top = option_find_int(options, "top", 1);

    int i = 0;
    char **names = get_labels(name_list);
    clock_t time;
    int *indexes = calloc(top, sizeof(int));
    char buff[256];
    char *input = buff;
    while(1){
        if(filename){
            strncpy(input, filename, 256);
        }else{
            printf("Enter Image Path: ");
            fflush(stdout);
            input = fgets(input, 256, stdin);
            if(!input) return;
            strtok(input, "\n");
        }
        image im = load_image_color(input, 0, 0);
        image r = letterbox_image(im, net->w, net->h);
        //resize_network(net, r.w, r.h);
        //printf("%d %d\n", r.w, r.h);

        float *X = r.data;
        time=clock();
        float *predictions = network_predict(net, X);
        if(net->hierarchy) hierarchy_predictions(predictions, net->outputs, net->hierarchy, 1, 1);
        top_k(predictions, net->outputs, top, indexes);
        fprintf(stderr, "%s: Predicted in %f seconds.\n", input, sec(clock()-time));
        for(i = 0; i < top; ++i){
            int index = indexes[i];
            //if(net->hierarchy) printf("%d, %s: %f, parent: %s \n",index, names[index], predictions[index], (net->hierarchy->parent[index] >= 0) ? names[net->hierarchy->parent[index]] : "Root");
            //else printf("%s: %f\n",names[index], predictions[index]);
            printf("%5.2f%%: %s\n", predictions[index]*100, names[index]);
        }
        if(r.data != im.data) free_image(r);
        free_image(im);
        if (filename) break;
    }
}


void label_classifier(char *datacfg, char *filename, char *weightfile)
{
    int i;
    network *net = load_network(filename, weightfile, 0);
    set_batch_network(net, 1);
    srand(time(0));

    list *options = read_data_cfg(datacfg);

    char *label_list = option_find_str(options, "names", "data/labels.list");
    char *test_list = option_find_str(options, "test", "data/train.list");
    int classes = option_find_int(options, "classes", 2);

    char **labels = get_labels(label_list);
    list *plist = get_paths(test_list);

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    for(i = 0; i < m; ++i){
        image im = load_image_color(paths[i], 0, 0);
        image resized = resize_min(im, net->w);
        image crop = crop_image(resized, (resized.w - net->w)/2, (resized.h - net->h)/2, net->w, net->h);
        float *pred = network_predict(net, crop.data);

        if(resized.data != im.data) free_image(resized);
        free_image(im);
        free_image(crop);
        int ind = max_index(pred, classes);

        printf("%s\n", labels[ind]);
    }
}


void test_classifier(char *datacfg, char *cfgfile, char *weightfile, int target_layer)
{
    int curr = 0;
    network *net = load_network(cfgfile, weightfile, 0);
    srand(time(0));

    list *options = read_data_cfg(datacfg);

    char *test_list = option_find_str(options, "test", "data/test.list");
    int classes = option_find_int(options, "classes", 2);

    list *plist = get_paths(test_list);

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    clock_t time;

    data val, buffer;

    load_args args = {0};
    args.w = net->w;
    args.h = net->h;
    args.paths = paths;
    args.classes = classes;
    args.n = net->batch;
    args.m = 0;
    args.labels = 0;
    args.d = &buffer;
    args.type = OLD_CLASSIFICATION_DATA;

    pthread_t load_thread = load_data_in_thread(args);
    for(curr = net->batch; curr < m; curr += net->batch){
        time=clock();

        pthread_join(load_thread, 0);
        val = buffer;

        if(curr < m){
            args.paths = paths + curr;
            if (curr + net->batch > m) args.n = m - curr;
            load_thread = load_data_in_thread(args);
        }
        fprintf(stderr, "Loaded: %d images in %lf seconds\n", val.X.rows, sec(clock()-time));

        time=clock();
        matrix pred = network_predict_data(net, val);

        int i, j;
        if (target_layer >= 0){
            //layer l = net->layers[target_layer];
        }

        for(i = 0; i < pred.rows; ++i){
            printf("%s", paths[curr-net->batch+i]);
            for(j = 0; j < pred.cols; ++j){
                printf("\t%g", pred.vals[i][j]);
            }
            printf("\n");
        }

        free_matrix(pred);

        fprintf(stderr, "%lf seconds, %d images, %d total\n", sec(clock()-time), val.X.rows, curr);
        free_data(val);
    }
}


void threat_classifier(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename)
{
#ifdef OPENCV
    float threat = 0;
    float roll = .2;

    printf("Classifier Demo\n");
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    list *options = read_data_cfg(datacfg);

    srand(2222222);
    CvCapture * cap;

    if(filename){
        cap = cvCaptureFromFile(filename);
    }else{
        cap = cvCaptureFromCAM(cam_index);
    }

    int top = option_find_int(options, "top", 1);

    char *name_list = option_find_str(options, "names", 0);
    char **names = get_labels(name_list);

    int *indexes = calloc(top, sizeof(int));

    if(!cap) error("Couldn't connect to webcam.\n");
    //cvNamedWindow("Threat", CV_WINDOW_NORMAL); 
    //cvResizeWindow("Threat", 512, 512);
    float fps = 0;
    int i;

    int count = 0;

    while(1){
        ++count;
        struct timeval tval_before, tval_after, tval_result;
        gettimeofday(&tval_before, NULL);

        image in = get_image_from_stream(cap);
        if(!in.data) break;
        image in_s = resize_image(in, net->w, net->h);

        image out = in;
        int x1 = out.w / 20;
        int y1 = out.h / 20;
        int x2 = 2*x1;
        int y2 = out.h - out.h/20;

        int border = .01*out.h;
        int h = y2 - y1 - 2*border;
        int w = x2 - x1 - 2*border;

        float *predictions = network_predict(net, in_s.data);
        float curr_threat = 0;
        if(1){
            curr_threat = predictions[0] * 0 + 
                predictions[1] * .6 + 
                predictions[2];
        } else {
            curr_threat = predictions[218] +
                predictions[539] + 
                predictions[540] + 
                predictions[368] + 
                predictions[369] + 
                predictions[370];
        }
        threat = roll * curr_threat + (1-roll) * threat;

        draw_box_width(out, x2 + border, y1 + .02*h, x2 + .5 * w, y1 + .02*h + border, border, 0,0,0);
        if(threat > .97) {
            draw_box_width(out,  x2 + .5 * w + border,
                    y1 + .02*h - 2*border, 
                    x2 + .5 * w + 6*border, 
                    y1 + .02*h + 3*border, 3*border, 1,0,0);
        }
        draw_box_width(out,  x2 + .5 * w + border,
                y1 + .02*h - 2*border, 
                x2 + .5 * w + 6*border, 
                y1 + .02*h + 3*border, .5*border, 0,0,0);
        draw_box_width(out, x2 + border, y1 + .42*h, x2 + .5 * w, y1 + .42*h + border, border, 0,0,0);
        if(threat > .57) {
            draw_box_width(out,  x2 + .5 * w + border,
                    y1 + .42*h - 2*border, 
                    x2 + .5 * w + 6*border, 
                    y1 + .42*h + 3*border, 3*border, 1,1,0);
        }
        draw_box_width(out,  x2 + .5 * w + border,
                y1 + .42*h - 2*border, 
                x2 + .5 * w + 6*border, 
                y1 + .42*h + 3*border, .5*border, 0,0,0);

        draw_box_width(out, x1, y1, x2, y2, border, 0,0,0);
        for(i = 0; i < threat * h ; ++i){
            float ratio = (float) i / h;
            float r = (ratio < .5) ? (2*(ratio)) : 1;
            float g = (ratio < .5) ? 1 : 1 - 2*(ratio - .5);
            draw_box_width(out, x1 + border, y2 - border - i, x2 - border, y2 - border - i, 1, r, g, 0);
        }
        top_predictions(net, top, indexes);
        char buff[256];
        sprintf(buff, "/home/pjreddie/tmp/threat_%06d", count);
        //save_image(out, buff);

        printf("\033[2J");
        printf("\033[1;1H");
        printf("\nFPS:%.0f\n",fps);

        for(i = 0; i < top; ++i){
            int index = indexes[i];
            printf("%.1f%%: %s\n", predictions[index]*100, names[index]);
        }

        if(1){
            show_image(out, "Threat");
            cvWaitKey(10);
        }
        free_image(in_s);
        free_image(in);

        gettimeofday(&tval_after, NULL);
        timersub(&tval_after, &tval_before, &tval_result);
        float curr = 1000000.f/((long int)tval_result.tv_usec);
        fps = .9*fps + .1*curr;
    }
#endif
}


void gun_classifier(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename)
{
#ifdef OPENCV
    int bad_cats[] = {218, 539, 540, 1213, 1501, 1742, 1911, 2415, 4348, 19223, 368, 369, 370, 1133, 1200, 1306, 2122, 2301, 2537, 2823, 3179, 3596, 3639, 4489, 5107, 5140, 5289, 6240, 6631, 6762, 7048, 7171, 7969, 7984, 7989, 8824, 8927, 9915, 10270, 10448, 13401, 15205, 18358, 18894, 18895, 19249, 19697};

    printf("Classifier Demo\n");
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    list *options = read_data_cfg(datacfg);

    srand(2222222);
    CvCapture * cap;

    if(filename){
        cap = cvCaptureFromFile(filename);
    }else{
        cap = cvCaptureFromCAM(cam_index);
    }

    int top = option_find_int(options, "top", 1);

    char *name_list = option_find_str(options, "names", 0);
    char **names = get_labels(name_list);

    int *indexes = calloc(top, sizeof(int));

    if(!cap) error("Couldn't connect to webcam.\n");
    cvNamedWindow("Threat Detection", CV_WINDOW_NORMAL); 
    cvResizeWindow("Threat Detection", 512, 512);
    float fps = 0;
    int i;

    while(1){
        struct timeval tval_before, tval_after, tval_result;
        gettimeofday(&tval_before, NULL);

        image in = get_image_from_stream(cap);
        image in_s = resize_image(in, net->w, net->h);
        show_image(in, "Threat Detection");

        float *predictions = network_predict(net, in_s.data);
        top_predictions(net, top, indexes);

        printf("\033[2J");
        printf("\033[1;1H");

        int threat = 0;
        for(i = 0; i < sizeof(bad_cats)/sizeof(bad_cats[0]); ++i){
            int index = bad_cats[i];
            if(predictions[index] > .01){
                printf("Threat Detected!\n");
                threat = 1;
                break;
            }
        }
        if(!threat) printf("Scanning...\n");
        for(i = 0; i < sizeof(bad_cats)/sizeof(bad_cats[0]); ++i){
            int index = bad_cats[i];
            if(predictions[index] > .01){
                printf("%s\n", names[index]);
            }
        }

        free_image(in_s);
        free_image(in);

        cvWaitKey(10);

        gettimeofday(&tval_after, NULL);
        timersub(&tval_after, &tval_before, &tval_result);
        float curr = 1000000.f/((long int)tval_result.tv_usec);
        fps = .9*fps + .1*curr;
    }
#endif
}

void demo_classifier(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename)
{
#ifdef OPENCV
    printf("Classifier Demo\n");
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    list *options = read_data_cfg(datacfg);

    srand(2222222);
    CvCapture * cap;

    if(filename){
        cap = cvCaptureFromFile(filename);
    }else{
        cap = cvCaptureFromCAM(cam_index);
    }

    int top = option_find_int(options, "top", 1);

    char *name_list = option_find_str(options, "names", 0);
    char **names = get_labels(name_list);

    int *indexes = calloc(top, sizeof(int));

    if(!cap) error("Couldn't connect to webcam.\n");
    cvNamedWindow("Classifier", CV_WINDOW_NORMAL); 
    cvResizeWindow("Classifier", 512, 512);
    float fps = 0;
    int i;

    while(1){
        struct timeval tval_before, tval_after, tval_result;
        gettimeofday(&tval_before, NULL);

        image in = get_image_from_stream(cap);
        image in_s = resize_image(in, net->w, net->h);
        show_image(in, "Classifier");

        float *predictions = network_predict(net, in_s.data);
        if(net->hierarchy) hierarchy_predictions(predictions, net->outputs, net->hierarchy, 1, 1);
        top_predictions(net, top, indexes);

        printf("\033[2J");
        printf("\033[1;1H");
        printf("\nFPS:%.0f\n",fps);

        for(i = 0; i < top; ++i){
            int index = indexes[i];
            printf("%.1f%%: %s\n", predictions[index]*100, names[index]);
        }

        free_image(in_s);
        free_image(in);

        cvWaitKey(10);

        gettimeofday(&tval_after, NULL);
        timersub(&tval_after, &tval_before, &tval_result);
        float curr = 1000000.f/((long int)tval_result.tv_usec);
        fps = .9*fps + .1*curr;
    }
#endif
}


void run_classifier(int argc, char **argv)
{
    if(argc < 4){
        fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]);
        return;
    }

    char *gpu_list = find_char_arg(argc, argv, "-gpus", 0);
    int ngpus;
    int *gpus = read_intlist(gpu_list, &ngpus, gpu_index);


    int cam_index = find_int_arg(argc, argv, "-c", 0);
    int top = find_int_arg(argc, argv, "-t", 0);
    int clear = find_arg(argc, argv, "-clear");
    char *data = argv[3];
    char *cfg = argv[4];
    char *weights = (argc > 5) ? argv[5] : 0;
    char *filename = (argc > 6) ? argv[6]: 0;
    char *layer_s = (argc > 7) ? argv[7]: 0;
    int layer = layer_s ? atoi(layer_s) : -1;
    if(0==strcmp(argv[2], "predict")) predict_classifier(data, cfg, weights, filename, top);
    else if(0==strcmp(argv[2], "try")) try_classifier(data, cfg, weights, filename, atoi(layer_s));
    else if(0==strcmp(argv[2], "train")) train_classifier(data, cfg, weights, gpus, ngpus, clear);
    else if(0==strcmp(argv[2], "demo")) demo_classifier(data, cfg, weights, cam_index, filename);
    else if(0==strcmp(argv[2], "gun")) gun_classifier(data, cfg, weights, cam_index, filename);
    else if(0==strcmp(argv[2], "threat")) threat_classifier(data, cfg, weights, cam_index, filename);
    else if(0==strcmp(argv[2], "test")) test_classifier(data, cfg, weights, layer);
    else if(0==strcmp(argv[2], "label")) label_classifier(data, cfg, weights);
    else if(0==strcmp(argv[2], "valid")) validate_classifier_single(data, cfg, weights);
    else if(0==strcmp(argv[2], "validmulti")) validate_classifier_multi(data, cfg, weights);
    else if(0==strcmp(argv[2], "valid10")) validate_classifier_10(data, cfg, weights);
    else if(0==strcmp(argv[2], "validcrop")) validate_classifier_crop(data, cfg, weights);
    else if(0==strcmp(argv[2], "validfull")) validate_classifier_full(data, cfg, weights);
}




================================================
FILE: examples/coco.c
================================================
#include "darknet.h"

#include <stdio.h>

char *coco_classes[] = {"person","bicycle","car","motorcycle","airplane","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","couch","potted plant","bed","dining table","toilet","tv","laptop","mouse","remote","keyboard","cell phone","microwave","oven","toaster","sink","refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"};

int coco_ids[] = {1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,67,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90};

void train_coco(char *cfgfile, char *weightfile)
{
    //char *train_images = "/home/pjreddie/data/voc/test/train.txt";
    //char *train_images = "/home/pjreddie/data/coco/train.txt";
    char *train_images = "data/coco.trainval.txt";
    //char *train_images = "data/bags.train.list";
    char *backup_directory = "/home/pjreddie/backup/";
    srand(time(0));
    char *base = basecfg(cfgfile);
    printf("%s\n", base);
    float avg_loss = -1;
    network *net = load_network(cfgfile, weightfile, 0);
    printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
    int imgs = net->batch*net->subdivisions;
    int i = *net->seen/imgs;
    data train, buffer;


    layer l = net->layers[net->n - 1];

    int side = l.side;
    int classes = l.classes;
    float jitter = l.jitter;

    list *plist = get_paths(train_images);
    //int N = plist->size;
    char **paths = (char **)list_to_array(plist);

    load_args args = {0};
    args.w = net->w;
    args.h = net->h;
    args.paths = paths;
    args.n = imgs;
    args.m = plist->size;
    args.classes = classes;
    args.jitter = jitter;
    args.num_boxes = side;
    args.d = &buffer;
    args.type = REGION_DATA;

    args.angle = net->angle;
    args.exposure = net->exposure;
    args.saturation = net->saturation;
    args.hue = net->hue;

    pthread_t load_thread = load_data_in_thread(args);
    clock_t time;
    //while(i*imgs < N*120){
    while(get_current_batch(net) < net->max_batches){
        i += 1;
        time=clock();
        pthread_join(load_thread, 0);
        train = buffer;
        load_thread = load_data_in_thread(args);

        printf("Loaded: %lf seconds\n", sec(clock()-time));

        /*
           image im = float_to_image(net->w, net->h, 3, train.X.vals[113]);
           image copy = copy_image(im);
           draw_coco(copy, train.y.vals[113], 7, "truth");
           cvWaitKey(0);
           free_image(copy);
         */

        time=clock();
        float loss = train_network(net, train);
        if (avg_loss < 0) avg_loss = loss;
        avg_loss = avg_loss*.9 + loss*.1;

        printf("%d: %f, %f avg, %f rate, %lf seconds, %d images\n", i, loss, avg_loss, get_current_rate(net), sec(clock()-time), i*imgs);
        if(i%1000==0 || (i < 1000 && i%100 == 0)){
            char buff[256];
            sprintf(buff, "%s/%s_%d.weights", backup_directory, base, i);
            save_weights(net, buff);
        }
        if(i%100==0){
            char buff[256];
            sprintf(buff, "%s/%s.backup", backup_directory, base);
            save_weights(net, buff);
        }
        free_data(train);
    }
    char buff[256];
    sprintf(buff, "%s/%s_final.weights", backup_directory, base);
    save_weights(net, buff);
}

void print_cocos(FILE *fp, int image_id, box *boxes, float **probs, int num_boxes, int classes, int w, int h)
{
    int i, j;
    for(i = 0; i < num_boxes; ++i){
        float xmin = boxes[i].x - boxes[i].w/2.;
        float xmax = boxes[i].x + boxes[i].w/2.;
        float ymin = boxes[i].y - boxes[i].h/2.;
        float ymax = boxes[i].y + boxes[i].h/2.;

        if (xmin < 0) xmin = 0;
        if (ymin < 0) ymin = 0;
        if (xmax > w) xmax = w;
        if (ymax > h) ymax = h;

        float bx = xmin;
        float by = ymin;
        float bw = xmax - xmin;
        float bh = ymax - ymin;

        for(j = 0; j < classes; ++j){
            if (probs[i][j]) fprintf(fp, "{\"image_id\":%d, \"category_id\":%d, \"bbox\":[%f, %f, %f, %f], \"score\":%f},\n", image_id, coco_ids[j], bx, by, bw, bh, probs[i][j]);
        }
    }
}

int get_coco_image_id(char *filename)
{
    char *p = strrchr(filename, '_');
    return atoi(p+1);
}

void validate_coco(char *cfg, char *weights)
{
    network *net = load_network(cfg, weights, 0);
    set_batch_network(net, 1);
    fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
    srand(time(0));

    char *base = "results/";
    list *plist = get_paths("data/coco_val_5k.list");
    //list *plist = get_paths("/home/pjreddie/data/people-art/test.txt");
    //list *plist = get_paths("/home/pjreddie/data/voc/test/2007_test.txt");
    char **paths = (char **)list_to_array(plist);

    layer l = net->layers[net->n-1];
    int classes = l.classes;
    int side = l.side;

    int j;
    char buff[1024];
    snprintf(buff, 1024, "%s/coco_results.json", base);
    FILE *fp = fopen(buff, "w");
    fprintf(fp, "[\n");

    box *boxes = calloc(side*side*l.n, sizeof(box));
    float **probs = calloc(side*side*l.n, sizeof(float *));
    for(j = 0; j < side*side*l.n; ++j) probs[j] = calloc(classes, sizeof(float *));

    int m = plist->size;
    int i=0;
    int t;

    float thresh = .01;
    int nms = 1;
    float iou_thresh = .5;

    int nthreads = 8;
    image *val = calloc(nthreads, sizeof(image));
    image *val_resized = calloc(nthreads, sizeof(image));
    image *buf = calloc(nthreads, sizeof(image));
    image *buf_resized = calloc(nthreads, sizeof(image));
    pthread_t *thr = calloc(nthreads, sizeof(pthread_t));

    load_args args = {0};
    args.w = net->w;
    args.h = net->h;
    args.type = IMAGE_DATA;

    for(t = 0; t < nthreads; ++t){
        args.path = paths[i+t];
        args.im = &buf[t];
        args.resized = &buf_resized[t];
        thr[t] = load_data_in_thread(args);
    }
    time_t start = time(0);
    for(i = nthreads; i < m+nthreads; i += nthreads){
        fprintf(stderr, "%d\n", i);
        for(t = 0; t < nthreads && i+t-nthreads < m; ++t){
            pthread_join(thr[t], 0);
            val[t] = buf[t];
            val_resized[t] = buf_resized[t];
        }
        for(t = 0; t < nthreads && i+t < m; ++t){
            args.path = paths[i+t];
            args.im = &buf[t];
            args.resized = &buf_resized[t];
            thr[t] = load_data_in_thread(args);
        }
        for(t = 0; t < nthreads && i+t-nthreads < m; ++t){
            char *path = paths[i+t-nthreads];
            int image_id = get_coco_image_id(path);
            float *X = val_resized[t].data;
            network_predict(net, X);
            int w = val[t].w;
            int h = val[t].h;
            get_detection_boxes(l, w, h, thresh, probs, boxes, 0);
            if (nms) do_nms_sort(boxes, probs, side*side*l.n, classes, iou_thresh);
            print_cocos(fp, image_id, boxes, probs, side*side*l.n, classes, w, h);
            free_image(val[t]);
            free_image(val_resized[t]);
        }
    }
    fseek(fp, -2, SEEK_CUR); 
    fprintf(fp, "\n]\n");
    fclose(fp);

    fprintf(stderr, "Total Detection Time: %f Seconds\n", (double)(time(0) - start));
}

void validate_coco_recall(char *cfgfile, char *weightfile)
{
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
    srand(time(0));

    char *base = "results/comp4_det_test_";
    list *plist = get_paths("/home/pjreddie/data/voc/test/2007_test.txt");
    char **paths = (char **)list_to_array(plist);

    layer l = net->layers[net->n-1];
    int classes = l.classes;
    int side = l.side;

    int j, k;
    FILE **fps = calloc(classes, sizeof(FILE *));
    for(j = 0; j < classes; ++j){
        char buff[1024];
        snprintf(buff, 1024, "%s%s.txt", base, coco_classes[j]);
        fps[j] = fopen(buff, "w");
    }
    box *boxes = calloc(side*side*l.n, sizeof(box));
    float **probs = calloc(side*side*l.n, sizeof(float *));
    for(j = 0; j < side*side*l.n; ++j) probs[j] = calloc(classes, sizeof(float *));

    int m = plist->size;
    int i=0;

    float thresh = .001;
    int nms = 0;
    float iou_thresh = .5;
    float nms_thresh = .5;

    int total = 0;
    int correct = 0;
    int proposals = 0;
    float avg_iou = 0;

    for(i = 0; i < m; ++i){
        char *path = paths[i];
        image orig = load_image_color(path, 0, 0);
        image sized = resize_image(orig, net->w, net->h);
        char *id = basecfg(path);
        network_predict(net, sized.data);
        get_detection_boxes(l, 1, 1, thresh, probs, boxes, 1);
        if (nms) do_nms(boxes, probs, side*side*l.n, 1, nms_thresh);

        char labelpath[4096];
        find_replace(path, "images", "labels", labelpath);
        find_replace(labelpath, "JPEGImages", "labels", labelpath);
        find_replace(labelpath, ".jpg", ".txt", labelpath);
        find_replace(labelpath, ".JPEG", ".txt", labelpath);

        int num_labels = 0;
        box_label *truth = read_boxes(labelpath, &num_labels);
        for(k = 0; k < side*side*l.n; ++k){
            if(probs[k][0] > thresh){
                ++proposals;
            }
        }
        for (j = 0; j < num_labels; ++j) {
            ++total;
            box t = {truth[j].x, truth[j].y, truth[j].w, truth[j].h};
            float best_iou = 0;
            for(k = 0; k < side*side*l.n; ++k){
                float iou = box_iou(boxes[k], t);
                if(probs[k][0] > thresh && iou > best_iou){
                    best_iou = iou;
                }
            }
            avg_iou += best_iou;
            if(best_iou > iou_thresh){
                ++correct;
            }
        }

        fprintf(stderr, "%5d %5d %5d\tRPs/Img: %.2f\tIOU: %.2f%%\tRecall:%.2f%%\n", i, correct, total, (float)proposals/(i+1), avg_iou*100/total, 100.*correct/total);
        free(id);
        free_image(orig);
        free_image(sized);
    }
}

void test_coco(char *cfgfile, char *weightfile, char *filename, float thresh)
{
    image **alphabet = load_alphabet();
    network *net = load_network(cfgfile, weightfile, 0);
    layer l = net->layers[net->n-1];
    set_batch_network(net, 1);
    srand(2222222);
    float nms = .4;
    clock_t time;
    char buff[256];
    char *input = buff;
    int j;
    box *boxes = calloc(l.side*l.side*l.n, sizeof(box));
    float **probs = calloc(l.side*l.side*l.n, sizeof(float *));
    for(j = 0; j < l.side*l.side*l.n; ++j) probs[j] = calloc(l.classes, sizeof(float *));
    while(1){
        if(filename){
            strncpy(input, filename, 256);
        } else {
            printf("Enter Image Path: ");
            fflush(stdout);
            input = fgets(input, 256, stdin);
            if(!input) return;
            strtok(input, "\n");
        }
        image im = load_image_color(input,0,0);
        image sized = resize_image(im, net->w, net->h);
        float *X = sized.data;
        time=clock();
        network_predict(net, X);
        printf("%s: Predicted in %f seconds.\n", input, sec(clock()-time));
        get_detection_boxes(l, 1, 1, thresh, probs, boxes, 0);
        if (nms) do_nms_sort(boxes, probs, l.side*l.side*l.n, l.classes, nms);
        draw_detections(im, l.side*l.side*l.n, thresh, boxes, probs, 0, coco_classes, alphabet, 80);
        save_image(im, "prediction");
        show_image(im, "predictions");
        free_image(im);
        free_image(sized);
#ifdef OPENCV
        cvWaitKey(0);
        cvDestroyAllWindows();
#endif
        if (filename) break;
    }
}

void run_coco(int argc, char **argv)
{
    char *prefix = find_char_arg(argc, argv, "-prefix", 0);
    float thresh = find_float_arg(argc, argv, "-thresh", .2);
    int cam_index = find_int_arg(argc, argv, "-c", 0);
    int frame_skip = find_int_arg(argc, argv, "-s", 0);

    if(argc < 4){
        fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]);
        return;
    }

    char *cfg = argv[3];
    char *weights = (argc > 4) ? argv[4] : 0;
    char *filename = (argc > 5) ? argv[5]: 0;
    int avg = find_int_arg(argc, argv, "-avg", 1);
    if(0==strcmp(argv[2], "test")) test_coco(cfg, weights, filename, thresh);
    else if(0==strcmp(argv[2], "train")) train_coco(cfg, weights);
    else if(0==strcmp(argv[2], "valid")) validate_coco(cfg, weights);
    else if(0==strcmp(argv[2], "recall")) validate_coco_recall(cfg, weights);
    else if(0==strcmp(argv[2], "demo")) demo(cfg, weights, thresh, cam_index, filename, coco_classes, 80, frame_skip, prefix, avg, .5, 0,0,0,0);
}


================================================
FILE: examples/darknet.c
================================================
#include "darknet.h"

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

extern void predict_classifier(char *datacfg, char *cfgfile, char *weightfile, char *filename, int top);
extern void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh, float hier_thresh, char *outfile, int fullscreen);
extern void run_yolo(int argc, char **argv);
extern void run_detector(int argc, char **argv);
extern void run_coco(int argc, char **argv);
extern void run_captcha(int argc, char **argv);
extern void run_nightmare(int argc, char **argv);
extern void run_classifier(int argc, char **argv);
extern void run_regressor(int argc, char **argv);
extern void run_segmenter(int argc, char **argv);
extern void run_char_rnn(int argc, char **argv);
extern void run_tag(int argc, char **argv);
extern void run_cifar(int argc, char **argv);
extern void run_go(int argc, char **argv);
extern void run_art(int argc, char **argv);
extern void run_super(int argc, char **argv);
extern void run_lsd(int argc, char **argv);

void average(int argc, char *argv[])
{
    char *cfgfile = argv[2];
    char *outfile = argv[3];
    gpu_index = -1;
    network *net = parse_network_cfg(cfgfile);
    network *sum = parse_network_cfg(cfgfile);

    char *weightfile = argv[4];   
    load_weights(sum, weightfile);

    int i, j;
    int n = argc - 5;
    for(i = 0; i < n; ++i){
        weightfile = argv[i+5];   
        load_weights(net, weightfile);
        for(j = 0; j < net->n; ++j){
            layer l = net->layers[j];
            layer out = sum->layers[j];
            if(l.type == CONVOLUTIONAL){
                int num = l.n*l.c*l.size*l.size;
                axpy_cpu(l.n, 1, l.biases, 1, out.biases, 1);
                axpy_cpu(num, 1, l.weights, 1, out.weights, 1);
                if(l.batch_normalize){
                    axpy_cpu(l.n, 1, l.scales, 1, out.scales, 1);
                    axpy_cpu(l.n, 1, l.rolling_mean, 1, out.rolling_mean, 1);
                    axpy_cpu(l.n, 1, l.rolling_variance, 1, out.rolling_variance, 1);
                }
            }
            if(l.type == CONNECTED){
                axpy_cpu(l.outputs, 1, l.biases, 1, out.biases, 1);
                axpy_cpu(l.outputs*l.inputs, 1, l.weights, 1, out.weights, 1);
            }
        }
    }
    n = n+1;
    for(j = 0; j < net->n; ++j){
        layer l = sum->layers[j];
        if(l.type == CONVOLUTIONAL){
            int num = l.n*l.c*l.size*l.size;
            scal_cpu(l.n, 1./n, l.biases, 1);
            scal_cpu(num, 1./n, l.weights, 1);
                if(l.batch_normalize){
                    scal_cpu(l.n, 1./n, l.scales, 1);
                    scal_cpu(l.n, 1./n, l.rolling_mean, 1);
                    scal_cpu(l.n, 1./n, l.rolling_variance, 1);
                }
        }
        if(l.type == CONNECTED){
            scal_cpu(l.outputs, 1./n, l.biases, 1);
            scal_cpu(l.outputs*l.inputs, 1./n, l.weights, 1);
        }
    }
    save_weights(sum, outfile);
}

long numops(network *net)
{
    int i;
    long ops = 0;
    for(i = 0; i < net->n; ++i){
        layer l = net->layers[i];
        if(l.type == CONVOLUTIONAL){
            ops += 2l * l.n * l.size*l.size*l.c/l.groups * l.out_h*l.out_w;
        } else if(l.type == CONNECTED){
            ops += 2l * l.inputs * l.outputs;
        } else if (l.type == RNN){
            ops += 2l * l.input_layer->inputs * l.input_layer->outputs;
            ops += 2l * l.self_layer->inputs * l.self_layer->outputs;
            ops += 2l * l.output_layer->inputs * l.output_layer->outputs;
        } else if (l.type == GRU){
            ops += 2l * l.uz->inputs * l.uz->outputs;
            ops += 2l * l.uh->inputs * l.uh->outputs;
            ops += 2l * l.ur->inputs * l.ur->outputs;
            ops += 2l * l.wz->inputs * l.wz->outputs;
            ops += 2l * l.wh->inputs * l.wh->outputs;
            ops += 2l * l.wr->inputs * l.wr->outputs;
        } else if (l.type == LSTM){
            ops += 2l * l.uf->inputs * l.uf->outputs;
            ops += 2l * l.ui->inputs * l.ui->outputs;
            ops += 2l * l.ug->inputs * l.ug->outputs;
            ops += 2l * l.uo->inputs * l.uo->outputs;
            ops += 2l * l.wf->inputs * l.wf->outputs;
            ops += 2l * l.wi->inputs * l.wi->outputs;
            ops += 2l * l.wg->inputs * l.wg->outputs;
            ops += 2l * l.wo->inputs * l.wo->outputs;
        }
    }
    return ops;
}

void speed(char *cfgfile, int tics)
{
    if (tics == 0) tics = 1000;
    network *net = parse_network_cfg(cfgfile);
    set_batch_network(net, 1);
    int i;
    double time=what_time_is_it_now();
    image im = make_image(net->w, net->h, net->c*net->batch);
    for(i = 0; i < tics; ++i){
        network_predict(net, im.data);
    }
    double t = what_time_is_it_now() - time;
    long ops = numops(net);
    printf("\n%d evals, %f Seconds\n", tics, t);
    printf("Floating Point Operations: %.2f Bn\n", (float)ops/1000000000.);
    printf("FLOPS: %.2f Bn\n", (float)ops/1000000000.*tics/t);
    printf("Speed: %f sec/eval\n", t/tics);
    printf("Speed: %f Hz\n", tics/t);
}

void operations(char *cfgfile)
{
    gpu_index = -1;
    network *net = parse_network_cfg(cfgfile);
    long ops = numops(net);
    printf("Floating Point Operations: %ld\n", ops);
    printf("Floating Point Operations: %.2f Bn\n", (float)ops/1000000000.);
}

void oneoff(char *cfgfile, char *weightfile, char *outfile)
{
    gpu_index = -1;
    network *net = parse_network_cfg(cfgfile);
    int oldn = net->layers[net->n - 2].n;
    int c = net->layers[net->n - 2].c;
    scal_cpu(oldn*c, .1, net->layers[net->n - 2].weights, 1);
    scal_cpu(oldn, 0, net->layers[net->n - 2].biases, 1);
    net->layers[net->n - 2].n = 11921;
    net->layers[net->n - 2].biases += 5;
    net->layers[net->n - 2].weights += 5*c;
    if(weightfile){
        load_weights(net, weightfile);
    }
    net->layers[net->n - 2].biases -= 5;
    net->layers[net->n - 2].weights -= 5*c;
    net->layers[net->n - 2].n = oldn;
    printf("%d\n", oldn);
    layer l = net->layers[net->n - 2];
    copy_cpu(l.n/3, l.biases, 1, l.biases +   l.n/3, 1);
    copy_cpu(l.n/3, l.biases, 1, l.biases + 2*l.n/3, 1);
    copy_cpu(l.n/3*l.c, l.weights, 1, l.weights +   l.n/3*l.c, 1);
    copy_cpu(l.n/3*l.c, l.weights, 1, l.weights + 2*l.n/3*l.c, 1);
    *net->seen = 0;
    save_weights(net, outfile);
}

void oneoff2(char *cfgfile, char *weightfile, char *outfile, int l)
{
    gpu_index = -1;
    network *net = parse_network_cfg(cfgfile);
    if(weightfile){
        load_weights_upto(net, weightfile, 0, net->n);
        load_weights_upto(net, weightfile, l, net->n);
    }
    *net->seen = 0;
    save_weights_upto(net, outfile, net->n);
}

void partial(char *cfgfile, char *weightfile, char *outfile, int max)
{
    gpu_index = -1;
    network *net = load_network(cfgfile, weightfile, 1);
    save_weights_upto(net, outfile, max);
}

void rescale_net(char *cfgfile, char *weightfile, char *outfile)
{
    gpu_index = -1;
    network *net = load_network(cfgfile, weightfile, 0);
    int i;
    for(i = 0; i < net->n; ++i){
        layer l = net->layers[i];
        if(l.type == CONVOLUTIONAL){
            rescale_weights(l, 2, -.5);
            break;
        }
    }
    save_weights(net, outfile);
}

void rgbgr_net(char *cfgfile, char *weightfile, char *outfile)
{
    gpu_index = -1;
    network *net = load_network(cfgfile, weightfile, 0);
    int i;
    for(i = 0; i < net->n; ++i){
        layer l = net->layers[i];
        if(l.type == CONVOLUTIONAL){
            rgbgr_weights(l);
            break;
        }
    }
    save_weights(net, outfile);
}

void reset_normalize_net(char *cfgfile, char *weightfile, char *outfile)
{
    gpu_index = -1;
    network *net = load_network(cfgfile, weightfile, 0);
    int i;
    for (i = 0; i < net->n; ++i) {
        layer l = net->layers[i];
        if (l.type == CONVOLUTIONAL && l.batch_normalize) {
            denormalize_convolutional_layer(l);
        }
        if (l.type == CONNECTED && l.batch_normalize) {
            denormalize_connected_layer(l);
        }
        if (l.type == GRU && l.batch_normalize) {
            denormalize_connected_layer(*l.input_z_layer);
            denormalize_connected_layer(*l.input_r_layer);
            denormalize_connected_layer(*l.input_h_layer);
            denormalize_connected_layer(*l.state_z_layer);
            denormalize_connected_layer(*l.state_r_layer);
            denormalize_connected_layer(*l.state_h_layer);
        }
    }
    save_weights(net, outfile);
}

layer normalize_layer(layer l, int n)
{
    int j;
    l.batch_normalize=1;
    l.scales = calloc(n, sizeof(float));
    for(j = 0; j < n; ++j){
        l.scales[j] = 1;
    }
    l.rolling_mean = calloc(n, sizeof(float));
    l.rolling_variance = calloc(n, sizeof(float));
    return l;
}

void normalize_net(char *cfgfile, char *weightfile, char *outfile)
{
    gpu_index = -1;
    network *net = load_network(cfgfile, weightfile, 0);
    int i;
    for(i = 0; i < net->n; ++i){
        layer l = net->layers[i];
        if(l.type == CONVOLUTIONAL && !l.batch_normalize){
            net->layers[i] = normalize_layer(l, l.n);
        }
        if (l.type == CONNECTED && !l.batch_normalize) {
            net->layers[i] = normalize_layer(l, l.outputs);
        }
        if (l.type == GRU && l.batch_normalize) {
            *l.input_z_layer = normalize_layer(*l.input_z_layer, l.input_z_layer->outputs);
            *l.input_r_layer = normalize_layer(*l.input_r_layer, l.input_r_layer->outputs);
            *l.input_h_layer = normalize_layer(*l.input_h_layer, l.input_h_layer->outputs);
            *l.state_z_layer = normalize_layer(*l.state_z_layer, l.state_z_layer->outputs);
            *l.state_r_layer = normalize_layer(*l.state_r_layer, l.state_r_layer->outputs);
            *l.state_h_layer = normalize_layer(*l.state_h_layer, l.state_h_layer->outputs);
            net->layers[i].batch_normalize=1;
        }
    }
    save_weights(net, outfile);
}

void statistics_net(char *cfgfile, char *weightfile)
{
    gpu_index = -1;
    network *net = load_network(cfgfile, weightfile, 0);
    int i;
    for (i = 0; i < net->n; ++i) {
        layer l = net->layers[i];
        if (l.type == CONNECTED && l.batch_normalize) {
            printf("Connected Layer %d\n", i);
            statistics_connected_layer(l);
        }
        if (l.type == GRU && l.batch_normalize) {
            printf("GRU Layer %d\n", i);
            printf("Input Z\n");
            statistics_connected_layer(*l.input_z_layer);
            printf("Input R\n");
            statistics_connected_layer(*l.input_r_layer);
            printf("Input H\n");
            statistics_connected_layer(*l.input_h_layer);
            printf("State Z\n");
            statistics_connected_layer(*l.state_z_layer);
            printf("State R\n");
            statistics_connected_layer(*l.state_r_layer);
            printf("State H\n");
            statistics_connected_layer(*l.state_h_layer);
        }
        printf("\n");
    }
}

void denormalize_net(char *cfgfile, char *weightfile, char *outfile)
{
    gpu_index = -1;
    network *net = load_network(cfgfile, weightfile, 0);
    int i;
    for (i = 0; i < net->n; ++i) {
        layer l = net->layers[i];
        if ((l.type == DECONVOLUTIONAL || l.type == CONVOLUTIONAL) && l.batch_normalize) {
            denormalize_convolutional_layer(l);
            net->layers[i].batch_normalize=0;
        }
        if (l.type == CONNECTED && l.batch_normalize) {
            denormalize_connected_layer(l);
            net->layers[i].batch_normalize=0;
        }
        if (l.type == GRU && l.batch_normalize) {
            denormalize_connected_layer(*l.input_z_layer);
            denormalize_connected_layer(*l.input_r_layer);
            denormalize_connected_layer(*l.input_h_layer);
            denormalize_connected_layer(*l.state_z_layer);
            denormalize_connected_layer(*l.state_r_layer);
            denormalize_connected_layer(*l.state_h_layer);
            l.input_z_layer->batch_normalize = 0;
            l.input_r_layer->batch_normalize = 0;
            l.input_h_layer->batch_normalize = 0;
            l.state_z_layer->batch_normalize = 0;
            l.state_r_layer->batch_normalize = 0;
            l.state_h_layer->batch_normalize = 0;
            net->layers[i].batch_normalize=0;
        }
    }
    save_weights(net, outfile);
}

void mkimg(char *cfgfile, char *weightfile, int h, int w, int num, char *prefix)
{
    network *net = load_network(cfgfile, weightfile, 0);
    image *ims = get_weights(net->layers[0]);
    int n = net->layers[0].n;
    int z;
    for(z = 0; z < num; ++z){
        image im = make_image(h, w, 3);
        fill_image(im, .5);
        int i;
        for(i = 0; i < 100; ++i){
            image r = copy_image(ims[rand()%n]);
            rotate_image_cw(r, rand()%4);
            random_distort_image(r, 1, 1.5, 1.5);
            int dx = rand()%(w-r.w);
            int dy = rand()%(h-r.h);
            ghost_image(r, im, dx, dy);
            free_image(r);
        }
        char buff[256];
        sprintf(buff, "%s/gen_%d", prefix, z);
        save_image(im, buff);
        free_image(im);
    }
}

void visualize(char *cfgfile, char *weightfile)
{
    network *net = load_network(cfgfile, weightfile, 0);
    visualize_network(net);
#ifdef OPENCV
    cvWaitKey(0);
#endif
}

int main(int argc, char **argv)
{
    //test_resize("data/bad.jpg");
    //test_box();
    //test_convolutional_layer();
    if(argc < 2){
        fprintf(stderr, "usage: %s <function>\n", argv[0]);
        return 0;
    }
    gpu_index = find_int_arg(argc, argv, "-i", 0);
    if(find_arg(argc, argv, "-nogpu")) {
        gpu_index = -1;
    }

#ifndef GPU
    gpu_index = -1;
#else
    if(gpu_index >= 0){
        cuda_set_device(gpu_index);
    }
#endif

    if (0 == strcmp(argv[1], "average")){
        average(argc, argv);
    } else if (0 == strcmp(argv[1], "yolo")){
        run_yolo(argc, argv);
    } else if (0 == strcmp(argv[1], "super")){
        run_super(argc, argv);
    } else if (0 == strcmp(argv[1], "lsd")){
        run_lsd(argc, argv);
    } else if (0 == strcmp(argv[1], "detector")){
        run_detector(argc, argv);
    } else if (0 == strcmp(argv[1], "detect")){
        float thresh = find_float_arg(argc, argv, "-thresh", .24);
        char *filename = (argc > 4) ? argv[4]: 0;
        char *outfile = find_char_arg(argc, argv, "-out", 0);
        int fullscreen = find_arg(argc, argv, "-fullscreen");
        test_detector("cfg/coco.data", argv[2], argv[3], filename, thresh, .5, outfile, fullscreen);
    } else if (0 == strcmp(argv[1], "cifar")){
        run_cifar(argc, argv);
    } else if (0 == strcmp(argv[1], "go")){
        run_go(argc, argv);
    } else if (0 == strcmp(argv[1], "rnn")){
        run_char_rnn(argc, argv);
    } else if (0 == strcmp(argv[1], "coco")){
        run_coco(argc, argv);
    } else if (0 == strcmp(argv[1], "classify")){
        predict_classifier("cfg/imagenet1k.data", argv[2], argv[3], argv[4], 5);
    } else if (0 == strcmp(argv[1], "classifier")){
        run_classifier(argc, argv);
    } else if (0 == strcmp(argv[1], "regressor")){
        run_regressor(argc, argv);
    } else if (0 == strcmp(argv[1], "segmenter")){
        run_segmenter(argc, argv);
    } else if (0 == strcmp(argv[1], "art")){
        run_art(argc, argv);
    } else if (0 == strcmp(argv[1], "tag")){
        run_tag(argc, argv);
    } else if (0 == strcmp(argv[1], "3d")){
        composite_3d(argv[2], argv[3], argv[4], (argc > 5) ? atof(argv[5]) : 0);
    } else if (0 == strcmp(argv[1], "test")){
        test_resize(argv[2]);
    } else if (0 == strcmp(argv[1], "captcha")){
        run_captcha(argc, argv);
    } else if (0 == strcmp(argv[1], "nightmare")){
        run_nightmare(argc, argv);
    } else if (0 == strcmp(argv[1], "rgbgr")){
        rgbgr_net(argv[2], argv[3], argv[4]);
    } else if (0 == strcmp(argv[1], "reset")){
        reset_normalize_net(argv[2], argv[3], argv[4]);
    } else if (0 == strcmp(argv[1], "denormalize")){
        denormalize_net(argv[2], argv[3], argv[4]);
    } else if (0 == strcmp(argv[1], "statistics")){
        statistics_net(argv[2], argv[3]);
    } else if (0 == strcmp(argv[1], "normalize")){
        normalize_net(argv[2], argv[3], argv[4]);
    } else if (0 == strcmp(argv[1], "rescale")){
        rescale_net(argv[2], argv[3], argv[4]);
    } else if (0 == strcmp(argv[1], "ops")){
        operations(argv[2]);
    } else if (0 == strcmp(argv[1], "speed")){
        speed(argv[2], (argc > 3 && argv[3]) ? atoi(argv[3]) : 0);
    } else if (0 == strcmp(argv[1], "oneoff")){
        oneoff(argv[2], argv[3], argv[4]);
    } else if (0 == strcmp(argv[1], "oneoff2")){
        oneoff2(argv[2], argv[3], argv[4], atoi(argv[5]));
    } else if (0 == strcmp(argv[1], "partial")){
        partial(argv[2], argv[3], argv[4], atoi(argv[5]));
    } else if (0 == strcmp(argv[1], "average")){
        average(argc, argv);
    } else if (0 == strcmp(argv[1], "visualize")){
        visualize(argv[2], (argc > 3) ? argv[3] : 0);
    } else if (0 == strcmp(argv[1], "mkimg")){
        mkimg(argv[2], argv[3], atoi(argv[4]), atoi(argv[5]), atoi(argv[6]), argv[7]);
    } else if (0 == strcmp(argv[1], "imtest")){
        test_resize(argv[2]);
    } else {
        fprintf(stderr, "Not an option: %s\n", argv[1]);
    }
    return 0;
}



================================================
FILE: examples/detector.c
================================================
#include "darknet.h"

static int coco_ids[] = {1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,67,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90};

void train_detector(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear)
{
    list *options = read_data_cfg(datacfg);
    char *train_images = option_find_str(options, "train", "data/train.list");
    char *backup_directory = option_find_str(options, "backup", "/backup/");

    srand(time(0));
    char *base = basecfg(cfgfile);
    printf("%s\n", base);
    float avg_loss = -1;
    network **nets = calloc(ngpus, sizeof(network));

    srand(time(0));
    int seed = rand();
    int i;
    for(i = 0; i < ngpus; ++i){
        srand(seed);
#ifdef GPU
        cuda_set_device(gpus[i]);
#endif
        nets[i] = load_network(cfgfile, weightfile, clear);
        nets[i]->learning_rate *= ngpus;
    }
    srand(time(0));
    network *net = nets[0];

    int imgs = net->batch * net->subdivisions * ngpus;
    printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
    data train, buffer;

    layer l = net->layers[net->n - 1];

    int classes = l.classes;
    float jitter = l.jitter;

    list *plist = get_paths(train_images);
    //int N = plist->size;
    char **paths = (char **)list_to_array(plist);

    load_args args = get_base_args(net);
    args.coords = l.coords;
    args.paths = paths;
    args.n = imgs;
    args.m = plist->size;
    args.classes = classes;
    args.jitter = jitter;
    args.num_boxes = l.max_boxes;
    args.d = &buffer;
    args.type = DETECTION_DATA;
    //args.type = INSTANCE_DATA;
    args.threads = 64;

    pthread_t load_thread = load_data(args);
    double time;
    int count = 0;
    //while(i*imgs < N*120){
    while(get_current_batch(net) < net->max_batches){
        if(l.random && count++%10 == 0){
            printf("Resizing\n");
            int dim = (rand() % 10 + 10) * 32;
            if (get_current_batch(net)+200 > net->max_batches) dim = 608;
            //int dim = (rand() % 4 + 16) * 32;
            printf("%d\n", dim);
            args.w = dim;
            args.h = dim;

            pthread_join(load_thread, 0);
            train = buffer;
            free_data(train);
            load_thread = load_data(args);

            for(i = 0; i < ngpus; ++i){
                resize_network(nets[i], dim, dim);
            }
            net = nets[0];
        }
        time=what_time_is_it_now();
        pthread_join(load_thread, 0);
        train = buffer;
        load_thread = load_data(args);

        /*
        int k;
        for(k = 0; k < l.max_boxes; ++k){
            box b = float_to_box(train.y.vals[10] + 1 + k*5);
            if(!b.x) break;
            printf("loaded: %f %f %f %f\n", b.x, b.y, b.w, b.h);
        }
        */
        /*
        int zz;
        for(zz = 0; zz < train.X.cols; ++zz){
            image im = float_to_image(net->w, net->h, 3, train.X.vals[zz]);
            int k;
            for(k = 0; k < l.max_boxes; ++k){
                box b = float_to_box(train.y.vals[zz] + k*5, 1);
                printf("%f %f %f %f\n", b.x, b.y, b.w, b.h);
                draw_bbox(im, b, 1, 1,0,0);
            }
            show_image(im, "truth11");
            cvWaitKey(0);
            save_image(im, "truth11");
        }
        */

        printf("Loaded: %lf seconds\n", what_time_is_it_now()-time);

        time=what_time_is_it_now();
        float loss = 0;
#ifdef GPU
        if(ngpus == 1){
            loss = train_network(net, train);
        } else {
            loss = train_networks(nets, ngpus, train, 4);
        }
#else
        loss = train_network(net, train);
#endif
        if (avg_loss < 0) avg_loss = loss;
        avg_loss = avg_loss*.9 + loss*.1;

        i = get_current_batch(net);
        printf("%ld: %f, %f avg, %f rate, %lf seconds, %d images\n", get_current_batch(net), loss, avg_loss, get_current_rate(net), what_time_is_it_now()-time, i*imgs);
        if(i%100==0){
#ifdef GPU
            if(ngpus != 1) sync_nets(nets, ngpus, 0);
#endif
            char buff[256];
            sprintf(buff, "%s/%s.backup", backup_directory, base);
            save_weights(net, buff);
        }
        if(i%1000==0 || (i < 1000 && i%100 == 0)){
#ifdef GPU
            if(ngpus != 1) sync_nets(nets, ngpus, 0);
#endif
            char buff[256];
            sprintf(buff, "%s/%s_%d.weights", backup_directory, base, i);
            save_weights(net, buff);
        }
        free_data(train);
    }
#ifdef GPU
    if(ngpus != 1) sync_nets(nets, ngpus, 0);
#endif
    char buff[256];
    sprintf(buff, "%s/%s_final.weights", backup_directory, base);
    save_weights(net, buff);
}


static int get_coco_image_id(char *filename)
{
    char *p = strrchr(filename, '_');
    return atoi(p+1);
}

static void print_cocos(FILE *fp, char *image_path, box *boxes, float **probs, int num_boxes, int classes, int w, int h)
{
    int i, j;
    int image_id = get_coco_image_id(image_path);
    for(i = 0; i < num_boxes; ++i){
        float xmin = boxes[i].x - boxes[i].w/2.;
        float xmax = boxes[i].x + boxes[i].w/2.;
        float ymin = boxes[i].y - boxes[i].h/2.;
        float ymax = boxes[i].y + boxes[i].h/2.;

        if (xmin < 0) xmin = 0;
        if (ymin < 0) ymin = 0;
        if (xmax > w) xmax = w;
        if (ymax > h) ymax = h;

        float bx = xmin;
        float by = ymin;
        float bw = xmax - xmin;
        float bh = ymax - ymin;

        for(j = 0; j < classes; ++j){
            if (probs[i][j]) fprintf(fp, "{\"image_id\":%d, \"category_id\":%d, \"bbox\":[%f, %f, %f, %f], \"score\":%f},\n", image_id, coco_ids[j], bx, by, bw, bh, probs[i][j]);
        }
    }
}

void print_detector_detections(FILE **fps, char *id, box *boxes, float **probs, int total, int classes, int w, int h)
{
    int i, j;
    for(i = 0; i < total; ++i){
        float xmin = boxes[i].x - boxes[i].w/2. + 1;
        float xmax = boxes[i].x + boxes[i].w/2. + 1;
        float ymin = boxes[i].y - boxes[i].h/2. + 1;
        float ymax = boxes[i].y + boxes[i].h/2. + 1;

        if (xmin < 1) xmin = 1;
        if (ymin < 1) ymin = 1;
        if (xmax > w) xmax = w;
        if (ymax > h) ymax = h;

        for(j = 0; j < classes; ++j){
            if (probs[i][j]) fprintf(fps[j], "%s %f %f %f %f %f\n", id, probs[i][j],
                    xmin, ymin, xmax, ymax);
        }
    }
}

void print_imagenet_detections(FILE *fp, int id, box *boxes, float **probs, int total, int classes, int w, int h)
{
    int i, j;
    for(i = 0; i < total; ++i){
        float xmin = boxes[i].x - boxes[i].w/2.;
        float xmax = boxes[i].x + boxes[i].w/2.;
        float ymin = boxes[i].y - boxes[i].h/2.;
        float ymax = boxes[i].y + boxes[i].h/2.;

        if (xmin < 0) xmin = 0;
        if (ymin < 0) ymin = 0;
        if (xmax > w) xmax = w;
        if (ymax > h) ymax = h;

        for(j = 0; j < classes; ++j){
            int class = j;
            if (probs[i][class]) fprintf(fp, "%d %d %f %f %f %f %f\n", id, j+1, probs[i][class],
                    xmin, ymin, xmax, ymax);
        }
    }
}

void validate_detector_flip(char *datacfg, char *cfgfile, char *weightfile, char *outfile)
{
    int j;
    list *options = read_data_cfg(datacfg);
    char *valid_images = option_find_str(options, "valid", "data/train.list");
    char *name_list = option_find_str(options, "names", "data/names.list");
    char *prefix = option_find_str(options, "results", "results");
    char **names = get_labels(name_list);
    char *mapf = option_find_str(options, "map", 0);
    int *map = 0;
    if (mapf) map = read_map(mapf);

    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 2);
    fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
    srand(time(0));

    list *plist = get_paths(valid_images);
    char **paths = (char **)list_to_array(plist);

    layer l = net->layers[net->n-1];
    int classes = l.classes;

    char buff[1024];
    char *type = option_find_str(options, "eval", "voc");
    FILE *fp = 0;
    FILE **fps = 0;
    int coco = 0;
    int imagenet = 0;
    if(0==strcmp(type, "coco")){
        if(!outfile) outfile = "coco_results";
        snprintf(buff, 1024, "%s/%s.json", prefix, outfile);
        fp = fopen(buff, "w");
        fprintf(fp, "[\n");
        coco = 1;
    } else if(0==strcmp(type, "imagenet")){
        if(!outfile) outfile = "imagenet-detection";
        snprintf(buff, 1024, "%s/%s.txt", prefix, outfile);
        fp = fopen(buff, "w");
        imagenet = 1;
        classes = 200;
    } else {
        if(!outfile) outfile = "comp4_det_test_";
        fps = calloc(classes, sizeof(FILE *));
        for(j = 0; j < classes; ++j){
            snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]);
            fps[j] = fopen(buff, "w");
        }
    }


    box *boxes = calloc(l.w*l.h*l.n, sizeof(box));
    float **probs = calloc(l.w*l.h*l.n, sizeof(float *));
    for(j = 0; j < l.w*l.h*l.n; ++j) probs[j] = calloc(classes+1, sizeof(float *));

    int m = plist->size;
    int i=0;
    int t;

    float thresh = .005;
    float nms = .45;

    int nthreads = 4;
    image *val = calloc(nthreads, sizeof(image));
    image *val_resized = calloc(nthreads, sizeof(image));
    image *buf = calloc(nthreads, sizeof(image));
    image *buf_resized = calloc(nthreads, sizeof(image));
    pthread_t *thr = calloc(nthreads, sizeof(pthread_t));

    image input = make_image(net->w, net->h, net->c*2);

    load_args args = {0};
    args.w = net->w;
    args.h = net->h;
    //args.type = IMAGE_DATA;
    args.type = LETTERBOX_DATA;

    for(t = 0; t < nthreads; ++t){
        args.path = paths[i+t];
        args.im = &buf[t];
        args.resized = &buf_resized[t];
        thr[t] = load_data_in_thread(args);
    }
    double start = what_time_is_it_now();
    for(i = nthreads; i < m+nthreads; i += nthreads){
        fprintf(stderr, "%d\n", i);
        for(t = 0; t < nthreads && i+t-nthreads < m; ++t){
            pthread_join(thr[t], 0);
            val[t] = buf[t];
            val_resized[t] = buf_resized[t];
        }
        for(t = 0; t < nthreads && i+t < m; ++t){
            args.path = paths[i+t];
            args.im = &buf[t];
            args.resized = &buf_resized[t];
            thr[t] = load_data_in_thread(args);
        }
        for(t = 0; t < nthreads && i+t-nthreads < m; ++t){
            char *path = paths[i+t-nthreads];
            char *id = basecfg(path);
            copy_cpu(net->w*net->h*net->c, val_resized[t].data, 1, input.data, 1);
            flip_image(val_resized[t]);
            copy_cpu(net->w*net->h*net->c, val_resized[t].data, 1, input.data + net->w*net->h*net->c, 1);

            network_predict(net, input.data);
            int w = val[t].w;
            int h = val[t].h;
            get_region_boxes(l, w, h, net->w, net->h, thresh, probs, boxes, 0, 0, map, .5, 0);
            if (nms) do_nms_sort(boxes, probs, l.w*l.h*l.n, classes, nms);
            if (coco){
                print_cocos(fp, path, boxes, probs, l.w*l.h*l.n, classes, w, h);
            } else if (imagenet){
                print_imagenet_detections(fp, i+t-nthreads+1, boxes, probs, l.w*l.h*l.n, classes, w, h);
            } else {
                print_detector_detections(fps, id, boxes, probs, l.w*l.h*l.n, classes, w, h);
            }
            free(id);
            free_image(val[t]);
            free_image(val_resized[t]);
        }
    }
    for(j = 0; j < classes; ++j){
        if(fps) fclose(fps[j]);
    }
    if(coco){
        fseek(fp, -2, SEEK_CUR);
        fprintf(fp, "\n]\n");
        fclose(fp);
    }
    fprintf(stderr, "Total Detection Time: %f Seconds\n", what_time_is_it_now() - start);
}


void validate_detector(char *datacfg, char *cfgfile, char *weightfile, char *outfile)
{
    int j;
    list *options = read_data_cfg(datacfg);
    char *valid_images = option_find_str(options, "valid", "data/train.list");
    char *name_list = option_find_str(options, "names", "data/names.list");
    char *prefix = option_find_str(options, "results", "results");
    char **names = get_labels(name_list);
    char *mapf = option_find_str(options, "map", 0);
    int *map = 0;
    if (mapf) map = read_map(mapf);

    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
    srand(time(0));

    list *plist = get_paths(valid_images);
    char **paths = (char **)list_to_array(plist);

    layer l = net->layers[net->n-1];
    int classes = l.classes;

    char buff[1024];
    char *type = option_find_str(options, "eval", "voc");
    FILE *fp = 0;
    FILE **fps = 0;
    int coco = 0;
    int imagenet = 0;
    if(0==strcmp(type, "coco")){
        if(!outfile) outfile = "coco_results";
        snprintf(buff, 1024, "%s/%s.json", prefix, outfile);
        fp = fopen(buff, "w");
        fprintf(fp, "[\n");
        coco = 1;
    } else if(0==strcmp(type, "imagenet")){
        if(!outfile) outfile = "imagenet-detection";
        snprintf(buff, 1024, "%s/%s.txt", prefix, outfile);
        fp = fopen(buff, "w");
        imagenet = 1;
        classes = 200;
    } else {
        if(!outfile) outfile = "comp4_det_test_";
        fps = calloc(classes, sizeof(FILE *));
        for(j = 0; j < classes; ++j){
            snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]);
            fps[j] = fopen(buff, "w");
        }
    }


    box *boxes = calloc(l.w*l.h*l.n, sizeof(box));
    float **probs = calloc(l.w*l.h*l.n, sizeof(float *));
    for(j = 0; j < l.w*l.h*l.n; ++j) probs[j] = calloc(classes+1, sizeof(float *));

    int m = plist->size;
    int i=0;
    int t;

    float thresh = .005;
    float nms = .45;

    int nthreads = 4;
    image *val = calloc(nthreads, sizeof(image));
    image *val_resized = calloc(nthreads, sizeof(image));
    image *buf = calloc(nthreads, sizeof(image));
    image *buf_resized = calloc(nthreads, sizeof(image));
    pthread_t *thr = calloc(nthreads, sizeof(pthread_t));

    load_args args = {0};
    args.w = net->w;
    args.h = net->h;
    //args.type = IMAGE_DATA;
    args.type = LETTERBOX_DATA;

    for(t = 0; t < nthreads; ++t){
        args.path = paths[i+t];
        args.im = &buf[t];
        args.resized = &buf_resized[t];
        thr[t] = load_data_in_thread(args);
    }
    double start = what_time_is_it_now();
    for(i = nthreads; i < m+nthreads; i += nthreads){
        fprintf(stderr, "%d\n", i);
        for(t = 0; t < nthreads && i+t-nthreads < m; ++t){
            pthread_join(thr[t], 0);
            val[t] = buf[t];
            val_resized[t] = buf_resized[t];
        }
        for(t = 0; t < nthreads && i+t < m; ++t){
            args.path = paths[i+t];
            args.im = &buf[t];
            args.resized = &buf_resized[t];
            thr[t] = load_data_in_thread(args);
        }
        for(t = 0; t < nthreads && i+t-nthreads < m; ++t){
            char *path = paths[i+t-nthreads];
            char *id = basecfg(path);
            float *X = val_resized[t].data;
            network_predict(net, X);
            int w = val[t].w;
            int h = val[t].h;
            get_region_boxes(l, w, h, net->w, net->h, thresh, probs, boxes, 0, 0, map, .5, 0);
            if (nms) do_nms_sort(boxes, probs, l.w*l.h*l.n, classes, nms);
            if (coco){
                print_cocos(fp, path, boxes, probs, l.w*l.h*l.n, classes, w, h);
            } else if (imagenet){
                print_imagenet_detections(fp, i+t-nthreads+1, boxes, probs, l.w*l.h*l.n, classes, w, h);
            } else {
                print_detector_detections(fps, id, boxes, probs, l.w*l.h*l.n, classes, w, h);
            }
            free(id);
            free_image(val[t]);
            free_image(val_resized[t]);
        }
    }
    for(j = 0; j < classes; ++j){
        if(fps) fclose(fps[j]);
    }
    if(coco){
        fseek(fp, -2, SEEK_CUR);
        fprintf(fp, "\n]\n");
        fclose(fp);
    }
    fprintf(stderr, "Total Detection Time: %f Seconds\n", what_time_is_it_now() - start);
}

void validate_detector_recall(char *cfgfile, char *weightfile)
{
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);
    srand(time(0));

    list *plist = get_paths("data/coco_val_5k.list");
    char **paths = (char **)list_to_array(plist);

    layer l = net->layers[net->n-1];
    int classes = l.classes;

    int j, k;
    box *boxes = calloc(l.w*l.h*l.n, sizeof(box));
    float **probs = calloc(l.w*l.h*l.n, sizeof(float *));
    for(j = 0; j < l.w*l.h*l.n; ++j) probs[j] = calloc(classes+1, sizeof(float *));

    int m = plist->size;
    int i=0;

    float thresh = .001;
    float iou_thresh = .5;
    float nms = .4;

    int total = 0;
    int correct = 0;
    int proposals = 0;
    float avg_iou = 0;

    for(i = 0; i < m; ++i){
        char *path = paths[i];
        image orig = load_image_color(path, 0, 0);
        image sized = resize_image(orig, net->w, net->h);
        char *id = basecfg(path);
        network_predict(net, sized.data);
        get_region_boxes(l, sized.w, sized.h, net->w, net->h, thresh, probs, boxes, 0, 1, 0, .5, 1);
        if (nms) do_nms(boxes, probs, l.w*l.h*l.n, 1, nms);

        char labelpath[4096];
        find_replace(path, "images", "labels", labelpath);
        find_replace(labelpath, "JPEGImages", "labels", labelpath);
        find_replace(labelpath, ".jpg", ".txt", labelpath);
        find_replace(labelpath, ".JPEG", ".txt", labelpath);

        int num_labels = 0;
        box_label *truth = read_boxes(labelpath, &num_labels);
        for(k = 0; k < l.w*l.h*l.n; ++k){
            if(probs[k][0] > thresh){
                ++proposals;
            }
        }
        for (j = 0; j < num_labels; ++j) {
            ++total;
            box t = {truth[j].x, truth[j].y, truth[j].w, truth[j].h};
            float best_iou = 0;
            for(k = 0; k < l.w*l.h*l.n; ++k){
                float iou = box_iou(boxes[k], t);
                if(probs[k][0] > thresh && iou > best_iou){
                    best_iou = iou;
                }
            }
            avg_iou += best_iou;
            if(best_iou > iou_thresh){
                ++correct;
            }
        }

        fprintf(stderr, "%5d %5d %5d\tRPs/Img: %.2f\tIOU: %.2f%%\tRecall:%.2f%%\n", i, correct, total, (float)proposals/(i+1), avg_iou*100/total, 100.*correct/total);
        free(id);
        free_image(orig);
        free_image(sized);
    }
}

void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh, float hier_thresh, char *outfile, int fullscreen)
{
    list *options = read_data_cfg(datacfg);
    char *name_list = option_find_str(options, "names", "data/names.list");
    char **names = get_labels(name_list);

    image **alphabet = load_alphabet();
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    srand(2222222);
    double time;
    char buff[256];
    char *input = buff;
    int j;
    float nms=.3;
    while(1){
        if(filename){
            strncpy(input, filename, 256);
        } else {
            printf("Enter Image Path: ");
            fflush(stdout);
            input = fgets(input, 256, stdin);
            if(!input) return;
            strtok(input, "\n");
        }
        image im = load_image_color(input,0,0);
        image sized = letterbox_image(im, net->w, net->h);
        //image sized = resize_image(im, net->w, net->h);
        //image sized2 = resize_max(im, net->w);
        //image sized = crop_image(sized2, -((net->w - sized2.w)/2), -((net->h - sized2.h)/2), net->w, net->h);
        //resize_network(net, sized.w, sized.h);
        layer l = net->layers[net->n-1];

        box *boxes = calloc(l.w*l.h*l.n, sizeof(box));
        float **probs = calloc(l.w*l.h*l.n, sizeof(float *));
        for(j = 0; j < l.w*l.h*l.n; ++j) probs[j] = calloc(l.classes + 1, sizeof(float *));
        float **masks = 0;
        if (l.coords > 4){
            masks = calloc(l.w*l.h*l.n, sizeof(float*));
            for(j = 0; j < l.w*l.h*l.n; ++j) masks[j] = calloc(l.coords-4, sizeof(float *));
        }

        float *X = sized.data;
        time=what_time_is_it_now();
        network_predict(net, X);
        printf("%s: Predicted in %f seconds.\n", input, what_time_is_it_now()-time);
        get_region_boxes(l, im.w, im.h, net->w, net->h, thresh, probs, boxes, masks, 0, 0, hier_thresh, 1);
        if (nms) do_nms_sort(boxes, probs, l.w*l.h*l.n, l.classes, nms);
        //else if (nms) do_nms_sort(boxes, probs, l.w*l.h*l.n, l.classes, nms);
        draw_detections(im, l.w*l.h*l.n, thresh, boxes, probs, masks, names, alphabet, l.classes);
        if(outfile){
            save_image(im, outfile);
        }
        else{
            save_image(im, "predictions");
#ifdef OPENCV
            cvNamedWindow("predictions", CV_WINDOW_NORMAL);
            if(fullscreen){
                cvSetWindowProperty("predictions", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
            }
            show_image(im, "predictions");
            cvWaitKey(0);
            cvDestroyAllWindows();
#endif
        }

        free_image(im);
        free_image(sized);
        free(boxes);
        free_ptrs((void **)probs, l.w*l.h*l.n);
        if (filename) break;
    }
}

void run_detector(int argc, char **argv)
{
    char *prefix = find_char_arg(argc, argv, "-prefix", 0);
    float thresh = find_float_arg(argc, argv, "-thresh", .24);
    float hier_thresh = find_float_arg(argc, argv, "-hier", .5);
    int cam_index = find_int_arg(argc, argv, "-c", 0);
    int frame_skip = find_int_arg(argc, argv, "-s", 0);
    int avg = find_int_arg(argc, argv, "-avg", 3);
    if(argc < 4){
        fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]);
        return;
    }
    char *gpu_list = find_char_arg(argc, argv, "-gpus", 0);
    char *outfile = find_char_arg(argc, argv, "-out", 0);
    int *gpus = 0;
    int gpu = 0;
    int ngpus = 0;
    if(gpu_list){
        printf("%s\n", gpu_list);
        int len = strlen(gpu_list);
        ngpus = 1;
        int i;
        for(i = 0; i < len; ++i){
            if (gpu_list[i] == ',') ++ngpus;
        }
        gpus = calloc(ngpus, sizeof(int));
        for(i = 0; i < ngpus; ++i){
            gpus[i] = atoi(gpu_list);
            gpu_list = strchr(gpu_list, ',')+1;
        }
    } else {
        gpu = gpu_index;
        gpus = &gpu;
        ngpus = 1;
    }

    int clear = find_arg(argc, argv, "-clear");
    int fullscreen = find_arg(argc, argv, "-fullscreen");
    int width = find_int_arg(argc, argv, "-w", 0);
    int height = find_int_arg(argc, argv, "-h", 0);
    int fps = find_int_arg(argc, argv, "-fps", 0);

    char *datacfg = argv[3];
    char *cfg = argv[4];
    char *weights = (argc > 5) ? argv[5] : 0;
    char *filename = (argc > 6) ? argv[6]: 0;
    if(0==strcmp(argv[2], "test")) test_detector(datacfg, cfg, weights, filename, thresh, hier_thresh, outfile, fullscreen);
    else if(0==strcmp(argv[2], "train")) train_detector(datacfg, cfg, weights, gpus, ngpus, clear);
    else if(0==strcmp(argv[2], "valid")) validate_detector(datacfg, cfg, weights, outfile);
    else if(0==strcmp(argv[2], "valid2")) validate_detector_flip(datacfg, cfg, weights, outfile);
    else if(0==strcmp(argv[2], "recall")) validate_detector_recall(cfg, weights);
    else if(0==strcmp(argv[2], "demo")) {
        list *options = read_data_cfg(datacfg);
        int classes = option_find_int(options, "classes", 20);
        char *name_list = option_find_str(options, "names", "data/names.list");
        char **names = get_labels(name_list);
        demo(cfg, weights, thresh, cam_index, filename, names, classes, frame_skip, prefix, avg, hier_thresh, width, height, fps, fullscreen);
    }
}


================================================
FILE: examples/detector.py
================================================
# Stupid python path shit.
# Instead just add darknet.py to somewhere in your python path
# OK actually that might not be a great idea, idk, work in progress
# Use at your own risk. or don't, i don't care

import sys, os
sys.path.append(os.path.join(os.getcwd(),'python/'))

import darknet as dn

net = dn.load_net("cfg/tiny-yolo.cfg", "tiny-yolo.weights", 0)
meta = dn.load_meta("cfg/coco.data")
r = dn.detect(net, meta, "data/dog.jpg")
print r

# And then down here you could detect a lot more images like:
r = dn.detect(net, meta, "data/eagle.jpg")
print r
r = dn.detect(net, meta, "data/giraffe.jpg")
print r
r = dn.detect(net, meta, "data/horses.jpg")
print r
r = dn.detect(net, meta, "data/person.jpg")
print r



================================================
FILE: examples/dice.c
================================================
#include "darknet.h"

char *dice_labels[] = {"face1","face2","face3","face4","face5","face6"};

void train_dice(char *cfgfile, char *weightfile)
{
    srand(time(0));
    float avg_loss = -1;
    char *base = basecfg(cfgfile);
    char *backup_directory = "/home/pjreddie/backup/";
    printf("%s\n", base);
    network net = parse_network_cfg(cfgfile);
    if(weightfile){
        load_weights(&net, weightfile);
    }
    printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net.learning_rate, net.momentum, net.decay);
    int imgs = 1024;
    int i = *net.seen/imgs;
    char **labels = dice_labels;
    list *plist = get_paths("data/dice/dice.train.list");
    char **paths = (char **)list_to_array(plist);
    printf("%d\n", plist->size);
    clock_t time;
    while(1){
        ++i;
        time=clock();
        data train = load_data_old(paths, imgs, plist->size, labels, 6, net.w, net.h);
        printf("Loaded: %lf seconds\n", sec(clock()-time));

        time=clock();
        float loss = train_network(net, train);
        if(avg_loss == -1) avg_loss = loss;
        avg_loss = avg_loss*.9 + loss*.1;
        printf("%d: %f, %f avg, %lf seconds, %ld images\n", i, loss, avg_loss, sec(clock()-time), *net.seen);
        free_data(train);
        if((i % 100) == 0) net.learning_rate *= .1;
        if(i%100==0){
            char buff[256];
            sprintf(buff, "%s/%s_%d.weights",backup_directory,base, i);
            save_weights(net, buff);
        }
    }
}

void validate_dice(char *filename, char *weightfile)
{
    network net = parse_network_cfg(filename);
    if(weightfile){
        load_weights(&net, weightfile);
    }
    srand(time(0));

    char **labels = dice_labels;
    list *plist = get_paths("data/dice/dice.val.list");

    char **paths = (char **)list_to_array(plist);
    int m = plist->size;
    free_list(plist);

    data val = load_data_old(paths, m, 0, labels, 6, net.w, net.h);
    float *acc = network_accuracies(net, val, 2);
    printf("Validation Accuracy: %f, %d images\n", acc[0], m);
    free_data(val);
}

void test_dice(char *cfgfile, char *weightfile, char *filename)
{
    network net = parse_network_cfg(cfgfile);
    if(weightfile){
        load_weights(&net, weightfile);
    }
    set_batch_network(&net, 1);
    srand(2222222);
    int i = 0;
    char **names = dice_labels;
    char buff[256];
    char *input = buff;
    int indexes[6];
    while(1){
        if(filename){
            strncpy(input, filename, 256);
        }else{
            printf("Enter Image Path: ");
            fflush(stdout);
            input = fgets(input, 256, stdin);
            if(!input) return;
            strtok(input, "\n");
        }
        image im = load_image_color(input, net.w, net.h);
        float *X = im.data;
        float *predictions = network_predict(net, X);
        top_predictions(net, 6, indexes);
        for(i = 0; i < 6; ++i){
            int index = indexes[i];
            printf("%s: %f\n", names[index], predictions[index]);
        }
        free_image(im);
        if (filename) break;
    }
}

void run_dice(int argc, char **argv)
{
    if(argc < 4){
        fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]);
        return;
    }

    char *cfg = argv[3];
    char *weights = (argc > 4) ? argv[4] : 0;
    char *filename = (argc > 5) ? argv[5]: 0;
    if(0==strcmp(argv[2], "test")) test_dice(cfg, weights, filename);
    else if(0==strcmp(argv[2], "train")) train_dice(cfg, weights);
    else if(0==strcmp(argv[2], "valid")) validate_dice(cfg, weights);
}



================================================
FILE: examples/go.c
================================================
#include "darknet.h"

#include <unistd.h>

int inverted = 1;
int noi = 1;
static const int nind = 2;

typedef struct {
    char **data;
    int n;
} moves;

char *fgetgo(FILE *fp)
{
    if(feof(fp)) return 0;
    size_t size = 94;
    char *line = malloc(size*sizeof(char));
    if(size != fread(line, sizeof(char), size, fp)){
        free(line);
        return 0;
    }

    return line;
}

moves load_go_moves(char *filename)
{
    moves m;
    m.n = 128;
    m.data = calloc(128, sizeof(char*));
    FILE *fp = fopen(filename, "rb");
    int count = 0;
    char *line = 0;
    while((line = fgetgo(fp))){
        if(count >= m.n){
            m.n *= 2;
            m.data = realloc(m.data, m.n*sizeof(char*));
        }
        m.data[count] = line;
        ++count;
    }
    printf("%d\n", count);
    m.n = count;
    m.data = realloc(m.data, count*sizeof(char*));
    return m;
}

void string_to_board(char *s, float *board)
{
    int i, j;
    //memset(board, 0, 1*19*19*sizeof(float));
    int count = 0;
    for(i = 0; i < 91; ++i){
        char c = s[i];
        for(j = 0; j < 4; ++j){
            int me = (c >> (2*j)) & 1;
            int you = (c >> (2*j + 1)) & 1;
            if (me) board[count] = 1;
            else if (you) board[count] = -1;
            else board[count] = 0;
            ++count;
            if(count >= 19*19) break;
        }
    }
}

void board_to_string(char *s, float *board)
{
    int i, j;
    memset(s, 0, (19*19/4+1)*sizeof(char));
    int count = 0;
    for(i = 0; i < 91; ++i){
        for(j = 0; j < 4; ++j){
            int me = (board[count] == 1);
            int you = (board[count] == -1);
            if (me) s[i] = s[i] | (1<<(2*j));
            if (you) s[i] = s[i] | (1<<(2*j + 1));
            ++count;
            if(count >= 19*19) break;
        }
    }
}

data random_go_moves(moves m, int n)
{
    data d = {0};
    d.X = make_matrix(n, 19*19);
    d.y = make_matrix(n, 19*19+1);
    int i;
    for(i = 0; i < n; ++i){
        float *board = d.X.vals[i];
        float *label = d.y.vals[i];
        char *b = m.data[rand()%m.n];
        int row = b[0];
        int col = b[1];
        if(row >= 19 || col >= 19){
            label[19*19] = 1;
        } else {
            label[col + 19*row] = 1;
            string_to_board(b+2, board);
            if(board[col + 19*row]) printf("hey\n");
        }

        int flip = rand()%2;
        int rotate = rand()%4;
        image in = float_to_image(19, 19, 1, board);
        image out = float_to_image(19, 19, 1, label);
        if(flip){
            flip_image(in);
            flip_image(out);
        }
        rotate_image_cw(in, rotate);
        rotate_image_cw(out, rotate);
    }
    return d;
}


void train_go(char *cfgfile, char *weightfile, char *filename, int *gpus, int ngpus, int clear)
{
    int i;
    float avg_loss = -1;
    char *base = basecfg(cfgfile);
    printf("%s\n", base);
    printf("%d\n", ngpus);
    network **nets = calloc(ngpus, sizeof(network*));

    srand(time(0));
    int seed = rand();
    for(i = 0; i < ngpus; ++i){
        srand(seed);
#ifdef GPU
        cuda_set_device(gpus[i]);
#endif
        nets[i] = load_network(cfgfile, weightfile, clear);
        nets[i]->learning_rate *= ngpus;
    }
    network *net = nets[0];
    printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);

    char *backup_directory = "/home/pjreddie/backup/";

    char buff[256];
    moves m = load_go_moves(filename);
    //moves m = load_go_moves("games.txt");

    int N = m.n;
    printf("Moves: %d\n", N);
    int epoch = (*net->seen)/N;
    while(get_current_batch(net) < net->max_batches || net->max_batches == 0){
        clock_t time=clock();

        data train = random_go_moves(m, net->batch*net->subdivisions*ngpus);
        printf("Loaded: %lf seconds\n", sec(clock()-time));
        time=clock();

        float loss = 0;
#ifdef GPU
        if(ngpus == 1){
            loss = train_network(net, train);
        } else {
            loss = train_networks(nets, ngpus, train, 4);
        }
#else
        loss = train_network(net, train);
#endif
        free_data(train);

        if(avg_loss == -1) avg_loss = loss;
        avg_loss = avg_loss*.95 + loss*.05;
        printf("%ld, %.3f: %f, %f avg, %f rate, %lf seconds, %ld images\n", get_current_batch(net), (float)(*net->seen)/N, loss, avg_loss, get_current_rate(net), sec(clock()-time), *net->seen);
        if(*net->seen/N > epoch){
            epoch = *net->seen/N;
            char buff[256];
            sprintf(buff, "%s/%s_%d.weights", backup_directory,base, epoch);
            save_weights(net, buff);

        }
        if(get_current_batch(net)%1000 == 0){
            char buff[256];
            sprintf(buff, "%s/%s.backup",backup_directory,base);
            save_weights(net, buff);
        }
        if(get_current_batch(net)%10000 == 0){
            char buff[256];
            sprintf(buff, "%s/%s_%ld.backup",backup_directory,base,get_current_batch(net));
            save_weights(net, buff);
        }
    }
    sprintf(buff, "%s/%s.weights", backup_directory, base);
    save_weights(net, buff);

    free_network(net);
    free(base);
}

void propagate_liberty(float *board, int *lib, int *visited, int row, int col, int side)
{
    if (row < 0 || row > 18 || col < 0 || col > 18) return;
    int index = row*19 + col;
    if (board[index] != side) return;
    if (visited[index]) return;
    visited[index] = 1;
    lib[index] += 1;
    propagate_liberty(board, lib, visited, row+1, col, side);
    propagate_liberty(board, lib, visited, row-1, col, side);
    propagate_liberty(board, lib, visited, row, col+1, side);
    propagate_liberty(board, lib, visited, row, col-1, side);
}


int *calculate_liberties(float *board)
{
    int *lib = calloc(19*19, sizeof(int));
    int visited[361];
    int i, j;
    for(j = 0; j < 19; ++j){
        for(i = 0; i < 19; ++i){
            memset(visited, 0, 19*19*sizeof(int));
            int index = j*19 + i;
            if(board[index] == 0){
                if ((i > 0)  && board[index - 1]) propagate_liberty(board, lib, visited, j, i-1, board[index-1]);
                if ((i < 18) && board[index + 1]) propagate_liberty(board, lib, visited, j, i+1, board[index+1]);
                if ((j > 0)  && board[index - 19]) propagate_liberty(board, lib, visited, j-1, i, board[index-19]);
                if ((j < 18) && board[index + 19]) propagate_liberty(board, lib, visited, j+1, i, board[index+19]);
            }
        }
    }
    return lib;
}

void print_board(FILE *stream, float *board, int swap, int *indexes)
{
    int i,j,n;
    fprintf(stream, "   ");
    for(i = 0; i < 19; ++i){
        fprintf(stream, "%c ", 'A' + i + 1*(i > 7 && noi));
    }
    fprintf(stream, "\n");
    for(j = 0; j < 19; ++j){
        fprintf(stream, "%2d", (inverted) ? 19-j : j+1);
        for(i = 0; i < 19; ++i){
            int index = j*19 + i;
            if(indexes){
                int found = 0;
                for(n = 0; n < nind; ++n){
                    if(index == indexes[n]){
                        found = 1;
                        /*
                           if(n == 0) fprintf(stream, "\uff11");
                           else if(n == 1) fprintf(stream, "\uff12");
                           else if(n == 2) fprintf(stream, "\uff13");
                           else if(n == 3) fprintf(stream, "\uff14");
                           else if(n == 4) fprintf(stream, "\uff15");
                         */
                        if(n == 0) fprintf(stream, " 1");
                        else if(n == 1) fprintf(stream, " 2");
                        else if(n == 2) fprintf(stream, " 3");
                        else if(n == 3) fprintf(stream, " 4");
                        else if(n == 4) fprintf(stream, " 5");
                    }
                }
                if(found) continue;
            }
            //if(board[index]*-swap > 0) fprintf(stream, "\u25C9 ");
            //else if(board[index]*-swap < 0) fprintf(stream, "\u25EF ");
            if(board[index]*-swap > 0) fprintf(stream, " O");
            else if(board[index]*-swap < 0) fprintf(stream, " X");
            else fprintf(stream, "  ");
        }
        fprintf(stream, "\n");
    }
}

void flip_board(float *board)
{
    int i;
    for(i = 0; i < 19*19; ++i){
        board[i] = -board[i];
    }
}

void predict_move(network *net, float *board, float *move, int multi)
{
    float *output = network_predict(net, board);
    copy_cpu(19*19+1, output, 1, move, 1);
    int i;
    if(multi){
        image bim = float_to_image(19, 19, 1, board);
        for(i = 1; i < 8; ++i){
            rotate_image_cw(bim, i);
            if(i >= 4) flip_image(bim);

            float *output = network_predict(net, board);
            image oim = float_to_image(19, 19, 1, output);

            if(i >= 4) flip_image(oim);
            rotate_image_cw(oim, -i);

            axpy_cpu(19*19+1, 1, output, 1, move, 1);

            if(i >= 4) flip_image(bim);
            rotate_image_cw(bim, -i);
        }
        scal_cpu(19*19+1, 1./8., move, 1);
    }
    for(i = 0; i < 19*19; ++i){
        if(board[i]) move[i] = 0;
    }
}

void remove_connected(float *b, int *lib, int p, int r, int c)
{
    if (r < 0 || r >= 19 || c < 0 || c >= 19) return;
    if (b[r*19 + c] != p) return;
    if (lib[r*19 + c] != 1) return;
    b[r*19 + c] = 0;
    remove_connected(b, lib, p, r+1, c);
    remove_connected(b, lib, p, r-1, c);
    remove_connected(b, lib, p, r, c+1);
    remove_connected(b, lib, p, r, c-1);
}


void move_go(float *b, int p, int r, int c)
{
    int *l = calculate_liberties(b);
    b[r*19 + c] = p;
    remove_connected(b, l, -p, r+1, c);
    remove_connected(b, l, -p, r-1, c);
    remove_connected(b, l, -p, r, c+1);
    remove_connected(b, l, -p, r, c-1);
    free(l);
}

int makes_safe_go(float *b, int *lib, int p, int r, int c){
    if (r < 0 || r >= 19 || c < 0 || c >= 19) return 0;
    if (b[r*19 + c] == -p){
        if (lib[r*19 + c] > 1) return 0;
        else return 1;
    }
    if (b[r*19 + c] == 0) return 1;
    if (lib[r*19 + c] > 1) return 1;
    return 0;
}

int suicide_go(float *b, int p, int r, int c)
{
    int *l = calculate_liberties(b);
    int safe = 0;
    safe = safe || makes_safe_go(b, l, p, r+1, c);
    safe = safe || makes_safe_go(b, l, p, r-1, c);
    safe = safe || makes_safe_go(b, l, p, r, c+1);
    safe = safe || makes_safe_go(b, l, p, r, c-1);
    free(l);
    return !safe;
}

int legal_go(float *b, char *ko, int p, int r, int c)
{
    if (b[r*19 + c]) return 0;
    char curr[91];
    char next[91];
    board_to_string(curr, b);
    move_go(b, p, r, c);
    board_to_string(next, b);
    string_to_board(curr, b);
    if(memcmp(next, ko, 91) == 0) return 0;
    return 1;
}

int generate_move(network *net, int player, float *board, int multi, float thresh, float temp, char *ko, int print)
{
    int i, j;
    int empty = 1;
    for(i = 0; i < 19*19; ++i){
        if (board[i]) {
            empty = 0;
            break;
        }
    }
    if(empty) {
        return 72;
    }
    for(i = 0; i < net->n; ++i) net->layers[i].temperature = temp;

    float move[362];
    if (player < 0) flip_board(board);
    predict_move(net, board, move, multi);
    if (player < 0) flip_board(board);


    for(i = 0; i < 19; ++i){
        for(j = 0; j < 19; ++j){
            if (!legal_go(board, ko, player, i, j)) move[i*19 + j] = 0;
        }
    }

    int indexes[nind];
    top_k(move, 19*19+1, nind, indexes);
    if(thresh > move[indexes[0]]) thresh = move[indexes[nind-1]];

    for(i = 0; i < 19*19+1; ++i){
        if (move[i] < thresh) move[i] = 0;
    }


    int max = max_index(move, 19*19+1);
    int row = max / 19;
    int col = max % 19;
    int index = sample_array(move, 19*19+1);

    if(print){
        top_k(move, 19*19+1, nind, indexes);
        for(i = 0; i < nind; ++i){
            if (!move[indexes[i]]) indexes[i] = -1;
        }
        print_board(stderr, board, player, indexes);
        for(i = 0; i < nind; ++i){
            fprintf(stderr, "%d: %f\n", i+1, move[indexes[i]]);
        }
    }
    if (row == 19) return -1;

    if (suicide_go(board, player, row, col)){
        return -1; 
    }

    if (suicide_go(board, player, index/19, index%19)){
        index = max;
    }
    if (index == 19*19) return -1;
    return index;
}

void valid_go(char *cfgfile, char *weightfile, int multi, char *filename)
{
    srand(time(0));
    char *base = basecfg(cfgfile);
    printf("%s\n", base);
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay);

    float *board = calloc(19*19, sizeof(float));
    float *move = calloc(19*19+1, sizeof(float));
   // moves m = load_go_moves("/home/pjreddie/backup/go.test");
    moves m = load_go_moves(filename);

    int N = m.n;
    int i;
    int correct = 0;
    for(i = 0; i <N; ++i){
        char *b = m.data[i];
        int row = b[0];
        int col = b[1];
        int truth = col + 19*row;
        string_to_board(b+2, board);
        predict_move(net, bo
Download .txt
gitextract_6ruq8af_/

├── .gitignore
├── Licenses/
│   ├── LICENSE
│   ├── LICENSE.fuck
│   ├── LICENSE.gen
│   ├── LICENSE.gpl
│   ├── LICENSE.meta
│   ├── LICENSE.mit
│   └── LICENSE.v1
├── Makefile
├── README.md
├── examples/
│   ├── art.c
│   ├── attention.c
│   ├── captcha.c
│   ├── cifar.c
│   ├── classifier.c
│   ├── coco.c
│   ├── darknet.c
│   ├── detector.c
│   ├── detector.py
│   ├── dice.c
│   ├── go.c
│   ├── lsd.c
│   ├── nightmare.c
│   ├── regressor.c
│   ├── rnn.c
│   ├── rnn_vid.c
│   ├── segmenter.c
│   ├── super.c
│   ├── swag.c
│   ├── tag.c
│   ├── voxel.c
│   ├── writing.c
│   └── yolo.c
├── include/
│   └── darknet.h
├── python/
│   ├── darknet.py
│   └── proverbot.py
└── src/
    ├── activation_kernels.cu
    ├── activation_layer.c
    ├── activation_layer.h
    ├── activations.c
    ├── activations.h
    ├── avgpool_layer.c
    ├── avgpool_layer.h
    ├── avgpool_layer_kernels.cu
    ├── batchnorm_layer.c
    ├── batchnorm_layer.h
    ├── blas.c
    ├── blas.h
    ├── blas_kernels.cu
    ├── box.c
    ├── box.h
    ├── classifier.h
    ├── col2im.c
    ├── col2im.h
    ├── col2im_kernels.cu
    ├── compare.c
    ├── connected_layer.c
    ├── connected_layer.h
    ├── convolutional_kernels.cu
    ├── convolutional_layer.c
    ├── convolutional_layer.h
    ├── cost_layer.c
    ├── cost_layer.h
    ├── crnn_layer.c
    ├── crnn_layer.h
    ├── crop_layer.c
    ├── crop_layer.h
    ├── crop_layer_kernels.cu
    ├── cuda.c
    ├── cuda.h
    ├── data.c
    ├── data.h
    ├── deconvolutional_kernels.cu
    ├── deconvolutional_layer.c
    ├── deconvolutional_layer.h
    ├── demo.c
    ├── demo.h
    ├── detection_layer.c
    ├── detection_layer.h
    ├── dropout_layer.c
    ├── dropout_layer.h
    ├── dropout_layer_kernels.cu
    ├── gemm.c
    ├── gemm.h
    ├── gru_layer.c
    ├── gru_layer.h
    ├── im2col.c
    ├── im2col.h
    ├── im2col_kernels.cu
    ├── image.c
    ├── image.h
    ├── layer.c
    ├── layer.h
    ├── list.c
    ├── list.h
    ├── local_layer.c
    ├── local_layer.h
    ├── lstm_layer.c
    ├── lstm_layer.h
    ├── matrix.c
    ├── matrix.h
    ├── maxpool_layer.c
    ├── maxpool_layer.h
    ├── maxpool_layer_kernels.cu
    ├── network.c
    ├── network.h
    ├── normalization_layer.c
    ├── normalization_layer.h
    ├── option_list.c
    ├── option_list.h
    ├── parser.c
    ├── parser.h
    ├── region_layer.c
    ├── region_layer.h
    ├── reorg_layer.c
    ├── reorg_layer.h
    ├── rnn_layer.c
    ├── rnn_layer.h
    ├── route_layer.c
    ├── route_layer.h
    ├── shortcut_layer.c
    ├── shortcut_layer.h
    ├── softmax_layer.c
    ├── softmax_layer.h
    ├── stb_image.h
    ├── stb_image_write.h
    ├── tree.c
    ├── tree.h
    ├── utils.c
    └── utils.h
Download .txt
SYMBOL INDEX (1053 symbols across 82 files)

FILE: examples/art.c
  function demo_art (line 5) | void demo_art(char *cfgfile, char *weightfile, int cam_index)
  function run_art (line 57) | void run_art(int argc, char **argv)

FILE: examples/attention.c
  function train_attention (line 6) | void train_attention(char *datacfg, char *cfgfile, char *weightfile, cha...
  function validate_attention_single (line 129) | void validate_attention_single(char *datacfg, char *filename, char *weig...
  function validate_attention_multi (line 188) | void validate_attention_multi(char *datacfg, char *filename, char *weigh...
  function predict_attention (line 249) | void predict_attention(char *datacfg, char *cfgfile, char *weightfile, c...
  function run_attention (line 301) | void run_attention(int argc, char **argv)

FILE: examples/captcha.c
  function fix_data_captcha (line 3) | void fix_data_captcha(data d, int mask)
  function train_captcha (line 27) | void train_captcha(char *cfgfile, char *weightfile)
  function test_captcha (line 93) | void test_captcha(char *cfgfile, char *weightfile, char *filename)
  function valid_captcha (line 130) | void valid_captcha(char *cfgfile, char *weightfile, char *filename)
  function run_captcha (line 335) | void run_captcha(int argc, char **argv)

FILE: examples/cifar.c
  function train_cifar (line 3) | void train_cifar(char *cfgfile, char *weightfile)
  function train_cifar_distill (line 48) | void train_cifar_distill(char *cfgfile, char *weightfile)
  function test_cifar_multi (line 101) | void test_cifar_multi(char *filename, char *weightfile)
  function test_cifar (line 130) | void test_cifar(char *filename, char *weightfile)
  function extract_cifar (line 149) | void extract_cifar()
  function test_cifar_csv (line 171) | void test_cifar_csv(char *filename, char *weightfile)
  function test_cifar_csvtrain (line 195) | void test_cifar_csvtrain(char *cfg, char *weights)
  function eval_cifar_csv (line 219) | void eval_cifar_csv()
  function run_cifar (line 232) | void run_cifar(int argc, char **argv)

FILE: examples/classifier.c
  function train_classifier (line 18) | void train_classifier(char *datacfg, char *cfgfile, char *weightfile, in...
  function validate_classifier_crop (line 160) | void validate_classifier_crop(char *datacfg, char *filename, char *weigh...
  function validate_classifier_10 (line 224) | void validate_classifier_10(char *datacfg, char *filename, char *weightf...
  function validate_classifier_full (line 293) | void validate_classifier_full(char *datacfg, char *filename, char *weigh...
  function validate_classifier_single (line 351) | void validate_classifier_single(char *datacfg, char *filename, char *wei...
  function validate_classifier_multi (line 410) | void validate_classifier_multi(char *datacfg, char *cfg, char *weights)
  function try_classifier (line 472) | void try_classifier(char *datacfg, char *cfgfile, char *weightfile, char...
  function predict_classifier (line 550) | void predict_classifier(char *datacfg, char *cfgfile, char *weightfile, ...
  function label_classifier (line 602) | void label_classifier(char *datacfg, char *filename, char *weightfile)
  function test_classifier (line 638) | void test_classifier(char *datacfg, char *cfgfile, char *weightfile, int...
  function threat_classifier (line 708) | void threat_classifier(char *datacfg, char *cfgfile, char *weightfile, i...
  function gun_classifier (line 838) | void gun_classifier(char *datacfg, char *cfgfile, char *weightfile, int ...
  function demo_classifier (line 914) | void demo_classifier(char *datacfg, char *cfgfile, char *weightfile, int...
  function run_classifier (line 979) | void run_classifier(int argc, char **argv)

FILE: examples/coco.c
  function train_coco (line 9) | void train_coco(char *cfgfile, char *weightfile)
  function print_cocos (line 97) | void print_cocos(FILE *fp, int image_id, box *boxes, float **probs, int ...
  function get_coco_image_id (line 122) | int get_coco_image_id(char *filename)
  function validate_coco (line 128) | void validate_coco(char *cfg, char *weights)
  function validate_coco_recall (line 216) | void validate_coco_recall(char *cfgfile, char *weightfile)
  function test_coco (line 300) | void test_coco(char *cfgfile, char *weightfile, char *filename, float th...
  function run_coco (line 346) | void run_coco(int argc, char **argv)

FILE: examples/darknet.c
  function average (line 25) | void average(int argc, char *argv[])
  function numops (line 81) | long numops(network *net)
  function speed (line 116) | void speed(char *cfgfile, int tics)
  function operations (line 136) | void operations(char *cfgfile)
  function oneoff (line 145) | void oneoff(char *cfgfile, char *weightfile, char *outfile)
  function oneoff2 (line 172) | void oneoff2(char *cfgfile, char *weightfile, char *outfile, int l)
  function partial (line 184) | void partial(char *cfgfile, char *weightfile, char *outfile, int max)
  function rescale_net (line 191) | void rescale_net(char *cfgfile, char *weightfile, char *outfile)
  function rgbgr_net (line 206) | void rgbgr_net(char *cfgfile, char *weightfile, char *outfile)
  function reset_normalize_net (line 221) | void reset_normalize_net(char *cfgfile, char *weightfile, char *outfile)
  function layer (line 246) | layer normalize_layer(layer l, int n)
  function normalize_net (line 259) | void normalize_net(char *cfgfile, char *weightfile, char *outfile)
  function statistics_net (line 285) | void statistics_net(char *cfgfile, char *weightfile)
  function denormalize_net (line 315) | void denormalize_net(char *cfgfile, char *weightfile, char *outfile)
  function mkimg (line 349) | void mkimg(char *cfgfile, char *weightfile, int h, int w, int num, char ...
  function visualize (line 375) | void visualize(char *cfgfile, char *weightfile)
  function main (line 384) | int main(int argc, char **argv)

FILE: examples/detector.c
  function train_detector (line 5) | void train_detector(char *datacfg, char *cfgfile, char *weightfile, int ...
  function get_coco_image_id (line 155) | static int get_coco_image_id(char *filename)
  function print_cocos (line 161) | static void print_cocos(FILE *fp, char *image_path, box *boxes, float **...
  function print_detector_detections (line 187) | void print_detector_detections(FILE **fps, char *id, box *boxes, float *...
  function print_imagenet_detections (line 208) | void print_imagenet_detections(FILE *fp, int id, box *boxes, float **pro...
  function validate_detector_flip (line 230) | void validate_detector_flip(char *datacfg, char *cfgfile, char *weightfi...
  function validate_detector (line 363) | void validate_detector(char *datacfg, char *cfgfile, char *weightfile, c...
  function validate_detector_recall (line 490) | void validate_detector_recall(char *cfgfile, char *weightfile)
  function test_detector (line 565) | void test_detector(char *datacfg, char *cfgfile, char *weightfile, char ...
  function run_detector (line 639) | void run_detector(int argc, char **argv)

FILE: examples/dice.c
  function train_dice (line 5) | void train_dice(char *cfgfile, char *weightfile)
  function validate_dice (line 45) | void validate_dice(char *filename, char *weightfile)
  function test_dice (line 66) | void test_dice(char *cfgfile, char *weightfile, char *filename)
  function run_dice (line 102) | void run_dice(int argc, char **argv)

FILE: examples/go.c
  type moves (line 9) | typedef struct {
  function moves (line 27) | moves load_go_moves(char *filename)
  function string_to_board (line 49) | void string_to_board(char *s, float *board)
  function board_to_string (line 68) | void board_to_string(char *s, float *board)
  function data (line 85) | data random_go_moves(moves m, int n)
  function train_go (line 120) | void train_go(char *cfgfile, char *weightfile, char *filename, int *gpus...
  function propagate_liberty (line 198) | void propagate_liberty(float *board, int *lib, int *visited, int row, in...
  function print_board (line 233) | void print_board(FILE *stream, float *board, int swap, int *indexes)
  function flip_board (line 276) | void flip_board(float *board)
  function predict_move (line 284) | void predict_move(network *net, float *board, float *move, int multi)
  function remove_connected (line 313) | void remove_connected(float *b, int *lib, int p, int r, int c)
  function move_go (line 326) | void move_go(float *b, int p, int r, int c)
  function makes_safe_go (line 337) | int makes_safe_go(float *b, int *lib, int p, int r, int c){
  function suicide_go (line 348) | int suicide_go(float *b, int p, int r, int c)
  function legal_go (line 360) | int legal_go(float *b, char *ko, int p, int r, int c)
  function generate_move (line 373) | int generate_move(network *net, int player, float *board, int multi, flo...
  function valid_go (line 437) | void valid_go(char *cfgfile, char *weightfile, int multi, char *filename)
  function print_game (line 467) | int print_game(float *board, FILE *fp)
  function engine_go (line 484) | void engine_go(char *filename, char *weightfile, int multi)
  function test_go (line 674) | void test_go(char *cfg, char *weights, int multi)
  function score_game (line 751) | float score_game(float *board)
  function self_go (line 777) | void self_go(char *filename, char *weightfile, char *f2, char *w2, int m...
  function run_go (line 859) | void run_go(int argc, char **argv)

FILE: examples/lsd.c
  function test_dcgan (line 386) | void test_dcgan(char *cfgfile, char *weightfile)
  function dcgan_batch (line 429) | void dcgan_batch(network gnet, network anet)
  function train_dcgan (line 435) | void train_dcgan(char *cfg, char *weight, char *acfg, char *aweight, int...
  function train_colorizer (line 616) | void train_colorizer(char *cfg, char *weight, char *acfg, char *aweight,...
  function test_lsd (line 1045) | void test_lsd(char *cfg, char *weights, char *filename, int gray)
  function run_lsd (line 1101) | void run_lsd(int argc, char **argv)

FILE: examples/nightmare.c
  function abs_mean (line 7) | float abs_mean(float *x, int n)
  function calculate_loss (line 17) | void calculate_loss(float *output, float *delta, int n, float thresh)
  function optimize_picture (line 28) | void optimize_picture(network *net, image orig, int max_layer, float sca...
  function smooth (line 109) | void smooth(image recon, image update, float lambda, int num)
  function reconstruct_picture (line 130) | void reconstruct_picture(network *net, float *features, image recon, ima...
  function run_nightmare (line 283) | void run_nightmare(int argc, char **argv)

FILE: examples/regressor.c
  function train_regressor (line 5) | void train_regressor(char *datacfg, char *cfgfile, char *weightfile, int...
  function predict_regressor (line 114) | void predict_regressor(char *cfgfile, char *weightfile, char *filename)
  function demo_regressor (line 148) | void demo_regressor(char *datacfg, char *cfgfile, char *weightfile, int ...
  function run_regressor (line 199) | void run_regressor(int argc, char **argv)

FILE: examples/rnn.c
  type float_pair (line 5) | typedef struct {
  function float_pair (line 70) | float_pair get_rnn_token_data(int *tokens, size_t *offsets, int characte...
  function float_pair (line 96) | float_pair get_seq2seq_data(char **source, char **dest, int n, int chara...
  function float_pair (line 127) | float_pair get_rnn_data(unsigned char *text, size_t *offsets, int charac...
  function train_char_rnn (line 157) | void train_char_rnn(char *cfgfile, char *weightfile, char *filename, int...
  function print_symbol (line 237) | void print_symbol(int n, char **tokens){
  function test_char_rnn (line 245) | void test_char_rnn(char *cfgfile, char *weightfile, int num, char *seed,...
  function test_tactic_rnn_multi (line 299) | void test_tactic_rnn_multi(char *cfgfile, char *weightfile, int num, flo...
  function test_tactic_rnn (line 344) | void test_tactic_rnn(char *cfgfile, char *weightfile, int num, float tem...
  function valid_tactic_rnn (line 386) | void valid_tactic_rnn(char *cfgfile, char *weightfile, char *seed)
  function valid_char_rnn (line 435) | void valid_char_rnn(char *cfgfile, char *weightfile, char *seed)
  function vec_char_rnn (line 473) | void vec_char_rnn(char *cfgfile, char *weightfile, char *seed)
  function run_char_rnn (line 519) | void run_char_rnn(int argc, char **argv)

FILE: examples/rnn_vid.c
  type float_pair (line 10) | typedef struct {
  function float_pair (line 15) | float_pair get_rnn_vid_data(network net, char **files, int n, int batch,...
  function train_vid_rnn (line 71) | void train_vid_rnn(char *cfgfile, char *weightfile)
  function image (line 129) | image save_reconstruction(network net, image *init, float *feat, char *n...
  function generate_vid_rnn (line 147) | void generate_vid_rnn(char *cfgfile, char *weightfile)
  function run_vid_rnn (line 192) | void run_vid_rnn(int argc, char **argv)
  function run_vid_rnn (line 206) | void run_vid_rnn(int argc, char **argv){}

FILE: examples/segmenter.c
  function train_segmenter (line 5) | void train_segmenter(char *datacfg, char *cfgfile, char *weightfile, int...
  function predict_segmenter (line 135) | void predict_segmenter(char *datafile, char *cfg, char *weights, char *f...
  function demo_segmenter (line 177) | void demo_segmenter(char *datacfg, char *cfg, char *weights, int cam_ind...
  function run_segmenter (line 230) | void run_segmenter(int argc, char **argv)

FILE: examples/super.c
  function train_super (line 3) | void train_super(char *cfgfile, char *weightfile, int clear)
  function test_super (line 67) | void test_super(char *cfgfile, char *weightfile, char *filename)
  function run_super (line 103) | void run_super(int argc, char **argv)

FILE: examples/swag.c
  function train_swag (line 4) | void train_swag(char *cfgfile, char *weightfile)
  function run_swag (line 73) | void run_swag(int argc, char **argv)

FILE: examples/tag.c
  function train_tag (line 3) | void train_tag(char *cfgfile, char *weightfile, int clear)
  function test_tag (line 83) | void test_tag(char *cfgfile, char *weightfile, char *filename)
  function run_tag (line 126) | void run_tag(int argc, char **argv)

FILE: examples/voxel.c
  function extract_voxel (line 3) | void extract_voxel(char *lfile, char *rfile, char *prefix)
  function train_voxel (line 39) | void train_voxel(char *cfgfile, char *weightfile)
  function test_voxel (line 106) | void test_voxel(char *cfgfile, char *weightfile, char *filename)
  function run_voxel (line 145) | void run_voxel(int argc, char **argv)

FILE: examples/writing.c
  function train_writing (line 3) | void train_writing(char *cfgfile, char *weightfile)
  function test_writing (line 82) | void test_writing(char *cfgfile, char *weightfile, char *filename)
  function run_writing (line 131) | void run_writing(int argc, char **argv)

FILE: examples/yolo.c
  function train_yolo (line 5) | void train_yolo(char *cfgfile, char *weightfile)
  function print_yolo_detections (line 77) | void print_yolo_detections(FILE **fps, char *id, box *boxes, float **pro...
  function validate_yolo (line 98) | void validate_yolo(char *cfg, char *weights)
  function validate_yolo_recall (line 183) | void validate_yolo_recall(char *cfg, char *weights)
  function test_yolo (line 266) | void test_yolo(char *cfgfile, char *weightfile, char *filename, float th...
  function run_yolo (line 313) | void run_yolo(int argc, char **argv)

FILE: include/darknet.h
  type metadata (line 35) | typedef struct{
  type tree (line 42) | typedef struct{
  type ACTIVATION (line 55) | typedef enum{
  type LAYER_TYPE (line 59) | typedef enum {
  type COST_TYPE (line 87) | typedef enum{
  type update_args (line 91) | typedef struct{
  type network (line 103) | struct network
  type network (line 104) | typedef struct network network;
  type layer (line 106) | struct layer
  type layer (line 107) | typedef struct layer layer;
  type layer (line 109) | struct layer{
  type learning_rate_policy (line 408) | typedef enum {
  type network (line 412) | typedef struct network{
  type augment_args (line 479) | typedef struct {
  type image (line 489) | typedef struct {
  type box (line 496) | typedef struct{
  type matrix (line 500) | typedef struct matrix{
  type data (line 506) | typedef struct{
  type data_type (line 515) | typedef enum {
  type load_args (line 519) | typedef struct load_args{
  type box_label (line 552) | typedef struct{
  type node (line 564) | typedef struct node{
  type list (line 570) | typedef struct list{

FILE: python/darknet.py
  function sample (line 5) | def sample(probs):
  function c_array (line 15) | def c_array(ctype, values):
  class BOX (line 18) | class BOX(Structure):
  class IMAGE (line 24) | class IMAGE(Structure):
  class METADATA (line 30) | class METADATA(Structure):
  function classify (line 92) | def classify(net, meta, im):
  function detect (line 100) | def detect(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45):

FILE: python/proverbot.py
  function predict_tactic (line 3) | def predict_tactic(net, s):
  function predict_tactics (line 27) | def predict_tactics(net, s, n):

FILE: src/activation_layer.c
  function layer (line 12) | layer make_activation_layer(int batch, int inputs, ACTIVATION activation)
  function forward_activation_layer (line 38) | void forward_activation_layer(layer l, network net)
  function backward_activation_layer (line 44) | void backward_activation_layer(layer l, network net)
  function forward_activation_layer_gpu (line 52) | void forward_activation_layer_gpu(layer l, network net)
  function backward_activation_layer_gpu (line 58) | void backward_activation_layer_gpu(layer l, network net)

FILE: src/activations.c
  function ACTIVATION (line 43) | ACTIVATION get_activation(char *s)
  function activate (line 62) | float activate(float x, ACTIVATION a)
  function activate_array (line 95) | void activate_array(float *x, const int n, const ACTIVATION a)
  function gradient (line 103) | float gradient(float x, ACTIVATION a)
  function gradient_array (line 136) | void gradient_array(const float *x, const int n, const ACTIVATION a, flo...

FILE: src/activations.h
  function stair_activate (line 19) | static inline float stair_activate(float x)
  function hardtan_activate (line 25) | static inline float hardtan_activate(float x)
  function linear_activate (line 31) | static inline float linear_activate(float x){return x;}
  function logistic_activate (line 32) | static inline float logistic_activate(float x){return 1./(1. + exp(-x));}
  function loggy_activate (line 33) | static inline float loggy_activate(float x){return 2./(1. + exp(-x)) - 1;}
  function relu_activate (line 34) | static inline float relu_activate(float x){return x*(x>0);}
  function elu_activate (line 35) | static inline float elu_activate(float x){return (x >= 0)*x + (x < 0)*(e...
  function relie_activate (line 36) | static inline float relie_activate(float x){return (x>0) ? x : .01*x;}
  function ramp_activate (line 37) | static inline float ramp_activate(float x){return x*(x>0)+.1*x;}
  function leaky_activate (line 38) | static inline float leaky_activate(float x){return (x>0) ? x : .1*x;}
  function tanh_activate (line 39) | static inline float tanh_activate(float x){return (exp(2*x)-1)/(exp(2*x)...
  function plse_activate (line 40) | static inline float plse_activate(float x)
  function lhtan_activate (line 47) | static inline float lhtan_activate(float x)
  function lhtan_gradient (line 53) | static inline float lhtan_gradient(float x)
  function hardtan_gradient (line 59) | static inline float hardtan_gradient(float x)
  function linear_gradient (line 64) | static inline float linear_gradient(float x){return 1;}
  function logistic_gradient (line 65) | static inline float logistic_gradient(float x){return (1-x)*x;}
  function loggy_gradient (line 66) | static inline float loggy_gradient(float x)
  function stair_gradient (line 71) | static inline float stair_gradient(float x)
  function relu_gradient (line 76) | static inline float relu_gradient(float x){return (x>0);}
  function elu_gradient (line 77) | static inline float elu_gradient(float x){return (x >= 0) + (x < 0)*(x +...
  function relie_gradient (line 78) | static inline float relie_gradient(float x){return (x>0) ? 1 : .01;}
  function ramp_gradient (line 79) | static inline float ramp_gradient(float x){return (x>0)+.1;}
  function leaky_gradient (line 80) | static inline float leaky_gradient(float x){return (x>0) ? 1 : .1;}
  function tanh_gradient (line 81) | static inline float tanh_gradient(float x){return 1-x*x;}
  function plse_gradient (line 82) | static inline float plse_gradient(float x){return (x < 0 || x > 1) ? .01...

FILE: src/avgpool_layer.c
  function avgpool_layer (line 5) | avgpool_layer make_avgpool_layer(int batch, int w, int h, int c)
  function resize_avgpool_layer (line 33) | void resize_avgpool_layer(avgpool_layer *l, int w, int h)
  function forward_avgpool_layer (line 40) | void forward_avgpool_layer(const avgpool_layer l, network net)
  function backward_avgpool_layer (line 57) | void backward_avgpool_layer(const avgpool_layer l, network net)

FILE: src/avgpool_layer.h
  type layer (line 9) | typedef layer avgpool_layer;

FILE: src/batchnorm_layer.c
  function layer (line 6) | layer make_batchnorm_layer(int batch, int w, int h, int c)
  function backward_scale_cpu (line 72) | void backward_scale_cpu(float *x_norm, float *delta, int batch, int n, i...
  function mean_delta_cpu (line 87) | void mean_delta_cpu(float *delta, float *variance, int batch, int filter...
  function variance_delta_cpu (line 102) | void  variance_delta_cpu(float *x, float *delta, float *mean, float *var...
  function normalize_delta_cpu (line 117) | void normalize_delta_cpu(float *x, float *mean, float *variance, float *...
  function resize_batchnorm_layer (line 130) | void resize_batchnorm_layer(layer *layer, int w, int h)
  function forward_batchnorm_layer (line 135) | void forward_batchnorm_layer(layer l, network net)
  function backward_batchnorm_layer (line 157) | void backward_batchnorm_layer(layer l, network net)
  function pull_batchnorm_layer (line 176) | void pull_batchnorm_layer(layer l)
  function push_batchnorm_layer (line 182) | void push_batchnorm_layer(layer l)
  function forward_batchnorm_layer_gpu (line 189) | void forward_batchnorm_layer_gpu(layer l, network net)
  function backward_batchnorm_layer_gpu (line 238) | void backward_batchnorm_layer_gpu(layer l, network net)

FILE: src/blas.c
  function reorg_cpu (line 9) | void reorg_cpu(float *x, int w, int h, int c, int batch, int stride, int...
  function flatten (line 32) | void flatten(float *x, int size, int layers, int batch, int forward)
  function weighted_sum_cpu (line 50) | void weighted_sum_cpu(float *a, float *b, float *s, int n, float *c)
  function weighted_delta_cpu (line 58) | void weighted_delta_cpu(float *a, float *b, float *s, float *da, float *...
  function shortcut_cpu (line 68) | void shortcut_cpu(int batch, int w1, int h1, int c1, float *add, int w2,...
  function mean_cpu (line 94) | void mean_cpu(float *x, int batch, int filters, int spatial, float *mean)
  function variance_cpu (line 110) | void variance_cpu(float *x, float *mean, int batch, int filters, int spa...
  function normalize_cpu (line 126) | void normalize_cpu(float *x, float *mean, float *variance, int batch, in...
  function const_cpu (line 139) | void const_cpu(int N, float ALPHA, float *X, int INCX)
  function mul_cpu (line 145) | void mul_cpu(int N, float *X, int INCX, float *Y, int INCY)
  function pow_cpu (line 151) | void pow_cpu(int N, float ALPHA, float *X, int INCX, float *Y, int INCY)
  function axpy_cpu (line 157) | void axpy_cpu(int N, float ALPHA, float *X, int INCX, float *Y, int INCY)
  function scal_cpu (line 163) | void scal_cpu(int N, float ALPHA, float *X, int INCX)
  function fill_cpu (line 169) | void fill_cpu(int N, float ALPHA, float *X, int INCX)
  function deinter_cpu (line 175) | void deinter_cpu(int NX, float *X, int NY, float *Y, int B, float *OUT)
  function inter_cpu (line 191) | void inter_cpu(int NX, float *X, int NY, float *Y, int B, float *OUT)
  function copy_cpu (line 205) | void copy_cpu(int N, float *X, int INCX, float *Y, int INCY)
  function mult_add_into_cpu (line 211) | void mult_add_into_cpu(int N, float *X, float *Y, float *Z)
  function smooth_l1_cpu (line 217) | void smooth_l1_cpu(int n, float *pred, float *truth, float *delta, float...
  function l1_cpu (line 234) | void l1_cpu(int n, float *pred, float *truth, float *delta, float *error)
  function l2_cpu (line 244) | void l2_cpu(int n, float *pred, float *truth, float *delta, float *error)
  function dot_cpu (line 254) | float dot_cpu(int N, float *X, int INCX, float *Y, int INCY)
  function softmax (line 262) | void softmax(float *input, int n, float temp, int stride, float *output)
  function softmax_cpu (line 281) | void softmax_cpu(float *input, int n, int batch, int batch_offset, int g...

FILE: src/box.c
  function box (line 6) | box float_to_box(float *f, int stride)
  function dbox (line 16) | dbox derivative(box a, box b)
  function overlap (line 67) | float overlap(float x1, float w1, float x2, float w2)
  function box_intersection (line 78) | float box_intersection(box a, box b)
  function box_union (line 87) | float box_union(box a, box b)
  function box_iou (line 94) | float box_iou(box a, box b)
  function box_rmse (line 99) | float box_rmse(box a, box b)
  function dbox (line 107) | dbox dintersect(box a, box b)
  function dbox (line 122) | dbox dunion(box a, box b)
  function test_dunion (line 136) | void test_dunion()
  function test_dintersect (line 158) | void test_dintersect()
  function test_box (line 181) | void test_box()
  function dbox (line 210) | dbox diou(box a, box b)
  type sortable_bbox (line 233) | typedef struct{
  function nms_comparator (line 239) | int nms_comparator(const void *pa, const void *pb)
  function do_nms_obj (line 249) | void do_nms_obj(box *boxes, float **probs, int total, int classes, float...
  function do_nms_sort (line 277) | void do_nms_sort(box *boxes, float **probs, int total, int classes, floa...
  function do_nms (line 307) | void do_nms(box *boxes, float **probs, int total, int classes, float thr...
  function box (line 327) | box encode_box(box b, box anchor)
  function box (line 337) | box decode_box(box b, box anchor)

FILE: src/box.h
  type dbox (line 5) | typedef struct{

FILE: src/col2im.c
  function col2im_add_pixel (line 3) | void col2im_add_pixel(float *im, int height, int width, int channels,
  function col2im_cpu (line 14) | void col2im_cpu(float* data_col,

FILE: src/compare.c
  function train_compare (line 10) | void train_compare(char *cfgfile, char *weightfile)
  function validate_compare (line 81) | void validate_compare(char *filename, char *weightfile)
  type sortable_bbox (line 148) | typedef struct {
  function elo_comparator (line 160) | int elo_comparator(const void*a, const void *b)
  function bbox_comparator (line 169) | int bbox_comparator(const void *a, const void *b)
  function bbox_update (line 193) | void bbox_update(sortable_bbox *a, sortable_bbox *b, int class, int result)
  function bbox_fight (line 204) | void bbox_fight(network net, sortable_bbox *a, sortable_bbox *b, int cla...
  function SortMaster3000 (line 227) | void SortMaster3000(char *filename, char *weightfile)
  function BattleRoyaleWithCheese (line 258) | void BattleRoyaleWithCheese(char *filename, char *weightfile)
  function run_compare (line 333) | void run_compare(int argc, char **argv)

FILE: src/connected_layer.c
  function layer (line 14) | layer make_connected_layer(int batch, int inputs, int outputs, ACTIVATIO...
  function update_connected_layer (line 132) | void update_connected_layer(layer l, update_args a)
  function forward_connected_layer (line 151) | void forward_connected_layer(layer l, network net)
  function backward_connected_layer (line 169) | void backward_connected_layer(layer l, network net)
  function denormalize_connected_layer (line 199) | void denormalize_connected_layer(layer l)
  function statistics_connected_layer (line 215) | void statistics_connected_layer(layer l)
  function pull_connected_layer (line 235) | void pull_connected_layer(layer l)
  function push_connected_layer (line 248) | void push_connected_layer(layer l)
  function update_connected_layer_gpu (line 261) | void update_connected_layer_gpu(layer l, update_args a)
  function forward_connected_layer_gpu (line 288) | void forward_connected_layer_gpu(layer l, network net)
  function backward_connected_layer_gpu (line 308) | void backward_connected_layer_gpu(layer l, network net)

FILE: src/convolutional_layer.c
  function swap_binary (line 15) | void swap_binary(convolutional_layer *l)
  function binarize_weights (line 28) | void binarize_weights(float *weights, int n, int size, float *binary)
  function binarize_cpu (line 43) | void binarize_cpu(float *input, int n, float *binary)
  function binarize_input (line 51) | void binarize_input(float *input, int n, int size, float *binary)
  function convolutional_out_height (line 66) | int convolutional_out_height(convolutional_layer l)
  function convolutional_out_width (line 71) | int convolutional_out_width(convolutional_layer l)
  function image (line 76) | image get_convolutional_image(convolutional_layer l)
  function image (line 81) | image get_convolutional_delta(convolutional_layer l)
  function get_workspace_size (line 86) | static size_t get_workspace_size(layer l){
  function cudnn_convolutional_setup (line 123) | void cudnn_convolutional_setup(layer *l)
  function convolutional_layer (line 176) | convolutional_layer make_convolutional_layer(int batch, int h, int w, in...
  function denormalize_convolutional_layer (line 329) | void denormalize_convolutional_layer(convolutional_layer l)
  function resize_convolutional_layer (line 369) | void resize_convolutional_layer(convolutional_layer *l, int w, int h)
  function add_bias (line 410) | void add_bias(float *output, float *biases, int batch, int n, int size)
  function scale_bias (line 422) | void scale_bias(float *output, float *scales, int batch, int n, int size)
  function backward_bias (line 434) | void backward_bias(float *bias_updates, float *delta, int batch, int n, ...
  function forward_convolutional_layer (line 444) | void forward_convolutional_layer(convolutional_layer l, network net)
  function backward_convolutional_layer (line 482) | void backward_convolutional_layer(convolutional_layer l, network net)
  function update_convolutional_layer (line 523) | void update_convolutional_layer(convolutional_layer l, update_args a)
  function image (line 544) | image get_convolutional_weight(convolutional_layer l, int i)
  function rgbgr_weights (line 552) | void rgbgr_weights(convolutional_layer l)
  function rescale_weights (line 563) | void rescale_weights(convolutional_layer l, float scale, float trans)
  function image (line 576) | image *get_weights(convolutional_layer l)
  function image (line 593) | image *visualize_convolutional_layer(convolutional_layer l, char *window...

FILE: src/convolutional_layer.h
  type layer (line 10) | typedef layer convolutional_layer;

FILE: src/cost_layer.c
  function COST_TYPE (line 10) | COST_TYPE get_cost_type(char *s)
  function cost_layer (line 38) | cost_layer make_cost_layer(int batch, int inputs, COST_TYPE cost_type, f...
  function resize_cost_layer (line 65) | void resize_cost_layer(cost_layer *l, int inputs)
  function forward_cost_layer (line 79) | void forward_cost_layer(cost_layer l, network net)
  function backward_cost_layer (line 98) | void backward_cost_layer(const cost_layer l, network net)
  function pull_cost_layer (line 105) | void pull_cost_layer(cost_layer l)
  function push_cost_layer (line 110) | void push_cost_layer(cost_layer l)
  function float_abs_compare (line 115) | int float_abs_compare (const void * a, const void * b)
  function forward_cost_layer_gpu (line 124) | void forward_cost_layer_gpu(cost_layer l, network net)
  function backward_cost_layer_gpu (line 166) | void backward_cost_layer_gpu(const cost_layer l, network net)

FILE: src/cost_layer.h
  type layer (line 6) | typedef layer cost_layer;

FILE: src/crnn_layer.c
  function increment_layer (line 13) | static void increment_layer(layer *l, int steps)
  function layer (line 29) | layer make_crnn_layer(int batch, int h, int w, int c, int hidden_filters...
  function update_crnn_layer (line 84) | void update_crnn_layer(layer l, update_args a)
  function forward_crnn_layer (line 91) | void forward_crnn_layer(layer l, network net)
  function backward_crnn_layer (line 132) | void backward_crnn_layer(layer l, network net)
  function pull_crnn_layer (line 183) | void pull_crnn_layer(layer l)
  function push_crnn_layer (line 190) | void push_crnn_layer(layer l)
  function update_crnn_layer_gpu (line 197) | void update_crnn_layer_gpu(layer l, update_args a)
  function forward_crnn_layer_gpu (line 204) | void forward_crnn_layer_gpu(layer l, network net)
  function backward_crnn_layer_gpu (line 244) | void backward_crnn_layer_gpu(layer l, network net)

FILE: src/crop_layer.c
  function image (line 5) | image get_crop_image(crop_layer l)
  function backward_crop_layer (line 13) | void backward_crop_layer(const crop_layer l, network net){}
  function backward_crop_layer_gpu (line 14) | void backward_crop_layer_gpu(const crop_layer l, network net){}
  function crop_layer (line 16) | crop_layer make_crop_layer(int batch, int h, int w, int c, int crop_heig...
  function resize_crop_layer (line 48) | void resize_crop_layer(layer *l, int w, int h)
  function forward_crop_layer (line 67) | void forward_crop_layer(const crop_layer l, network net)

FILE: src/crop_layer.h
  type layer (line 8) | typedef layer crop_layer;

FILE: src/cuda.c
  function cuda_set_device (line 12) | void cuda_set_device(int n)
  function cuda_get_device (line 19) | int cuda_get_device()
  function check_error (line 27) | void check_error(cudaError_t status)
  function dim3 (line 51) | dim3 cuda_gridsize(size_t n){
  function cudnnHandle_t (line 65) | cudnnHandle_t cudnn_handle()
  function cublasHandle_t (line 78) | cublasHandle_t blas_handle()
  function cuda_random (line 106) | void cuda_random(float *x_gpu, size_t n)
  function cuda_compare (line 120) | float cuda_compare(float *x_gpu, float *x, size_t n, char *s)
  function cuda_free (line 147) | void cuda_free(float *x_gpu)
  function cuda_push_array (line 153) | void cuda_push_array(float *x_gpu, float *x, size_t n)
  function cuda_pull_array (line 160) | void cuda_pull_array(float *x_gpu, float *x, size_t n)
  function cuda_mag_array (line 167) | float cuda_mag_array(float *x_gpu, size_t n)

FILE: src/data.c
  function list (line 12) | list *get_paths(char *filename)
  function matrix (line 68) | matrix load_image_paths_gray(char **paths, int n, int w, int h)
  function matrix (line 89) | matrix load_image_paths(char **paths, int n, int w, int h)
  function matrix (line 105) | matrix load_image_augment_paths(char **paths, int n, int min, int max, i...
  function box_label (line 138) | box_label *read_boxes(char *filename, int *n)
  function randomize_boxes (line 168) | void randomize_boxes(box_label *b, int n)
  function correct_boxes (line 179) | void correct_boxes(box_label *boxes, int n, float dx, float dy, float sx...
  function fill_truth_swag (line 216) | void fill_truth_swag(char *path, float *truth, int classes, int flip, fl...
  function fill_truth_region (line 254) | void fill_truth_region(char *path, float *truth, int classes, int num_bo...
  function load_rle (line 302) | void load_rle(image im, int *rle, int n)
  function or_image (line 318) | void or_image(image src, image dest, int c)
  function exclusive_image (line 326) | void exclusive_image(image src)
  function box (line 341) | box bound_image(image im)
  function fill_truth_iseg (line 363) | void fill_truth_iseg(char *path, int num_boxes, float *truth, int classe...
  function fill_truth_detection (line 408) | void fill_truth_detection(char *path, int num_boxes, float *truth, int c...
  function print_letters (line 448) | void print_letters(float *pred, int n)
  function fill_truth_captcha (line 458) | void fill_truth_captcha(char *path, int n, float *truth)
  function data (line 473) | data load_data_captcha(char **paths, int n, int m, int k, int w, int h)
  function data (line 488) | data load_data_captcha_encode(char **paths, int n, int m, int w, int h)
  function fill_truth (line 500) | void fill_truth(char *path, char **labels, int k, float *truth)
  function fill_hierarchy (line 514) | void fill_hierarchy(float *truth, int k, tree *hierarchy)
  function matrix (line 546) | matrix load_regression_labels_paths(char **paths, int n)
  function matrix (line 564) | matrix load_labels_paths(char **paths, int n, char **labels, int k, tree...
  function matrix (line 577) | matrix load_tags_paths(char **paths, int n, int k)
  function free_data (line 613) | void free_data(data d)
  function image (line 624) | image get_segmentation_image(char *path, int w, int h, int classes)
  function image (line 651) | image get_segmentation_image2(char *path, int w, int h, int classes)
  function data (line 685) | data load_data_seg(int n, char **paths, int m, int w, int h, int classes...
  function data (line 733) | data load_data_iseg(int n, char **paths, int m, int w, int h, int classe...
  function data (line 773) | data load_data_region(int n, char **paths, int m, int w, int h, int size...
  function data (line 827) | data load_data_compare(int n, char **paths, int m, int classes, int w, i...
  function data (line 891) | data load_data_swag(char **paths, int n, int classes, float jitter)
  function data (line 944) | data load_data_detection(int n, char **paths, int m, int w, int h, int b...
  type load_args (line 1000) | struct load_args
  function pthread_t (line 1040) | pthread_t load_data_in_thread(load_args args)
  function load_data_blocking (line 1078) | void load_data_blocking(load_args args)
  function pthread_t (line 1085) | pthread_t load_data(load_args args)
  function data (line 1094) | data load_data_writing(char **paths, int n, int m, int w, int h, int out...
  function data (line 1109) | data load_data_old(char **paths, int n, int m, char **labels, int k, int...
  function data (line 1134) | data load_data_super(char **paths, int n, int m, int w, int h, int scale)
  function data (line 1164) | data load_data_regression(char **paths, int n, int m, int min, int max, ...
  function data (line 1175) | data resize_data(data orig, int w, int h)
  function data (line 1194) | data load_data_augment(char **paths, int n, int m, char **labels, int k,...
  function data (line 1207) | data load_data_tag(char **paths, int n, int m, int k, int min, int max, ...
  function matrix (line 1220) | matrix concat_matrix(matrix m1, matrix m2)
  function data (line 1236) | data concat_data(data d1, data d2)
  function data (line 1245) | data concat_datas(data *d, int n)
  function data (line 1257) | data load_categorical_data_csv(char *filename, int target, int k)
  function data (line 1274) | data load_cifar10_data(char *filename)
  function get_random_batch (line 1301) | void get_random_batch(data d, int n, float *X, float *y)
  function get_next_batch (line 1311) | void get_next_batch(data d, int n, int offset, float *X, float *y)
  function smooth_data (line 1321) | void smooth_data(data d)
  function data (line 1333) | data load_all_cifar10()
  function data (line 1366) | data load_go(char *filename)
  function randomize_data (line 1413) | void randomize_data(data d)
  function scale_data_rows (line 1428) | void scale_data_rows(data d, float s)
  function translate_data_rows (line 1436) | void translate_data_rows(data d, float s)
  function data (line 1444) | data copy_data(data d)
  function normalize_data_rows (line 1457) | void normalize_data_rows(data d)
  function data (line 1465) | data get_data_part(data d, int part, int total)
  function data (line 1478) | data get_random_data(data d, int num)
  function data (line 1501) | data *split_data(data d, int part, int total)

FILE: src/data.h
  function distance_from_edge (line 11) | static inline float distance_from_edge(int x, int max)

FILE: src/deconvolutional_layer.c
  function get_workspace_size (line 14) | static size_t get_workspace_size(layer l){
  function layer (line 19) | layer make_deconvolutional_layer(int batch, int h, int w, int c, int n, ...
  function denormalize_deconvolutional_layer (line 147) | void denormalize_deconvolutional_layer(layer l)
  function resize_deconvolutional_layer (line 162) | void resize_deconvolutional_layer(layer *l, int h, int w)
  function forward_deconvolutional_layer (line 201) | void forward_deconvolutional_layer(const layer l, network net)
  function backward_deconvolutional_layer (line 228) | void backward_deconvolutional_layer(layer l, network net)
  function update_deconvolutional_layer (line 269) | void update_deconvolutional_layer(layer l, update_args a)

FILE: src/demo.c
  function demo (line 118) | void demo(char *cfgfile, char *weightfile, float thresh, int cam_index, ...
  function demo_compare (line 206) | void demo_compare(char *cfg1, char *weight1, char *cfg2, char *weight2, ...
  function demo (line 294) | void demo(char *cfgfile, char *weightfile, float thresh, int cam_index, ...

FILE: src/detection_layer.c
  function detection_layer (line 14) | detection_layer make_detection_layer(int batch, int inputs, int n, int s...
  function forward_detection_layer (line 50) | void forward_detection_layer(const detection_layer l, network net)
  function backward_detection_layer (line 220) | void backward_detection_layer(const detection_layer l, network net)
  function get_detection_boxes (line 225) | void get_detection_boxes(layer l, int w, int h, float thresh, float **pr...
  function forward_detection_layer_gpu (line 256) | void forward_detection_layer_gpu(const detection_layer l, network net)
  function backward_detection_layer_gpu (line 271) | void backward_detection_layer_gpu(detection_layer l, network net)

FILE: src/detection_layer.h
  type layer (line 7) | typedef layer detection_layer;

FILE: src/dropout_layer.c
  function dropout_layer (line 7) | dropout_layer make_dropout_layer(int batch, int inputs, float probability)
  function resize_dropout_layer (line 28) | void resize_dropout_layer(dropout_layer *l, int inputs)
  function forward_dropout_layer (line 38) | void forward_dropout_layer(dropout_layer l, network net)
  function backward_dropout_layer (line 50) | void backward_dropout_layer(dropout_layer l, network net)

FILE: src/dropout_layer.h
  type layer (line 7) | typedef layer dropout_layer;

FILE: src/gemm.c
  function gemm_bin (line 8) | void gemm_bin(int M, int N, int K, float ALPHA,
  function time_random_matrix (line 40) | void time_random_matrix(int TA, int TB, int m, int k, int n)
  function gemm (line 65) | void gemm(int TA, int TB, int M, int N, int K, float ALPHA,
  function gemm_nn (line 74) | void gemm_nn(int M, int N, int K, float ALPHA,
  function gemm_nt (line 91) | void gemm_nt(int M, int N, int K, float ALPHA,
  function gemm_tn (line 109) | void gemm_tn(int M, int N, int K, float ALPHA,
  function gemm_tt (line 126) | void gemm_tt(int M, int N, int K, float ALPHA,
  function gemm_cpu (line 145) | void gemm_cpu(int TA, int TB, int M, int N, int K, float ALPHA,
  function gemm_gpu (line 172) | void gemm_gpu(int TA, int TB, int M, int N, int K, float ALPHA,
  function time_gpu_random_matrix (line 189) | void time_gpu_random_matrix(int TA, int TB, int m, int k, int n)
  function time_gpu (line 213) | void time_gpu(int TA, int TB, int m, int k, int n)
  function test_gpu_accuracy (line 248) | void test_gpu_accuracy(int TA, int TB, int m, int k, int n)
  function test_gpu_blas (line 285) | int test_gpu_blas()

FILE: src/gru_layer.c
  function increment_layer (line 13) | static void increment_layer(layer *l, int steps)
  function layer (line 29) | layer make_gru_layer(int batch, int inputs, int outputs, int steps, int ...
  function update_gru_layer (line 118) | void update_gru_layer(layer l, update_args a)
  function forward_gru_layer (line 128) | void forward_gru_layer(layer l, network net)
  function backward_gru_layer (line 204) | void backward_gru_layer(layer l, network net)
  function pull_gru_layer (line 210) | void pull_gru_layer(layer l)
  function push_gru_layer (line 214) | void push_gru_layer(layer l)
  function update_gru_layer_gpu (line 218) | void update_gru_layer_gpu(layer l, update_args a)
  function forward_gru_layer_gpu (line 228) | void forward_gru_layer_gpu(layer l, network net)
  function backward_gru_layer_gpu (line 302) | void backward_gru_layer_gpu(layer l, network net)

FILE: src/im2col.c
  function im2col_get_pixel (line 3) | float im2col_get_pixel(float *im, int height, int width, int channels,
  function im2col_cpu (line 16) | void im2col_cpu(float* data_im,

FILE: src/image.c
  function get_color (line 17) | float get_color(int c, int x, int max)
  function image (line 28) | image mask_to_rgb(image mask)
  function get_pixel (line 47) | static float get_pixel(image m, int x, int y, int c)
  function get_pixel_extend (line 52) | static float get_pixel_extend(image m, int x, int y, int c)
  function set_pixel (line 64) | static void set_pixel(image m, int x, int y, int c, float val)
  function add_pixel (line 70) | static void add_pixel(image m, int x, int y, int c, float val)
  function bilinear_interpolate (line 76) | static float bilinear_interpolate(image im, float x, float y, int c)
  function composite_image (line 92) | void composite_image(image source, image dest, int dx, int dy)
  function image (line 106) | image border_image(image a, int border)
  function image (line 122) | image tile_images(image a, image b, int dx)
  function image (line 132) | image get_label(image **characters, char *string, int size)
  function draw_label (line 148) | void draw_label(image a, int r, int c, image label, const float *rgb)
  function draw_box (line 165) | void draw_box(image a, int x1, int y1, int x2, int y2, float r, float g,...
  function draw_box_width (line 201) | void draw_box_width(image a, int x1, int y1, int x2, int y2, int w, floa...
  function draw_bbox (line 209) | void draw_bbox(image a, box bbox, int w, float r, float g, float b)
  function image (line 222) | image **load_alphabet()
  function draw_detections (line 238) | void draw_detections(image im, int num, float thresh, box *boxes, float ...
  function transpose_image (line 310) | void transpose_image(image im)
  function rotate_image_cw (line 326) | void rotate_image_cw(image im, int times)
  function flip_image (line 347) | void flip_image(image a)
  function image (line 363) | image image_distance(image a, image b)
  function ghost_image (line 378) | void ghost_image(image source, image dest, int dx, int dy)
  function embed_image (line 397) | void embed_image(image source, image dest, int dx, int dy)
  function image (line 410) | image collapse_image_layers(image source, int border)
  function constrain_image (line 425) | void constrain_image(image im)
  function normalize_image (line 434) | void normalize_image(image p)
  function normalize_image2 (line 454) | void normalize_image2(image p)
  function copy_image_into (line 483) | void copy_image_into(image src, image dest)
  function image (line 488) | image copy_image(image p)
  function rgbgr_image (line 496) | void rgbgr_image(image im)
  function show_image_cv (line 507) | void show_image_cv(image p, const char *name, IplImage *disp)
  function show_image (line 544) | void show_image(image p, const char *name)
  function ipl_into_image (line 561) | void ipl_into_image(IplImage* src, image im)
  function image (line 579) | image ipl_to_image(IplImage* src)
  function image (line 589) | image load_image_cv(char *filename, int channels)
  function flush_stream_buffer (line 615) | void flush_stream_buffer(CvCapture *cap, int n)
  function image (line 623) | image get_image_from_stream(CvCapture *cap)
  function fill_image_from_stream (line 632) | int fill_image_from_stream(CvCapture *cap, image im)
  function save_image_jpg (line 641) | void save_image_jpg(image p, const char *name)
  function save_image_png (line 665) | void save_image_png(image im, const char *name)
  function save_image (line 682) | void save_image(image im, const char *name)
  function show_image_layers (line 692) | void show_image_layers(image p, char *name)
  function show_image_collapsed (line 704) | void show_image_collapsed(image p, char *name)
  function image (line 711) | image make_empty_image(int w, int h, int c)
  function image (line 721) | image make_image(int w, int h, int c)
  function image (line 728) | image make_random_image(int w, int h, int c)
  function image (line 739) | image float_to_image(int w, int h, int c, float *data)
  function place_image (line 746) | void place_image(image im, int w, int h, int dx, int dy, image canvas)
  function image (line 761) | image center_crop_image(image im, int w, int h)
  function image (line 770) | image rotate_crop_image(image im, float rad, float s, int w, int h, floa...
  function image (line 789) | image rotate_image(image im, float rad)
  function fill_image (line 808) | void fill_image(image m, float s)
  function translate_image (line 814) | void translate_image(image m, float s)
  function scale_image (line 820) | void scale_image(image m, float s)
  function image (line 826) | image crop_image(image im, int dx, int dy, int w, int h)
  function best_3d_shift_r (line 846) | int best_3d_shift_r(image a, image b, int min, int max)
  function best_3d_shift (line 860) | int best_3d_shift(image a, image b, int min, int max)
  function composite_3d (line 878) | void composite_3d(char *f1, char *f2, char *out, int delta)
  function letterbox_image_into (line 913) | void letterbox_image_into(image im, int w, int h, image boxed)
  function image (line 929) | image letterbox_image(image im, int w, int h)
  function image (line 950) | image resize_max(image im, int max)
  function image (line 966) | image resize_min(image im, int min)
  function image (line 982) | image random_crop_image(image im, int w, int h)
  function augment_args (line 990) | augment_args random_augment_args(image im, float angle, float aspect, in...
  function image (line 1017) | image random_augment_image(image im, float angle, float aspect, int low,...
  function three_way_max (line 1024) | float three_way_max(float a, float b, float c)
  function three_way_min (line 1029) | float three_way_min(float a, float b, float c)
  function yuv_to_rgb (line 1034) | void yuv_to_rgb(image im)
  function rgb_to_yuv (line 1057) | void rgb_to_yuv(image im)
  function rgb_to_hsv (line 1081) | void rgb_to_hsv(image im)
  function hsv_to_rgb (line 1118) | void hsv_to_rgb(image im)
  function grayscale_image_3c (line 1159) | void grayscale_image_3c(image im)
  function image (line 1177) | image grayscale_image(image im)
  function image (line 1193) | image threshold_image(image im, float thresh)
  function image (line 1203) | image blend_image(image fore, image back, float alpha)
  function scale_image_channel (line 1220) | void scale_image_channel(image im, int c, float v)
  function translate_image_channel (line 1232) | void translate_image_channel(image im, int c, float v)
  function image (line 1244) | image binarize_image(image im)
  function saturate_image (line 1255) | void saturate_image(image im, float sat)
  function hue_image (line 1263) | void hue_image(image im, float hue)
  function exposure_image (line 1276) | void exposure_image(image im, float sat)
  function distort_image (line 1284) | void distort_image(image im, float hue, float sat, float val)
  function random_distort_image (line 1299) | void random_distort_image(image im, float hue, float saturation, float e...
  function saturate_exposure_image (line 1307) | void saturate_exposure_image(image im, float sat, float exposure)
  function image (line 1316) | image resize_image(image im, int w, int h)
  function test_resize (line 1361) | void test_resize(char *filename)
  function image (line 1411) | image load_image_stb(char *filename, int channels)
  function image (line 1435) | image load_image(char *filename, int w, int h, int c)
  function image (line 1451) | image load_image_color(char *filename, int w, int h)
  function image (line 1456) | image get_image_layer(image m, int l)
  function print_image (line 1465) | void print_image(image m)
  function image (line 1482) | image collapse_images_vert(image *ims, int n)
  function image (line 1517) | image collapse_images_horz(image *ims, int n)
  function show_image_normalized (line 1553) | void show_image_normalized(image im, const char *name)
  function show_images (line 1561) | void show_images(image *ims, int n, char *window)
  function free_image (line 1579) | void free_image(image m)

FILE: src/layer.c
  function free_layer (line 6) | void free_layer(layer l)

FILE: src/list.c
  function list (line 5) | list *make_list()
  function list_insert (line 40) | void list_insert(list *l, void *val)
  function free_node (line 57) | void free_node(node *n)
  function free_list (line 67) | void free_list(list *l)
  function free_list_contents (line 73) | void free_list_contents(list *l)

FILE: src/local_layer.c
  function local_out_height (line 10) | int local_out_height(local_layer l)
  function local_out_width (line 18) | int local_out_width(local_layer l)
  function local_layer (line 26) | local_layer make_local_layer(int batch, int h, int w, int c, int n, int ...
  function forward_local_layer (line 91) | void forward_local_layer(const local_layer l, network net)
  function backward_local_layer (line 122) | void backward_local_layer(local_layer l, network net)
  function update_local_layer (line 167) | void update_local_layer(local_layer l, update_args a)
  function forward_local_layer_gpu (line 186) | void forward_local_layer_gpu(const local_layer l, network net)
  function backward_local_layer_gpu (line 217) | void backward_local_layer_gpu(local_layer l, network net)
  function update_local_layer_gpu (line 261) | void update_local_layer_gpu(local_layer l, update_args a)
  function pull_local_layer (line 278) | void pull_local_layer(local_layer l)
  function push_local_layer (line 286) | void push_local_layer(local_layer l)

FILE: src/local_layer.h
  type layer (line 10) | typedef layer local_layer;

FILE: src/lstm_layer.c
  function increment_layer (line 13) | static void increment_layer(layer *l, int steps)
  function layer (line 29) | layer make_lstm_layer(int batch, int inputs, int outputs, int steps, int...
  function update_lstm_layer (line 144) | void update_lstm_layer(layer l, update_args a)
  function forward_lstm_layer (line 156) | void forward_lstm_layer(layer l, network state)
  function backward_lstm_layer (line 242) | void backward_lstm_layer(layer l, network state)
  function update_lstm_layer_gpu (line 386) | void update_lstm_layer_gpu(layer l, update_args a)
  function forward_lstm_layer_gpu (line 398) | void forward_lstm_layer_gpu(layer l, network state)
  function backward_lstm_layer_gpu (line 484) | void backward_lstm_layer_gpu(layer l, network state)

FILE: src/matrix.c
  function free_matrix (line 10) | void free_matrix(matrix m)
  function matrix_topk_accuracy (line 17) | float matrix_topk_accuracy(matrix truth, matrix guess, int k)
  function scale_matrix (line 37) | void scale_matrix(matrix m, float scale)
  function matrix (line 47) | matrix resize_matrix(matrix m, int size)
  function matrix_add_matrix (line 66) | void matrix_add_matrix(matrix from, matrix to)
  function matrix (line 77) | matrix copy_matrix(matrix m)
  function matrix (line 91) | matrix make_matrix(int rows, int cols)
  function matrix (line 104) | matrix hold_out_matrix(matrix *m, int n)
  function matrix (line 133) | matrix csv_to_matrix(char *filename)
  function matrix_to_csv (line 161) | void matrix_to_csv(matrix m)
  function print_matrix (line 174) | void print_matrix(matrix m)

FILE: src/maxpool_layer.c
  function image (line 5) | image get_maxpool_image(maxpool_layer l)
  function image (line 13) | image get_maxpool_delta(maxpool_layer l)
  function maxpool_layer (line 21) | maxpool_layer make_maxpool_layer(int batch, int h, int w, int c, int siz...
  function resize_maxpool_layer (line 54) | void resize_maxpool_layer(maxpool_layer *l, int w, int h)
  function forward_maxpool_layer (line 79) | void forward_maxpool_layer(const maxpool_layer l, network net)
  function backward_maxpool_layer (line 116) | void backward_maxpool_layer(const maxpool_layer l, network net)

FILE: src/maxpool_layer.h
  type layer (line 9) | typedef layer maxpool_layer;

FILE: src/network.c
  function load_args (line 33) | load_args get_base_args(network *net)
  function network (line 51) | network *load_network(char *cfg, char *weights, int clear)
  function get_current_batch (line 61) | size_t get_current_batch(network *net)
  function reset_network_state (line 67) | void reset_network_state(network *net, int b)
  function reset_rnn (line 83) | void reset_rnn(network *net)
  function get_current_rate (line 88) | float get_current_rate(network *net)
  function network (line 173) | network *make_network(int n)
  function forward_network (line 184) | void forward_network(network *netp)
  function update_network (line 209) | void update_network(network *netp)
  function calc_network_cost (line 239) | void calc_network_cost(network *netp)
  function get_predicted_class_network (line 254) | int get_predicted_class_network(network *net)
  function backward_network (line 259) | void backward_network(network *netp)
  function train_network_datum (line 285) | float train_network_datum(network *net)
  function train_network_sgd (line 296) | float train_network_sgd(network *net, data d, int n)
  function train_network (line 310) | float train_network(network *net, data d)
  function set_temp_network (line 326) | void set_temp_network(network *net, float t)
  function set_batch_network (line 335) | void set_batch_network(network *net, int b)
  function resize_network (line 354) | int resize_network(network *net, int w, int h)
  function layer (line 427) | layer get_network_detection_layer(network *net)
  function image (line 440) | image get_network_image_layer(network *net, int i)
  function image (line 453) | image get_network_image(network *net)
  function visualize_network (line 464) | void visualize_network(network *net)
  function top_predictions (line 478) | void top_predictions(network *net, int k, int *index)
  function num_boxes (line 497) | int num_boxes(network *net)
  function box (line 503) | box *make_boxes(network *net)
  function network_detect (line 519) | void network_detect(network *net, image im, float thresh, float hier_thr...
  function network_width (line 538) | int network_width(network *net){return net->w;}
  function network_height (line 539) | int network_height(network *net){return net->h;}
  function matrix (line 541) | matrix network_predict_data_multi(network *net, data test, int n)
  function matrix (line 566) | matrix network_predict_data(network *net, data test)
  function print_network (line 589) | void print_network(network *net)
  function compare_networks (line 606) | void compare_networks(network *n1, network *n2, data test)
  function network_accuracy (line 631) | float network_accuracy(network *net, data d)
  function layer (line 649) | layer get_network_output_layer(network *net)
  function network_accuracy_multi (line 658) | float network_accuracy_multi(network *net, data d, int n)
  function free_network (line 666) | void free_network(network *net)
  function layer (line 686) | layer network_output_layer(network *net)
  function network_inputs (line 695) | int network_inputs(network *net)
  function network_outputs (line 700) | int network_outputs(network *net)
  function forward_network_gpu (line 712) | void forward_network_gpu(network *netp)
  function backward_network_gpu (line 740) | void backward_network_gpu(network *netp)
  function update_network_gpu (line 763) | void update_network_gpu(network *netp)
  function harmless_update_network_gpu (line 788) | void harmless_update_network_gpu(network *netp)
  type train_args (line 801) | typedef struct {
  function pthread_t (line 816) | pthread_t train_network_in_thread(network *net, data d, float *err)
  function merge_weights (line 827) | void merge_weights(layer l, layer base)
  function scale_weights (line 841) | void scale_weights(layer l, float s)
  function pull_weights (line 856) | void pull_weights(layer l)
  function push_weights (line 868) | void push_weights(layer l)
  function distribute_weights (line 880) | void distribute_weights(layer l, layer base)
  function sync_layer (line 977) | void sync_layer(network **nets, int n, int j)
  type sync_args (line 997) | typedef struct{
  function pthread_t (line 1011) | pthread_t sync_layer_in_thread(network **nets, int n, int j)
  function sync_nets (line 1022) | void sync_nets(network **nets, int n, int interval)
  function train_networks (line 1041) | float train_networks(network **nets, int n, data d, int interval)
  function pull_network_output (line 1073) | void pull_network_output(network *net)

FILE: src/normalization_layer.c
  function layer (line 6) | layer make_normalization_layer(int batch, int w, int h, int c, int size,...
  function resize_normalization_layer (line 40) | void resize_normalization_layer(layer *layer, int w, int h)
  function forward_normalization_layer (line 66) | void forward_normalization_layer(const layer layer, network net)
  function backward_normalization_layer (line 97) | void backward_normalization_layer(const layer layer, network net)
  function forward_normalization_layer_gpu (line 110) | void forward_normalization_layer_gpu(const layer layer, network net)
  function backward_normalization_layer_gpu (line 141) | void backward_normalization_layer_gpu(const layer layer, network net)

FILE: src/option_list.c
  function list (line 7) | list *read_data_cfg(char *filename)
  function metadata (line 35) | metadata get_metadata(char *file)
  function read_option (line 52) | int read_option(char *s, list *options)
  function option_insert (line 70) | void option_insert(list *l, char *key, char *val)
  function option_unused (line 79) | void option_unused(list *l)
  function option_find_int (line 112) | int option_find_int(list *l, char *key, int def)
  function option_find_int_quiet (line 120) | int option_find_int_quiet(list *l, char *key, int def)
  function option_find_float_quiet (line 127) | float option_find_float_quiet(list *l, char *key, float def)
  function option_find_float (line 134) | float option_find_float(list *l, char *key, float def)

FILE: src/option_list.h
  type kvp (line 5) | typedef struct{

FILE: src/parser.c
  type section (line 35) | typedef struct{
  function LAYER_TYPE (line 42) | LAYER_TYPE string_to_layer_type(char * type)
  function free_section (line 79) | void free_section(section *s)
  function parse_data (line 95) | void parse_data(char *data, float *a, int n)
  type size_params (line 111) | typedef struct size_params{
  function local_layer (line 122) | local_layer parse_local(list *options, size_params params)
  function layer (line 143) | layer parse_deconvolutional(list *options, size_params params)
  function convolutional_layer (line 169) | convolutional_layer parse_convolutional(list *options, size_params params)
  function layer (line 199) | layer parse_crnn(list *options, size_params params)
  function layer (line 214) | layer parse_rnn(list *options, size_params params)
  function layer (line 228) | layer parse_gru(list *options, size_params params)
  function layer (line 239) | layer parse_lstm(list *options, size_params params)
  function layer (line 249) | layer parse_connected(list *options, size_params params)
  function softmax_layer (line 260) | softmax_layer parse_softmax(list *options, size_params params)
  function layer (line 274) | layer parse_region(list *options, size_params params)
  function detection_layer (line 325) | detection_layer parse_detection(list *options, size_params params)
  function cost_layer (line 349) | cost_layer parse_cost(list *options, size_params params)
  function crop_layer (line 361) | crop_layer parse_crop(list *options, size_params params)
  function layer (line 385) | layer parse_reorg(list *options, size_params params)
  function maxpool_layer (line 403) | maxpool_layer parse_maxpool(list *options, size_params params)
  function avgpool_layer (line 420) | avgpool_layer parse_avgpool(list *options, size_params params)
  function dropout_layer (line 433) | dropout_layer parse_dropout(list *options, size_params params)
  function layer (line 443) | layer parse_normalization(list *options, size_params params)
  function layer (line 453) | layer parse_batchnorm(list *options, size_params params)
  function layer (line 459) | layer parse_shortcut(list *options, size_params params, network *net)
  function layer (line 477) | layer parse_activation(list *options, size_params params)
  function route_layer (line 494) | route_layer parse_route(list *options, size_params params, network *net)
  function learning_rate_policy (line 535) | learning_rate_policy get_policy(char *s)
  function parse_net_options (line 548) | void parse_net_options(list *options, network *net)
  function is_network (line 628) | int is_network(section *s)
  function network (line 634) | network *parse_network_cfg(char *filename)
  function list (line 770) | list *read_cfg(char *filename)
  function save_convolutional_weights_binary (line 805) | void save_convolutional_weights_binary(layer l, FILE *fp)
  function save_convolutional_weights (line 837) | void save_convolutional_weights(layer l, FILE *fp)
  function save_batchnorm_weights (line 858) | void save_batchnorm_weights(layer l, FILE *fp)
  function save_connected_weights (line 870) | void save_connected_weights(layer l, FILE *fp)
  function save_weights_upto (line 886) | void save_weights_upto(network *net, char *filename, int cutoff)
  function save_weights (line 958) | void save_weights(network *net, char *filename)
  function transpose_matrix (line 963) | void transpose_matrix(float *a, int rows, int cols)
  function load_connected_weights (line 976) | void load_connected_weights(layer l, FILE *fp, int transpose)
  function load_batchnorm_weights (line 1000) | void load_batchnorm_weights(layer l, FILE *fp)
  function load_convolutional_weights_binary (line 1012) | void load_convolutional_weights_binary(layer l, FILE *fp)
  function load_convolutional_weights (line 1042) | void load_convolutional_weights(layer l, FILE *fp)
  function load_weights_upto (line 1095) | void load_weights_upto(network *net, char *filename, int start, int cutoff)
  function load_weights (line 1185) | void load_weights(network *net, char *filename)

FILE: src/region_layer.c
  function layer (line 13) | layer make_region_layer(int batch, int w, int h, int n, int classes, int...
  function resize_region_layer (line 56) | void resize_region_layer(layer *l, int w, int h)
  function box (line 76) | box get_region_box(float *x, float *biases, int n, int index, int i, int...
  function delta_region_box (line 86) | float delta_region_box(box truth, float *x, float *biases, int n, int in...
  function delta_region_mask (line 103) | void delta_region_mask(float *truth, float *x, int n, int index, float *...
  function delta_region_class (line 112) | void delta_region_class(float *output, float *delta, int index, int clas...
  function logit (line 141) | float logit(float x)
  function tisnan (line 146) | float tisnan(float x)
  function entry_index (line 151) | int entry_index(layer l, int batch, int location, int entry)
  function forward_region_layer (line 158) | void forward_region_layer(const layer l, network net)
  function backward_region_layer (line 329) | void backward_region_layer(const layer l, network net)
  function correct_region_boxes (line 342) | void correct_region_boxes(box *boxes, int n, int w, int h, int netw, int...
  function get_region_boxes (line 370) | void get_region_boxes(layer l, int w, int h, int netw, int neth, float t...
  function forward_region_layer_gpu (line 461) | void forward_region_layer_gpu(const layer l, network net)
  function backward_region_layer_gpu (line 570) | void backward_region_layer_gpu(const layer l, network net)
  function zero_objectness (line 589) | void zero_objectness(layer l)

FILE: src/reorg_layer.c
  function layer (line 8) | layer make_reorg_layer(int batch, int w, int h, int c, int stride, int r...
  function resize_reorg_layer (line 58) | void resize_reorg_layer(layer *l, int w, int h)
  function forward_reorg_layer (line 91) | void forward_reorg_layer(const layer l, network net)
  function backward_reorg_layer (line 112) | void backward_reorg_layer(const layer l, network net)
  function forward_reorg_layer_gpu (line 134) | void forward_reorg_layer_gpu(layer l, network net)
  function backward_reorg_layer_gpu (line 154) | void backward_reorg_layer_gpu(layer l, network net)

FILE: src/rnn_layer.c
  function increment_layer (line 13) | static void increment_layer(layer *l, int steps)
  function layer (line 29) | layer make_rnn_layer(int batch, int inputs, int outputs, int steps, ACTI...
  function update_rnn_layer (line 82) | void update_rnn_layer(layer l, update_args a)
  function forward_rnn_layer (line 89) | void forward_rnn_layer(layer l, network net)
  function backward_rnn_layer (line 130) | void backward_rnn_layer(layer l, network net)
  function pull_rnn_layer (line 182) | void pull_rnn_layer(layer l)
  function push_rnn_layer (line 189) | void push_rnn_layer(layer l)
  function update_rnn_layer_gpu (line 196) | void update_rnn_layer_gpu(layer l, update_args a)
  function forward_rnn_layer_gpu (line 203) | void forward_rnn_layer_gpu(layer l, network net)
  function backward_rnn_layer_gpu (line 242) | void backward_rnn_layer_gpu(layer l, network net)

FILE: src/route_layer.c
  function route_layer (line 7) | route_layer make_route_layer(int batch, int n, int *input_layers, int *i...
  function resize_route_layer (line 40) | void resize_route_layer(route_layer *l, network *net)
  function forward_route_layer (line 74) | void forward_route_layer(const route_layer l, network net)
  function backward_route_layer (line 89) | void backward_route_layer(const route_layer l, network net)
  function forward_route_layer_gpu (line 105) | void forward_route_layer_gpu(const route_layer l, network net)
  function backward_route_layer_gpu (line 120) | void backward_route_layer_gpu(const route_layer l, network net)

FILE: src/route_layer.h
  type layer (line 6) | typedef layer route_layer;

FILE: src/shortcut_layer.c
  function layer (line 9) | layer make_shortcut_layer(int batch, int index, int w, int h, int c, int...
  function forward_shortcut_layer (line 41) | void forward_shortcut_layer(const layer l, network net)
  function backward_shortcut_layer (line 48) | void backward_shortcut_layer(const layer l, network net)
  function forward_shortcut_layer_gpu (line 56) | void forward_shortcut_layer_gpu(const layer l, network net)
  function backward_shortcut_layer_gpu (line 63) | void backward_shortcut_layer_gpu(const layer l, network net)

FILE: src/softmax_layer.c
  function softmax_layer (line 11) | softmax_layer make_softmax_layer(int batch, int inputs, int groups)
  function forward_softmax_layer (line 36) | void forward_softmax_layer(const softmax_layer l, network net)
  function backward_softmax_layer (line 51) | void backward_softmax_layer(const softmax_layer l, network net)
  function pull_softmax_layer_output (line 58) | void pull_softmax_layer_output(const softmax_layer layer)
  function forward_softmax_layer_gpu (line 63) | void forward_softmax_layer_gpu(const softmax_layer l, network net)
  function backward_softmax_layer_gpu (line 82) | void backward_softmax_layer_gpu(const softmax_layer layer, network net)

FILE: src/softmax_layer.h
  type layer (line 6) | typedef layer softmax_layer;

FILE: src/stb_image.h
  type stbi_uc (line 403) | typedef unsigned char stbi_uc;
  type stbi_io_callbacks (line 424) | typedef struct
  type stbi__uint16 (line 591) | typedef unsigned short stbi__uint16;
  type stbi__int16 (line 592) | typedef   signed short stbi__int16;
  type stbi__uint32 (line 593) | typedef unsigned int   stbi__uint32;
  type stbi__int32 (line 594) | typedef   signed int   stbi__int32;
  type stbi__uint16 (line 597) | typedef uint16_t stbi__uint16;
  type stbi__int16 (line 598) | typedef int16_t  stbi__int16;
  type stbi__uint32 (line 599) | typedef uint32_t stbi__uint32;
  type stbi__int32 (line 600) | typedef int32_t  stbi__int32;
  function stbi__cpuid3 (line 675) | static int stbi__cpuid3(void)
  function stbi__sse2_available (line 696) | static int stbi__sse2_available()
  function stbi__sse2_available (line 704) | static int stbi__sse2_available()
  type stbi__context (line 739) | typedef struct
  function stbi__start_mem (line 759) | static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int...
  function stbi__start_callbacks (line 768) | static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c...
  function stbi__stdio_read (line 780) | static int stbi__stdio_read(void *user, char *data, int size)
  function stbi__stdio_skip (line 785) | static void stbi__stdio_skip(void *user, int n)
  function stbi__stdio_eof (line 790) | static int stbi__stdio_eof(void *user)
  function stbi__start_file (line 802) | static void stbi__start_file(stbi__context *s, FILE *f)
  function stbi__rewind (line 811) | static void stbi__rewind(stbi__context *s)
  function STBIDEF (line 876) | STBIDEF const char *stbi_failure_reason(void)
  function stbi__err (line 881) | static int stbi__err(const char *str)
  function STBIDEF (line 907) | STBIDEF void stbi_image_free(void *retval_from_stbi_load)
  function STBIDEF (line 922) | STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip)
  function stbi__float_postprocess (line 992) | static void stbi__float_postprocess(float *result, int *x, int *y, int *...
  function FILE (line 1016) | static FILE *stbi__fopen(char const *filename, char const *mode)
  function STBIDEF (line 1029) | STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *co...
  function STBIDEF (line 1039) | STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp,...
  function STBIDEF (line 1053) | STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, i...
  function STBIDEF (line 1060) | STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk,...
  function STBIDEF (line 1085) | STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, in...
  function STBIDEF (line 1092) | STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, ...
  function STBIDEF (line 1100) | STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *com...
  function STBIDEF (line 1110) | STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, ...
  function STBIDEF (line 1124) | STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
  function STBIDEF (line 1138) | STBIDEF int      stbi_is_hdr          (char const *filename)
  function STBIDEF (line 1149) | STBIDEF int      stbi_is_hdr_from_file(FILE *f)
  function STBIDEF (line 1161) | STBIDEF int      stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clb...
  function STBIDEF (line 1176) | STBIDEF void   stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = ga...
  function STBIDEF (line 1177) | STBIDEF void   stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = sc...
  function STBIDEF (line 1180) | STBIDEF void   stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = ...
  function STBIDEF (line 1181) | STBIDEF void   stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = ...
  function stbi__refill_buffer (line 1196) | static void stbi__refill_buffer(stbi__context *s)
  function stbi_inline (line 1212) | stbi_inline static stbi_uc stbi__get8(stbi__context *s)
  function stbi_inline (line 1223) | stbi_inline static int stbi__at_eof(stbi__context *s)
  function stbi__skip (line 1235) | static void stbi__skip(stbi__context *s, int n)
  function stbi__getn (line 1252) | static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)
  function stbi__get16be (line 1276) | static int stbi__get16be(stbi__context *s)
  function stbi__uint32 (line 1282) | static stbi__uint32 stbi__get32be(stbi__context *s)
  function stbi__get16le (line 1288) | static int stbi__get16le(stbi__context *s)
  function stbi__uint32 (line 1294) | static stbi__uint32 stbi__get32le(stbi__context *s)
  function stbi_uc (line 1314) | static stbi_uc stbi__compute_y(int r, int g, int b)
  function stbi_uc (line 1384) | static stbi_uc *stbi__hdr_to_ldr(float   *data, int x, int y, int comp)
  type stbi__huffman (line 1436) | typedef struct
  type stbi__jpeg (line 1447) | typedef struct
  function stbi__build_huffman (line 1498) | static int stbi__build_huffman(stbi__huffman *h, int *count)
  function stbi__build_fast_ac (line 1541) | static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h)
  function stbi__grow_buffer_unsafe (line 1566) | static void stbi__grow_buffer_unsafe(stbi__jpeg *j)
  function stbi_inline (line 1587) | stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffm...
  function stbi_inline (line 1641) | stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)
  function stbi_inline (line 1657) | stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n)
  function stbi_inline (line 1668) | stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j)
  function stbi__jpeg_decode_block (line 1696) | static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__...
  function stbi__jpeg_decode_block_prog_dc (line 1748) | static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64]...
  function stbi__jpeg_decode_block_prog_ac (line 1775) | static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64]...
  function stbi_inline (line 1895) | stbi_inline static stbi_uc stbi__clamp(int x)
  function stbi__idct_block (line 1946) | static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64])
  function stbi__idct_simd (line 2009) | static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
  function stbi__idct_simd (line 2190) | static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
  function stbi_uc (line 2398) | static stbi_uc stbi__get_marker(stbi__jpeg *j)
  function stbi__jpeg_reset (line 2415) | static void stbi__jpeg_reset(stbi__jpeg *j)
  function stbi__parse_entropy_coded_data (line 2428) | static int stbi__parse_entropy_coded_data(stbi__jpeg *z)
  function stbi__jpeg_dequantize (line 2552) | static void stbi__jpeg_dequantize(short *data, stbi_uc *dequant)
  function stbi__jpeg_finish (line 2559) | static void stbi__jpeg_finish(stbi__jpeg *z)
  function stbi__process_marker (line 2578) | static int stbi__process_marker(stbi__jpeg *z, int m)
  function stbi__process_scan_header (line 2642) | static int stbi__process_scan_header(stbi__jpeg *z)
  function stbi__process_frame_header (line 2681) | static int stbi__process_frame_header(stbi__jpeg *z, int scan)
  function stbi__decode_jpeg_header (line 2772) | static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan)
  function stbi__decode_jpeg_image (line 2795) | static int stbi__decode_jpeg_image(stbi__jpeg *j)
  type stbi_uc (line 2834) | typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_u...
  function stbi_uc (line 2839) | static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *...
  function stbi_uc (line 2848) | static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, s...
  function stbi_uc (line 2858) | static stbi_uc*  stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, ...
  function stbi_uc (line 2888) | static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, ...
  function stbi_uc (line 2913) | static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_n...
  function stbi_uc (line 3029) | static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_nea...
  function stbi__YCbCr_to_RGB_row (line 3044) | static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const...
  function stbi__YCbCr_to_RGB_row (line 3072) | static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const...
  function stbi__YCbCr_to_RGB_simd (line 3099) | static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi...
  function stbi__setup_jpeg (line 3234) | static void stbi__setup_jpeg(stbi__jpeg *j)
  function stbi__cleanup_jpeg (line 3260) | static void stbi__cleanup_jpeg(stbi__jpeg *j)
  type stbi__resample (line 3281) | typedef struct
  function stbi_uc (line 3291) | static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, i...
  function stbi__jpeg_test (line 3396) | static int stbi__jpeg_test(stbi__context *s)
  function stbi__jpeg_info_raw (line 3407) | static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp)
  function stbi__jpeg_info (line 3419) | static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)
  type stbi__zhuffman (line 3442) | typedef struct
  function stbi_inline (line 3452) | stbi_inline static int stbi__bitreverse16(int n)
  function stbi_inline (line 3461) | stbi_inline static int stbi__bit_reverse(int v, int bits)
  function stbi__zbuild_huffman (line 3469) | static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, in...
  type stbi__zbuf (line 3522) | typedef struct
  function stbi_inline (line 3536) | stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z)
  function stbi__fill_bits (line 3542) | static void stbi__fill_bits(stbi__zbuf *z)
  function stbi__zreceive (line 3551) | int stbi__zreceive(stbi__zbuf *z, int n)
  function stbi__zhuffman_decode_slowpath (line 3561) | static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z)
  function stbi_inline (line 3579) | stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffm...
  function stbi__zexpand (line 3593) | static int stbi__zexpand(stbi__zbuf *z, char *zout, int n)  // need to m...
  function stbi__parse_huffman_block (line 3625) | static int stbi__parse_huffman_block(stbi__zbuf *a)
  function stbi__compute_huffman_codes (line 3667) | static int stbi__compute_huffman_codes(stbi__zbuf *a)
  function stbi__parse_uncomperssed_block (line 3713) | static int stbi__parse_uncomperssed_block(stbi__zbuf *a)
  function stbi__parse_zlib_header (line 3742) | static int stbi__parse_zlib_header(stbi__zbuf *a)
  function stbi__init_zdefaults (line 3757) | static void stbi__init_zdefaults(void)
  function stbi__parse_zlib (line 3768) | static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)
  function stbi__do_zlib (line 3797) | static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, i...
  function STBIDEF (line 3807) | STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int ...
  function STBIDEF (line 3823) | STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *...
  function STBIDEF (line 3828) | STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *b...
  function STBIDEF (line 3844) | STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const ...
  function STBIDEF (line 3855) | STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int l...
  function STBIDEF (line 3871) | STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, co...
  type stbi__pngchunk (line 3894) | typedef struct
  function stbi__pngchunk (line 3900) | static stbi__pngchunk stbi__get_chunk_header(stbi__context *s)
  function stbi__check_png_header (line 3908) | static int stbi__check_png_header(stbi__context *s)
  type stbi__png (line 3917) | typedef struct
  function stbi__paeth (line 3944) | static int stbi__paeth(int a, int b, int c)
  function stbi__create_png_image_raw (line 3958) | static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__...
  function stbi__create_png_image (line 4136) | static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stb...
  function stbi__compute_transparency (line 4178) | static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int o...
  function stbi__expand_png_palette (line 4203) | static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int ...
  function STBIDEF (line 4243) | STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpr...
  function STBIDEF (line 4248) | STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_conv...
  function stbi__de_iphone (line 4253) | static void stbi__de_iphone(stbi__png *z)
  function stbi__parse_png_file (line 4297) | static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
  function stbi__png_test (line 4484) | static int stbi__png_test(stbi__context *s)
  function stbi__png_info_raw (line 4492) | static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)
  function stbi__png_info (line 4504) | static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)
  function stbi__bmp_test_raw (line 4515) | static int stbi__bmp_test_raw(stbi__context *s)
  function stbi__bmp_test (line 4530) | static int stbi__bmp_test(stbi__context *s)
  function stbi__high_bit (line 4539) | static int stbi__high_bit(unsigned int z)
  function stbi__bitcount (line 4551) | static int stbi__bitcount(unsigned int a)
  function stbi__shiftsigned (line 4561) | static int stbi__shiftsigned(int v, int shift, int bits)
  function stbi_uc (line 4578) | static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *co...
  function stbi__tga_info (line 4784) | static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp)
  function stbi__tga_test (line 4821) | static int stbi__tga_test(stbi__context *s)
  function stbi_uc (line 4846) | static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *co...
  function stbi__psd_test (line 5045) | static int stbi__psd_test(stbi__context *s)
  function stbi_uc (line 5052) | static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *co...
  function stbi__pic_is4 (line 5221) | static int stbi__pic_is4(stbi__context *s,const char *str)
  function stbi__pic_test_core (line 5231) | static int stbi__pic_test_core(stbi__context *s)
  type stbi__pic_packet (line 5247) | typedef struct
  function stbi_uc (line 5252) | static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest)
  function stbi__copyval (line 5266) | static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src)
  function stbi_uc (line 5275) | static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int heigh...
  function stbi_uc (line 5386) | static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *com...
  function stbi__pic_test (line 5419) | static int stbi__pic_test(stbi__context *s)
  type stbi__gif_lzw (line 5431) | typedef struct
  type stbi__gif (line 5438) | typedef struct
  function stbi__gif_test_raw (line 5455) | static int stbi__gif_test_raw(stbi__context *s)
  function stbi__gif_test (line 5465) | static int stbi__gif_test(stbi__context *s)
  function stbi__gif_parse_colortable (line 5472) | static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256...
  function stbi__gif_header (line 5483) | static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, i...
  function stbi__gif_info_raw (line 5511) | static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)
  function stbi__out_gif_code (line 5523) | static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code)
  function stbi_uc (line 5557) | static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g)
  function stbi__fill_gif_background (line 5637) | static void stbi__fill_gif_background(stbi__gif *g)
  function stbi_uc (line 5652) | static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int ...
  function stbi_uc (line 5752) | static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *co...
  function stbi__gif_info (line 5768) | static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp)
  function stbi__hdr_test_core (line 5778) | static int stbi__hdr_test_core(stbi__context *s)
  function stbi__hdr_test (line 5788) | static int stbi__hdr_test(stbi__context* s)
  function stbi__hdr_convert (line 5818) | static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp)
  function stbi__hdr_info (line 5956) | static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp)
  function stbi__bmp_info (line 5997) | static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)
  function stbi__psd_info (line 6027) | static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp)
  function stbi__pic_info (line 6060) | static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)
  function stbi__pnm_test (line 6120) | static int      stbi__pnm_test(stbi__context *s)
  function stbi_uc (line 6132) | static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *co...
  function stbi__pnm_isspace (line 6152) | static int      stbi__pnm_isspace(char c)
  function stbi__pnm_skip_whitespace (line 6157) | static void     stbi__pnm_skip_whitespace(stbi__context *s, char *c)
  function stbi__pnm_isdigit (line 6163) | static int      stbi__pnm_isdigit(char c)
  function stbi__pnm_getinteger (line 6168) | static int      stbi__pnm_getinteger(stbi__context *s, char *c)
  function stbi__pnm_info (line 6180) | static int      stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp)
  function stbi__info_main (line 6215) | static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)
  function STBIDEF (line 6258) | STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp)
  function STBIDEF (line 6268) | STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
  function STBIDEF (line 6280) | STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x...
  function STBIDEF (line 6287) | STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *u...

FILE: src/stb_image_write.h
  type stbiw_uint32 (line 129) | typedef unsigned int stbiw_uint32;
  function writefv (line 132) | static void writefv(FILE *f, const char *fmt, va_list v)
  function write3 (line 152) | static void write3(FILE *f, unsigned char a, unsigned char b, unsigned c...
  function write_pixels (line 159) | static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, i...
  function outfile (line 206) | static int outfile(char const *filename, int rgb_dir, int vdir, int x, i...
  function stbi_write_bmp (line 222) | int stbi_write_bmp(char const *filename, int x, int y, int comp, const v...
  function stbi_write_tga (line 231) | int stbi_write_tga(char const *filename, int x, int y, int comp, const v...
  function stbiw__linear_to_rgbe (line 245) | void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear)
  function stbiw__write_run_data (line 262) | void stbiw__write_run_data(FILE *f, int length, unsigned char databyte)
  function stbiw__write_dump_data (line 270) | void stbiw__write_dump_data(FILE *f, int length, unsigned char *data)
  function stbiw__write_hdr_scanline (line 278) | void stbiw__write_hdr_scanline(FILE *f, int width, int comp, unsigned ch...
  function stbi_write_hdr (line 367) | int stbi_write_hdr(char const *filename, int x, int y, int comp, const f...
  function stbiw__zlib_bitrev (line 425) | static int stbiw__zlib_bitrev(int code, int codebits)
  function stbiw__zlib_countm (line 435) | static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *...
  function stbiw__zhash (line 443) | static unsigned int stbiw__zhash(unsigned char *data)
  function stbiw__crc32 (line 572) | unsigned int stbiw__crc32(unsigned char *buffer, int len)
  function stbiw__wpcrc (line 590) | static void stbiw__wpcrc(unsigned char **data, int len)
  function stbiw__paeth (line 596) | static unsigned char stbiw__paeth(int a, int b, int c)
  function stbi_write_png (line 696) | int stbi_write_png(char const *filename, int x, int y, int comp, const v...

FILE: src/tree.c
  function change_leaves (line 7) | void change_leaves(tree *t, char *leaf_list)
  function get_hierarchy_probability (line 27) | float get_hierarchy_probability(float *x, tree *hier, int c, int stride)
  function hierarchy_predictions (line 37) | void hierarchy_predictions(float *predictions, int n, tree *hier, int on...
  function hierarchy_top_prediction (line 53) | int hierarchy_top_prediction(float *predictions, tree *hier, float thres...
  function tree (line 83) | tree *read_tree(char *filename)

FILE: src/utils.c
  function what_time_is_it_now (line 26) | double what_time_is_it_now()
  function sorta_shuffle (line 71) | void sorta_shuffle(void *arr, size_t n, size_t size, size_t sections)
  function shuffle (line 82) | void shuffle(void *arr, size_t n, size_t size)
  function del_arg (line 94) | void del_arg(int argc, char **argv, int index)
  function find_arg (line 101) | int find_arg(int argc, char* argv[], char *arg)
  function find_int_arg (line 114) | int find_int_arg(int argc, char **argv, char *arg, int def)
  function find_float_arg (line 129) | float find_float_arg(int argc, char **argv, char *arg, float def)
  function alphanum_to_int (line 174) | int alphanum_to_int(char c)
  function int_to_alphanum (line 178) | char int_to_alphanum(int i)
  function pm (line 184) | void pm(int M, int N, float *A)
  function find_replace (line 197) | void find_replace(char *str, char *orig, char *rep, char *output)
  function sec (line 213) | float sec(clock_t clocks)
  function top_k (line 218) | void top_k(float *a, int n, int k, int *index)
  function error (line 234) | void error(const char *s)
  function malloc_error (line 256) | void malloc_error()
  function file_error (line 262) | void file_error(char *s)
  function list (line 268) | list *split_str(char *s, char delim)
  function strip (line 283) | void strip(char *s)
  function strip_char (line 296) | void strip_char(char *s, char bad)
  function free_ptrs (line 309) | void free_ptrs(void **ptrs, int n)
  function read_int (line 347) | int read_int(int fd)
  function write_int (line 355) | void write_int(int fd, int n)
  function read_all_fail (line 361) | int read_all_fail(int fd, char *buffer, size_t bytes)
  function write_all_fail (line 372) | int write_all_fail(int fd, char *buffer, size_t bytes)
  function read_all (line 383) | void read_all(int fd, char *buffer, size_t bytes)
  function write_all (line 393) | void write_all(int fd, char *buffer, size_t bytes)
  function list (line 411) | list *parse_csv_line(char *line)
  function count_fields (line 428) | int count_fields(char *line)
  function sum_array (line 460) | float sum_array(float *a, int n)
  function mean_array (line 468) | float mean_array(float *a, int n)
  function mean_arrays (line 473) | void mean_arrays(float **a, int n, int els, float *avg)
  function print_statistics (line 488) | void print_statistics(float *a, int n)
  function variance_array (line 495) | float variance_array(float *a, int n)
  function constrain_int (line 505) | int constrain_int(int a, int min, int max)
  function constrain (line 512) | float constrain(float min, float max, float a)
  function dist_array (line 519) | float dist_array(float *a, float *b, int n, int sub)
  function mse_array (line 527) | float mse_array(float *a, int n)
  function normalize_array (line 535) | void normalize_array(float *a, int n)
  function translate_array (line 547) | void translate_array(float *a, int n, float s)
  function mag_array (line 555) | float mag_array(float *a, int n)
  function scale_array (line 565) | void scale_array(float *a, int n, float s)
  function sample_array (line 573) | int sample_array(float *a, int n)
  function max_index (line 586) | int max_index(float *a, int n)
  function rand_int (line 600) | int rand_int(int min, int max)
  function rand_normal (line 612) | float rand_normal()
  function rand_size_t (line 644) | size_t rand_size_t()
  function rand_uniform (line 656) | float rand_uniform(float min, float max)
  function rand_scale (line 666) | float rand_scale(float s)
Condensed preview — 130 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,173K chars).
[
  {
    "path": ".gitignore",
    "chars": 187,
    "preview": "*.o\n*.dSYM\n*.csv\n*.out\n*.png\n*.jpg\n*.pyc\n*.weights\n*.a\n*.so\n*.23\nscripts/\ndata/\nimages/\nlabels/\nbackup/\ncfg/\ndarknet\n.fu"
  },
  {
    "path": "Licenses/LICENSE",
    "chars": 515,
    "preview": "                                  YOLO LICENSE\n                             Version 2, July 29 2016\n\nTHIS SOFTWARE LICEN"
  },
  {
    "path": "Licenses/LICENSE.fuck",
    "chars": 474,
    "preview": "           DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n                   Version 2, December 2004\n\nCopyright (C) 2004 S"
  },
  {
    "path": "Licenses/LICENSE.gen",
    "chars": 6646,
    "preview": "RNN LICENSE Version 3, June 21 2017\n\nCopyright (c) 1990, 1989, 1999 Free87337 May 48 THIRD PARTIES OR ANY OTHER THE\nCOMP"
  },
  {
    "path": "Licenses/LICENSE.gpl",
    "chars": 35141,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "Licenses/LICENSE.meta",
    "chars": 360,
    "preview": "                          META-LICENSE\n                    Version 1, June 21 2017\n\nAny and all licenses may be applied "
  },
  {
    "path": "Licenses/LICENSE.mit",
    "chars": 1071,
    "preview": "MIT License\n\nCopyright (c) 2017 Joseph Redmon\n\nPermission is hereby granted, free of charge, to any person obtaining a c"
  },
  {
    "path": "Licenses/LICENSE.v1",
    "chars": 461,
    "preview": "                                  YOLO LICENSE\n                             Version 1, July 10 2015\n\nTHIS SOFTWARE LICEN"
  },
  {
    "path": "Makefile",
    "chars": 3332,
    "preview": "GPU=1\nCUDNN=1\nOPENCV=0\nOPENMP=0\nDEBUG=0\n\nARCH= -gencode arch=compute_30,code=sm_30 \\\n      -gencode arch=compute_35,code"
  },
  {
    "path": "README.md",
    "chars": 12316,
    "preview": "# Darknet\nDarknet is an open source neural network framework written in C and CUDA. It is fast, easy to install, and sup"
  },
  {
    "path": "examples/art.c",
    "chars": 1497,
    "preview": "#include \"darknet.h\"\n\n#include <sys/time.h>\n\nvoid demo_art(char *cfgfile, char *weightfile, int cam_index)\n{\n#ifdef OPEN"
  },
  {
    "path": "examples/attention.c",
    "chars": 11029,
    "preview": "#include \"darknet.h\"\n\n#include <sys/time.h>\n#include <assert.h>\n\nvoid train_attention(char *datacfg, char *cfgfile, char"
  },
  {
    "path": "examples/captcha.c",
    "chars": 11033,
    "preview": "#include \"darknet.h\"\n\nvoid fix_data_captcha(data d, int mask)\n{\n    matrix labels = d.y;\n    int i, j;\n    for(i = 0; i "
  },
  {
    "path": "examples/cifar.c",
    "chars": 8103,
    "preview": "#include \"darknet.h\"\n\nvoid train_cifar(char *cfgfile, char *weightfile)\n{\n    srand(time(0));\n    float avg_loss = -1;\n "
  },
  {
    "path": "examples/classifier.c",
    "chars": 32670,
    "preview": "#include \"darknet.h\"\n\n#include <sys/time.h>\n#include <assert.h>\n\nfloat *get_regression_values(char **labels, int n)\n{\n  "
  },
  {
    "path": "examples/coco.c",
    "chars": 13280,
    "preview": "#include \"darknet.h\"\n\n#include <stdio.h>\n\nchar *coco_classes[] = {\"person\",\"bicycle\",\"car\",\"motorcycle\",\"airplane\",\"bus\""
  },
  {
    "path": "examples/darknet.c",
    "chars": 17461,
    "preview": "#include \"darknet.h\"\n\n#include <time.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nextern void predict_classifier(char *dat"
  },
  {
    "path": "examples/detector.c",
    "chars": 24286,
    "preview": "#include \"darknet.h\"\n\nstatic int coco_ids[] = {1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,3"
  },
  {
    "path": "examples/detector.py",
    "chars": 718,
    "preview": "# Stupid python path shit.\n# Instead just add darknet.py to somewhere in your python path\n# OK actually that might not b"
  },
  {
    "path": "examples/dice.c",
    "chars": 3592,
    "preview": "#include \"darknet.h\"\n\nchar *dice_labels[] = {\"face1\",\"face2\",\"face3\",\"face4\",\"face5\",\"face6\"};\n\nvoid train_dice(char *cf"
  },
  {
    "path": "examples/go.c",
    "chars": 28162,
    "preview": "#include \"darknet.h\"\n\n#include <unistd.h>\n\nint inverted = 1;\nint noi = 1;\nstatic const int nind = 2;\n\ntypedef struct {\n "
  },
  {
    "path": "examples/lsd.c",
    "chars": 37371,
    "preview": "#include \"darknet.h\"\n\n/*\nvoid train_lsd3(char *fcfg, char *fweight, char *gcfg, char *gweight, char *acfg, char *aweight"
  },
  {
    "path": "examples/nightmare.c",
    "chars": 13138,
    "preview": "#include \"darknet.h\"\n\n#include <math.h>\n\n// ./darknet nightmare cfg/extractor.recon.cfg ~/trained/yolo-coco.conv frame6."
  },
  {
    "path": "examples/regressor.c",
    "chars": 6814,
    "preview": "#include \"darknet.h\"\n#include <sys/time.h>\n#include <assert.h>\n\nvoid train_regressor(char *datacfg, char *cfgfile, char "
  },
  {
    "path": "examples/rnn.c",
    "chars": 15716,
    "preview": "#include \"darknet.h\"\n\n#include <math.h>\n\ntypedef struct {\n    float *x;\n    float *y;\n} float_pair;\n\nunsigned char **loa"
  },
  {
    "path": "examples/rnn_vid.c",
    "chars": 6730,
    "preview": "#include \"darknet.h\"\n\n#ifdef OPENCV\nimage get_image_from_stream(CvCapture *cap);\nimage ipl_to_image(IplImage* src);\n\nvoi"
  },
  {
    "path": "examples/segmenter.c",
    "chars": 7936,
    "preview": "#include \"darknet.h\"\n#include <sys/time.h>\n#include <assert.h>\n\nvoid train_segmenter(char *datacfg, char *cfgfile, char "
  },
  {
    "path": "examples/super.c",
    "chars": 3594,
    "preview": "#include \"darknet.h\"\n\nvoid train_super(char *cfgfile, char *weightfile, int clear)\n{\n    char *train_images = \"/data/ima"
  },
  {
    "path": "examples/swag.c",
    "chars": 2444,
    "preview": "#include \"darknet.h\"\n#include <sys/time.h>\n\nvoid train_swag(char *cfgfile, char *weightfile)\n{\n    char *train_images = "
  },
  {
    "path": "examples/tag.c",
    "chars": 4334,
    "preview": "#include \"darknet.h\"\n\nvoid train_tag(char *cfgfile, char *weightfile, int clear)\n{\n    srand(time(0));\n    float avg_los"
  },
  {
    "path": "examples/voxel.c",
    "chars": 4747,
    "preview": "#include \"darknet.h\"\n\nvoid extract_voxel(char *lfile, char *rfile, char *prefix)\n{\n#ifdef OPENCV\n    int w = 1920;\n    i"
  },
  {
    "path": "examples/writing.c",
    "chars": 4403,
    "preview": "#include \"darknet.h\"\n\nvoid train_writing(char *cfgfile, char *weightfile)\n{\n    char *backup_directory = \"/home/pjreddie"
  },
  {
    "path": "examples/yolo.c",
    "chars": 11477,
    "preview": "#include \"darknet.h\"\n\nchar *voc_names[] = {\"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair"
  },
  {
    "path": "include/darknet.h",
    "chars": 18198,
    "preview": "#ifndef DARKNET_API\n#define DARKNET_API\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <pthread.h>\n"
  },
  {
    "path": "python/darknet.py",
    "chars": 3705,
    "preview": "from ctypes import *\nimport math\nimport random\n\ndef sample(probs):\n    s = sum(probs)\n    probs = [a/s for a in probs]\n "
  },
  {
    "path": "python/proverbot.py",
    "chars": 900,
    "preview": "from darknet import *\n\ndef predict_tactic(net, s):\n    prob = 0\n    d = c_array(c_float, [0.0]*256)\n    tac = ''\n    if "
  },
  {
    "path": "src/activation_kernels.cu",
    "chars": 5087,
    "preview": "#include \"cuda_runtime.h\"\n#include \"curand.h\"\n#include \"cublas_v2.h\"\n\nextern \"C\" {\n#include \"activations.h\"\n#include \"cu"
  },
  {
    "path": "src/activation_layer.c",
    "chars": 1707,
    "preview": "#include \"activation_layer.h\"\n#include \"utils.h\"\n#include \"cuda.h\"\n#include \"blas.h\"\n#include \"gemm.h\"\n\n#include <math.h"
  },
  {
    "path": "src/activation_layer.h",
    "chars": 447,
    "preview": "#ifndef ACTIVATION_LAYER_H\n#define ACTIVATION_LAYER_H\n\n#include \"activations.h\"\n#include \"layer.h\"\n#include \"network.h\"\n"
  },
  {
    "path": "src/activations.c",
    "chars": 3560,
    "preview": "#include \"activations.h\"\n\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nchar *get_activa"
  },
  {
    "path": "src/activations.h",
    "chars": 2717,
    "preview": "#ifndef ACTIVATIONS_H\n#define ACTIVATIONS_H\n#include \"darknet.h\"\n#include \"cuda.h\"\n#include \"math.h\"\n\nACTIVATION get_act"
  },
  {
    "path": "src/avgpool_layer.c",
    "chars": 1877,
    "preview": "#include \"avgpool_layer.h\"\n#include \"cuda.h\"\n#include <stdio.h>\n\navgpool_layer make_avgpool_layer(int batch, int w, int "
  },
  {
    "path": "src/avgpool_layer.h",
    "chars": 606,
    "preview": "#ifndef AVGPOOL_LAYER_H\n#define AVGPOOL_LAYER_H\n\n#include \"image.h\"\n#include \"cuda.h\"\n#include \"layer.h\"\n#include \"netwo"
  },
  {
    "path": "src/avgpool_layer_kernels.cu",
    "chars": 1628,
    "preview": "#include \"cuda_runtime.h\"\n#include \"curand.h\"\n#include \"cublas_v2.h\"\n\nextern \"C\" {\n#include \"avgpool_layer.h\"\n#include \""
  },
  {
    "path": "src/batchnorm_layer.c",
    "chars": 10366,
    "preview": "#include \"convolutional_layer.h\"\n#include \"batchnorm_layer.h\"\n#include \"blas.h\"\n#include <stdio.h>\n\nlayer make_batchnorm"
  },
  {
    "path": "src/batchnorm_layer.h",
    "chars": 490,
    "preview": "#ifndef BATCHNORM_LAYER_H\n#define BATCHNORM_LAYER_H\n\n#include \"image.h\"\n#include \"layer.h\"\n#include \"network.h\"\n\nlayer m"
  },
  {
    "path": "src/blas.c",
    "chars": 7588,
    "preview": "#include \"blas.h\"\n\n#include <math.h>\n#include <assert.h>\n#include <float.h>\n#include <stdio.h>\n#include <stdlib.h>\n#incl"
  },
  {
    "path": "src/blas.h",
    "chars": 5996,
    "preview": "#ifndef BLAS_H\n#define BLAS_H\n#include \"darknet.h\"\n\nvoid flatten(float *x, int size, int layers, int batch, int forward)"
  },
  {
    "path": "src/blas_kernels.cu",
    "chars": 29741,
    "preview": "#include \"cuda_runtime.h\"\n#include \"curand.h\"\n#include \"cublas_v2.h\"\n#include <assert.h>\n\nextern \"C\" {\n#include \"blas.h\""
  },
  {
    "path": "src/box.c",
    "chars": 8230,
    "preview": "#include \"box.h\"\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n\nbox float_to_box(float *f, int stride)\n{\n    "
  },
  {
    "path": "src/box.h",
    "chars": 234,
    "preview": "#ifndef BOX_H\n#define BOX_H\n#include \"darknet.h\"\n\ntypedef struct{\n    float dx, dy, dw, dh;\n} dbox;\n\nfloat box_rmse(box "
  },
  {
    "path": "src/classifier.h",
    "chars": 1,
    "preview": "\n"
  },
  {
    "path": "src/col2im.c",
    "chars": 1340,
    "preview": "#include <stdio.h>\n#include <math.h>\nvoid col2im_add_pixel(float *im, int height, int width, int channels,\n             "
  },
  {
    "path": "src/col2im.h",
    "chars": 331,
    "preview": "#ifndef COL2IM_H\n#define COL2IM_H\n\nvoid col2im_cpu(float* data_col,\n        int channels, int height, int width,\n       "
  },
  {
    "path": "src/col2im_kernels.cu",
    "chars": 2311,
    "preview": "#include \"cuda_runtime.h\"\n#include \"curand.h\"\n#include \"cublas_v2.h\"\n\nextern \"C\" {\n#include \"col2im.h\"\n#include \"cuda.h\""
  },
  {
    "path": "src/compare.c",
    "chars": 10819,
    "preview": "#include <stdio.h>\n\n#include \"network.h\"\n#include \"detection_layer.h\"\n#include \"cost_layer.h\"\n#include \"utils.h\"\n#includ"
  },
  {
    "path": "src/connected_layer.c",
    "chars": 11056,
    "preview": "#include \"connected_layer.h\"\n#include \"convolutional_layer.h\"\n#include \"batchnorm_layer.h\"\n#include \"utils.h\"\n#include \""
  },
  {
    "path": "src/connected_layer.h",
    "chars": 666,
    "preview": "#ifndef CONNECTED_LAYER_H\n#define CONNECTED_LAYER_H\n\n#include \"activations.h\"\n#include \"layer.h\"\n#include \"network.h\"\n\nl"
  },
  {
    "path": "src/convolutional_kernels.cu",
    "chars": 10207,
    "preview": "#include \"cuda_runtime.h\"\n#include \"curand.h\"\n#include \"cublas_v2.h\"\n\nextern \"C\" {\n#include \"convolutional_layer.h\"\n#inc"
  },
  {
    "path": "src/convolutional_layer.c",
    "chars": 18441,
    "preview": "#include \"convolutional_layer.h\"\n#include \"utils.h\"\n#include \"batchnorm_layer.h\"\n#include \"im2col.h\"\n#include \"col2im.h\""
  },
  {
    "path": "src/convolutional_layer.h",
    "chars": 2218,
    "preview": "#ifndef CONVOLUTIONAL_LAYER_H\n#define CONVOLUTIONAL_LAYER_H\n\n#include \"cuda.h\"\n#include \"image.h\"\n#include \"activations."
  },
  {
    "path": "src/cost_layer.c",
    "chars": 4956,
    "preview": "#include \"cost_layer.h\"\n#include \"utils.h\"\n#include \"cuda.h\"\n#include \"blas.h\"\n#include <math.h>\n#include <string.h>\n#in"
  },
  {
    "path": "src/cost_layer.h",
    "chars": 574,
    "preview": "#ifndef COST_LAYER_H\n#define COST_LAYER_H\n#include \"layer.h\"\n#include \"network.h\"\n\ntypedef layer cost_layer;\n\nCOST_TYPE "
  },
  {
    "path": "src/crnn_layer.c",
    "chars": 9388,
    "preview": "#include \"crnn_layer.h\"\n#include \"convolutional_layer.h\"\n#include \"utils.h\"\n#include \"cuda.h\"\n#include \"blas.h\"\n#include"
  },
  {
    "path": "src/crnn_layer.h",
    "chars": 649,
    "preview": "\n#ifndef CRNN_LAYER_H\n#define CRNN_LAYER_H\n\n#include \"activations.h\"\n#include \"layer.h\"\n#include \"network.h\"\n\nlayer make"
  },
  {
    "path": "src/crop_layer.c",
    "chars": 2759,
    "preview": "#include \"crop_layer.h\"\n#include \"cuda.h\"\n#include <stdio.h>\n\nimage get_crop_image(crop_layer l)\n{\n    int h = l.out_h;\n"
  },
  {
    "path": "src/crop_layer.h",
    "chars": 506,
    "preview": "#ifndef CROP_LAYER_H\n#define CROP_LAYER_H\n\n#include \"image.h\"\n#include \"layer.h\"\n#include \"network.h\"\n\ntypedef layer cro"
  },
  {
    "path": "src/crop_layer_kernels.cu",
    "chars": 6669,
    "preview": "#include \"cuda_runtime.h\"\n#include \"curand.h\"\n#include \"cublas_v2.h\"\n\nextern \"C\" {\n#include \"crop_layer.h\"\n#include \"uti"
  },
  {
    "path": "src/cuda.c",
    "chars": 4059,
    "preview": "int gpu_index = 0;\n\n#ifdef GPU\n\n#include \"cuda.h\"\n#include \"utils.h\"\n#include \"blas.h\"\n#include <assert.h>\n#include <std"
  },
  {
    "path": "src/cuda.h",
    "chars": 378,
    "preview": "#ifndef CUDA_H\n#define CUDA_H\n\n#include \"darknet.h\"\n\n#ifdef GPU\n\nvoid check_error(cudaError_t status);\ncublasHandle_t bl"
  },
  {
    "path": "src/data.c",
    "chars": 42787,
    "preview": "#include \"data.h\"\n#include \"utils.h\"\n#include \"image.h\"\n#include \"cuda.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#inclu"
  },
  {
    "path": "src/data.h",
    "chars": 2145,
    "preview": "#ifndef DATA_H\n#define DATA_H\n#include <pthread.h>\n\n#include \"darknet.h\"\n#include \"matrix.h\"\n#include \"list.h\"\n#include "
  },
  {
    "path": "src/deconvolutional_kernels.cu",
    "chars": 4712,
    "preview": "#include \"cuda_runtime.h\"\n#include \"curand.h\"\n#include \"cublas_v2.h\"\n\nextern \"C\" {\n#include \"convolutional_layer.h\"\n#inc"
  },
  {
    "path": "src/deconvolutional_layer.c",
    "chars": 9160,
    "preview": "#include \"deconvolutional_layer.h\"\n#include \"convolutional_layer.h\"\n#include \"batchnorm_layer.h\"\n#include \"utils.h\"\n#inc"
  },
  {
    "path": "src/deconvolutional_layer.h",
    "chars": 871,
    "preview": "#ifndef DECONVOLUTIONAL_LAYER_H\n#define DECONVOLUTIONAL_LAYER_H\n\n#include \"cuda.h\"\n#include \"image.h\"\n#include \"activati"
  },
  {
    "path": "src/demo.c",
    "chars": 9220,
    "preview": "#include \"network.h\"\n#include \"detection_layer.h\"\n#include \"region_layer.h\"\n#include \"cost_layer.h\"\n#include \"utils.h\"\n#"
  },
  {
    "path": "src/demo.h",
    "chars": 58,
    "preview": "#ifndef DEMO_H\n#define DEMO_H\n\n#include \"image.h\"\n\n#endif\n"
  },
  {
    "path": "src/detection_layer.c",
    "chars": 10285,
    "preview": "#include \"detection_layer.h\"\n#include \"activations.h\"\n#include \"softmax_layer.h\"\n#include \"blas.h\"\n#include \"box.h\"\n#inc"
  },
  {
    "path": "src/detection_layer.h",
    "chars": 545,
    "preview": "#ifndef DETECTION_LAYER_H\n#define DETECTION_LAYER_H\n\n#include \"layer.h\"\n#include \"network.h\"\n\ntypedef layer detection_la"
  },
  {
    "path": "src/dropout_layer.c",
    "chars": 1606,
    "preview": "#include \"dropout_layer.h\"\n#include \"utils.h\"\n#include \"cuda.h\"\n#include <stdlib.h>\n#include <stdio.h>\n\ndropout_layer ma"
  },
  {
    "path": "src/dropout_layer.h",
    "chars": 523,
    "preview": "#ifndef DROPOUT_LAYER_H\n#define DROPOUT_LAYER_H\n\n#include \"layer.h\"\n#include \"network.h\"\n\ntypedef layer dropout_layer;\n\n"
  },
  {
    "path": "src/dropout_layer_kernels.cu",
    "chars": 1239,
    "preview": "#include \"cuda_runtime.h\"\n#include \"curand.h\"\n#include \"cublas_v2.h\"\n\nextern \"C\" {\n#include \"dropout_layer.h\"\n#include \""
  },
  {
    "path": "src/gemm.c",
    "chars": 8188,
    "preview": "#include \"gemm.h\"\n#include \"utils.h\"\n#include \"cuda.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n\nvoid ge"
  },
  {
    "path": "src/gemm.h",
    "chars": 928,
    "preview": "#ifndef GEMM_H\n#define GEMM_H\n\nvoid gemm_bin(int M, int N, int K, float ALPHA, \n        char  *A, int lda, \n        floa"
  },
  {
    "path": "src/gru_layer.c",
    "chars": 13715,
    "preview": "#include \"gru_layer.h\"\n#include \"connected_layer.h\"\n#include \"utils.h\"\n#include \"cuda.h\"\n#include \"blas.h\"\n#include \"gem"
  },
  {
    "path": "src/gru_layer.h",
    "chars": 597,
    "preview": "\n#ifndef GRU_LAYER_H\n#define GRU_LAYER_H\n\n#include \"activations.h\"\n#include \"layer.h\"\n#include \"network.h\"\n\nlayer make_g"
  },
  {
    "path": "src/im2col.c",
    "chars": 1337,
    "preview": "#include \"im2col.h\"\n#include <stdio.h>\nfloat im2col_get_pixel(float *im, int height, int width, int channels,\n          "
  },
  {
    "path": "src/im2col.h",
    "chars": 329,
    "preview": "#ifndef IM2COL_H\n#define IM2COL_H\n\nvoid im2col_cpu(float* data_im,\n        int channels, int height, int width,\n        "
  },
  {
    "path": "src/im2col_kernels.cu",
    "chars": 2278,
    "preview": "#include \"cuda_runtime.h\"\n#include \"curand.h\"\n#include \"cublas_v2.h\"\n\nextern \"C\" {\n#include \"im2col.h\"\n#include \"cuda.h\""
  },
  {
    "path": "src/image.c",
    "chars": 41296,
    "preview": "#include \"image.h\"\n#include \"utils.h\"\n#include \"blas.h\"\n#include \"cuda.h\"\n#include <stdio.h>\n#include <math.h>\n\n#define "
  },
  {
    "path": "src/image.h",
    "chars": 2407,
    "preview": "#ifndef IMAGE_H\n#define IMAGE_H\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <float.h>\n#include <string.h>\n#include "
  },
  {
    "path": "src/layer.c",
    "chars": 4471,
    "preview": "#include \"layer.h\"\n#include \"cuda.h\"\n\n#include <stdlib.h>\n\nvoid free_layer(layer l)\n{\n    if(l.type == DROPOUT){\n       "
  },
  {
    "path": "src/layer.h",
    "chars": 21,
    "preview": "#include \"darknet.h\"\n"
  },
  {
    "path": "src/list.c",
    "chars": 1370,
    "preview": "#include <stdlib.h>\n#include <string.h>\n#include \"list.h\"\n\nlist *make_list()\n{\n\tlist *l = malloc(sizeof(list));\n\tl->size"
  },
  {
    "path": "src/list.h",
    "chars": 185,
    "preview": "#ifndef LIST_H\n#define LIST_H\n#include \"darknet.h\"\n\nlist *make_list();\nint list_find(list *l, void *val);\n\nvoid list_ins"
  },
  {
    "path": "src/local_layer.c",
    "chars": 8929,
    "preview": "#include \"local_layer.h\"\n#include \"utils.h\"\n#include \"im2col.h\"\n#include \"col2im.h\"\n#include \"blas.h\"\n#include \"gemm.h\"\n"
  },
  {
    "path": "src/local_layer.h",
    "chars": 943,
    "preview": "#ifndef LOCAL_LAYER_H\n#define LOCAL_LAYER_H\n\n#include \"cuda.h\"\n#include \"image.h\"\n#include \"activations.h\"\n#include \"lay"
  },
  {
    "path": "src/lstm_layer.c",
    "chars": 24438,
    "preview": "#include \"lstm_layer.h\"\n#include \"connected_layer.h\"\n#include \"utils.h\"\n#include \"cuda.h\"\n#include \"blas.h\"\n#include \"ge"
  },
  {
    "path": "src/lstm_layer.h",
    "chars": 503,
    "preview": "#ifndef LSTM_LAYER_H\n#define LSTM_LAYER_H\n\n#include \"activations.h\"\n#include \"layer.h\"\n#include \"network.h\"\n#define USET"
  },
  {
    "path": "src/matrix.c",
    "chars": 4262,
    "preview": "#include \"matrix.h\"\n#include \"utils.h\"\n#include \"blas.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#inc"
  },
  {
    "path": "src/matrix.h",
    "chars": 246,
    "preview": "#ifndef MATRIX_H\n#define MATRIX_H\n#include \"darknet.h\"\n\nmatrix copy_matrix(matrix m);\nvoid print_matrix(matrix m);\n\nmatr"
  },
  {
    "path": "src/maxpool_layer.c",
    "chars": 3940,
    "preview": "#include \"maxpool_layer.h\"\n#include \"cuda.h\"\n#include <stdio.h>\n\nimage get_maxpool_image(maxpool_layer l)\n{\n    int h = "
  },
  {
    "path": "src/maxpool_layer.h",
    "chars": 641,
    "preview": "#ifndef MAXPOOL_LAYER_H\n#define MAXPOOL_LAYER_H\n\n#include \"image.h\"\n#include \"cuda.h\"\n#include \"layer.h\"\n#include \"netwo"
  },
  {
    "path": "src/maxpool_layer_kernels.cu",
    "chars": 3180,
    "preview": "#include \"cuda_runtime.h\"\n#include \"curand.h\"\n#include \"cublas_v2.h\"\n\nextern \"C\" {\n#include \"maxpool_layer.h\"\n#include \""
  },
  {
    "path": "src/network.c",
    "chars": 28728,
    "preview": "#include <stdio.h>\n#include <time.h>\n#include <assert.h>\n#include \"network.h\"\n#include \"image.h\"\n#include \"data.h\"\n#incl"
  },
  {
    "path": "src/network.h",
    "chars": 597,
    "preview": "// Oh boy, why am I about to do this....\n#ifndef NETWORK_H\n#define NETWORK_H\n#include \"darknet.h\"\n\n#include \"image.h\"\n#i"
  },
  {
    "path": "src/normalization_layer.c",
    "chars": 5532,
    "preview": "#include \"normalization_layer.h\"\n#include \"blas.h\"\n\n#include <stdio.h>\n\nlayer make_normalization_layer(int batch, int w,"
  },
  {
    "path": "src/normalization_layer.h",
    "chars": 658,
    "preview": "#ifndef NORMALIZATION_LAYER_H\n#define NORMALIZATION_LAYER_H\n\n#include \"image.h\"\n#include \"layer.h\"\n#include \"network.h\"\n"
  },
  {
    "path": "src/option_list.c",
    "chars": 3121,
    "preview": "#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include \"option_list.h\"\n#include \"utils.h\"\n\nlist *read_data_"
  },
  {
    "path": "src/option_list.h",
    "chars": 474,
    "preview": "#ifndef OPTION_LIST_H\n#define OPTION_LIST_H\n#include \"list.h\"\n\ntypedef struct{\n    char *key;\n    char *val;\n    int use"
  },
  {
    "path": "src/parser.c",
    "chars": 41186,
    "preview": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <assert.h>\n\n#include \"activation_layer.h\"\n#include \""
  },
  {
    "path": "src/parser.h",
    "chars": 188,
    "preview": "#ifndef PARSER_H\n#define PARSER_H\n#include \"darknet.h\"\n#include \"network.h\"\n\nvoid save_network(network net, char *filena"
  },
  {
    "path": "src/region_layer.c",
    "chars": 23086,
    "preview": "#include \"region_layer.h\"\n#include \"activations.h\"\n#include \"blas.h\"\n#include \"box.h\"\n#include \"cuda.h\"\n#include \"utils."
  },
  {
    "path": "src/region_layer.h",
    "chars": 492,
    "preview": "#ifndef REGION_LAYER_H\n#define REGION_LAYER_H\n\n#include \"darknet.h\"\n#include \"layer.h\"\n#include \"network.h\"\n\nlayer make_"
  },
  {
    "path": "src/reorg_layer.c",
    "chars": 5037,
    "preview": "#include \"reorg_layer.h\"\n#include \"cuda.h\"\n#include \"blas.h\"\n\n#include <stdio.h>\n\n\nlayer make_reorg_layer(int batch, int"
  },
  {
    "path": "src/reorg_layer.h",
    "chars": 519,
    "preview": "#ifndef REORG_LAYER_H\n#define REORG_LAYER_H\n\n#include \"image.h\"\n#include \"cuda.h\"\n#include \"layer.h\"\n#include \"network.h"
  },
  {
    "path": "src/rnn_layer.c",
    "chars": 10093,
    "preview": "#include \"rnn_layer.h\"\n#include \"connected_layer.h\"\n#include \"utils.h\"\n#include \"cuda.h\"\n#include \"blas.h\"\n#include \"gem"
  },
  {
    "path": "src/rnn_layer.h",
    "chars": 625,
    "preview": "\n#ifndef RNN_LAYER_H\n#define RNN_LAYER_H\n\n#include \"activations.h\"\n#include \"layer.h\"\n#include \"network.h\"\n#define USET\n"
  },
  {
    "path": "src/route_layer.c",
    "chars": 3937,
    "preview": "#include \"route_layer.h\"\n#include \"cuda.h\"\n#include \"blas.h\"\n\n#include <stdio.h>\n\nroute_layer make_route_layer(int batch"
  },
  {
    "path": "src/route_layer.h",
    "chars": 529,
    "preview": "#ifndef ROUTE_LAYER_H\n#define ROUTE_LAYER_H\n#include \"network.h\"\n#include \"layer.h\"\n\ntypedef layer route_layer;\n\nroute_l"
  },
  {
    "path": "src/shortcut_layer.c",
    "chars": 2226,
    "preview": "#include \"shortcut_layer.h\"\n#include \"cuda.h\"\n#include \"blas.h\"\n#include \"activations.h\"\n\n#include <stdio.h>\n#include <a"
  },
  {
    "path": "src/shortcut_layer.h",
    "chars": 451,
    "preview": "#ifndef SHORTCUT_LAYER_H\n#define SHORTCUT_LAYER_H\n\n#include \"layer.h\"\n#include \"network.h\"\n\nlayer make_shortcut_layer(in"
  },
  {
    "path": "src/softmax_layer.c",
    "chars": 2666,
    "preview": "#include \"softmax_layer.h\"\n#include \"blas.h\"\n#include \"cuda.h\"\n\n#include <float.h>\n#include <math.h>\n#include <stdlib.h>"
  },
  {
    "path": "src/softmax_layer.h",
    "chars": 604,
    "preview": "#ifndef SOFTMAX_LAYER_H\n#define SOFTMAX_LAYER_H\n#include \"layer.h\"\n#include \"network.h\"\n\ntypedef layer softmax_layer;\n\nv"
  },
  {
    "path": "src/stb_image.h",
    "chars": 220334,
    "preview": "/* stb_image - v2.06 - public domain image loader - http://nothings.org/stb_image.h\n                                    "
  },
  {
    "path": "src/stb_image_write.h",
    "chars": 25652,
    "preview": "/* stb_image_write - v0.98 - public domain - http://nothings.org/stb/stb_image_write.h\n   writes out PNG/BMP/TGA images "
  },
  {
    "path": "src/tree.c",
    "chars": 3730,
    "preview": "#include <stdio.h>\n#include <stdlib.h>\n#include \"tree.h\"\n#include \"utils.h\"\n#include \"data.h\"\n\nvoid change_leaves(tree *"
  },
  {
    "path": "src/tree.h",
    "chars": 255,
    "preview": "#ifndef TREE_H\n#define TREE_H\n#include \"darknet.h\"\n\ntree *read_tree(char *filename);\nint hierarchy_top_prediction(float "
  },
  {
    "path": "src/utils.c",
    "chars": 13690,
    "preview": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <assert.h>\n#include <unistd.h>\n#in"
  },
  {
    "path": "src/utils.h",
    "chars": 1755,
    "preview": "#ifndef UTILS_H\n#define UTILS_H\n#include <stdio.h>\n#include <time.h>\n#include \"darknet.h\"\n#include \"list.h\"\n\n#define TIM"
  }
]

About this extraction

This page contains the full source code of the RiccardoGrin/darknet GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 130 files (1.1 MB), approximately 336.6k tokens, and a symbol index with 1053 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!