ningwebbeginner

i'ni'tea

要显示太多修改。

为保证性能只显示 29 of 29+ 个文件。

.idea
DS_Store
examples/build
cmake-build-debug
\ No newline at end of file
... ...
cmake_minimum_required(VERSION 3.17)
project(RobustVideoMatting.lite.ai.toolkit)
set(CMAKE_CXX_STANDARD 11)
# setting up lite.ai.toolkit
set(LITE_AI_DIR ${CMAKE_SOURCE_DIR}/lite.ai.toolkit)
set(LITE_AI_INCLUDE_DIR ${LITE_AI_DIR}/include)
set(LITE_AI_LIBRARY_DIR ${LITE_AI_DIR}/lib)
include_directories(${LITE_AI_INCLUDE_DIR})
link_directories(${LITE_AI_LIBRARY_DIR})
#set(OpenCV_LIBS
# opencv_highgui
# opencv_core
# opencv_imgcodecs
# opencv_imgproc
# opencv_video
# opencv_videoio
# )
set(OpenCV_LIBS
opencv_world4110d
opencv_world4110
)
# add your executable
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/examples/build)
file(GLOB ALL_LIBS ${LITE_AI_LIBRARY_DIR}/*dll)
file(INSTALL ${ALL_LIBS} DESTINATION ${EXECUTABLE_OUTPUT_PATH})
add_executable(lite_rvm examples/test_lite_rvm.cpp)
target_link_libraries(lite_rvm
lite.ai.toolkit
onnxruntime
# MNN # need, if built lite.ai.toolkit with ENABLE_MNN=ON, default OFF
# ncnn # need, if built lite.ai.toolkit with ENABLE_NCNN=ON, default OFF
# TNN # need, if built lite.ai.toolkit with ENABLE_TNN=ON, default OFF
${OpenCV_LIBS}) # link lite.ai.toolkit & other libs.
... ...
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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:
<program> Copyright (C) <year> <name of author>
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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
... ...
## RVM Inference
<div align='left'>
<img src=https://img.shields.io/github/stars/DefTruth/RobustVideoMatting.lite.ai.toolkit.svg?style=social >
<img src=https://img.shields.io/github/forks/DefTruth/RobustVideoMatting.lite.ai.toolkit.svg?style=social >
<img src=https://img.shields.io/github/watchers/DefTruth/RobustVideoMatting.lite.ai.toolkit.svg?style=social>
</div>
## News 👇👇
Most of my time now is focused on **LLM/VLM** Inference. Please check 📖[Awesome-LLM-Inference](https://github.com/DefTruth/Awesome-LLM-Inference) ![](https://img.shields.io/github/stars/DefTruth/Awesome-LLM-Inference.svg?style=social), 📖[Awesome-SD-Inference](https://github.com/DefTruth/Awesome-SD-Inference) ![](https://img.shields.io/github/stars/DefTruth/Awesome-SD-Inference.svg?style=social) and 📖[CUDA-Learn-Notes](https://github.com/DefTruth/CUDA-Learn-Notes) ![](https://img.shields.io/github/stars/DefTruth/CUDA-Learn-Notes.svg?style=social) for more details.
## 1. 简介
使用Lite.AI.ToolKit C++工具箱来跑RobustVideoMatting的一些案例(https://github.com/DefTruth/lite.ai.toolkit) ,ONNXRuntime、MNN、NCNN和TNN四个版本。
<div align='center'>
<img src='resources/interviewi.gif' height="80px" width="160px">
<img src='resources/interview.gif' height="80px" width="160px">
<img src='resources/dance3i.gif' height="80px" width="160px">
<img src='resources/dance3.gif' height="80px" width="160px">
<br>
<img src='resources/teslai.gif' height="80px" width="160px">
<img src='resources/tesla.gif' height="80px" width="160px">
<img src='resources/b5i.gif' height="80px" width="160px">
<img src='resources/b5.gif' height="80px" width="160px">
</div>
若是有用,❤️不妨给个⭐️🌟支持一下吧~ 🙃🤪🍀
## 2. C++版本源码
RobustVideoMatting C++ 版本的源码包含ONNXRuntime、MNN、NCNN和TNN四个版本,可以在 [lite.ai.toolkit](https://github.com/DefTruth/lite.ai.toolkit) 工具箱中找到。本项目主要介绍如何基于 [lite.ai.toolkit](https://github.com/DefTruth/lite.ai.toolkit) 工具箱,直接使用RobustVideoMatting实现视频抠图和图片抠图。需要说明的是,本项目是基于MacOS下编译的 [liblite.ai.toolkit.v0.1.0.dylib](https://github.com/DefTruth/RobustVideoMatting.lite.ai.toolkit/blob/main/lite.ai.toolkit/lib) 来实现的,对于使用MacOS的用户,可以直接下载本项目包含的*liblite.ai.toolkit.v0.1.0*动态库和其他依赖库进行使用。而非MacOS用户,则需要从[lite.ai.toolkit](https://github.com/DefTruth/lite.ai.toolkit) 中下载源码进行编译。[lite.ai.toolkit](https://github.com/DefTruth/lite.ai.toolkit) c++工具箱目前包含70+流行的开源模型。
* [rvm.cpp](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/ort/cv/rvm.cpp)
* [rvm.h](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/ort/cv/rvm.h)
* [mnn_rvm.cpp](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/mnn/cv/mnn_rvm.cpp)
* [mnn_rvm.h](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/mnn/cv/mnn_rvm.h)
* [ncnn_rvm.cpp](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/ncnn/cv/ncnn_rvm.cpp)
* [ncnn_rvm.h](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/ncnn/cv/ncnn_rvm.h)
* [tnn_rvm.cpp](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/tnn/cv/tnn_rvm.cpp)
* [tnn_rvm.h](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/tnn/cv/tnn_rvm.h)
NCNN版本的测试没有通过,转换的模型可能有问题,这里先放出代码。这里案例使用的接口是默认版本,即ONNXRuntime. 目前ONNXRuntime、MNN和TNN版本均已测试通过。
## 3. 模型文件
### 3.1 ONNX模型文件
可以从我提供的链接下载 ([Baidu Drive](https://pan.baidu.com/s/1elUGcx7CZkkjEoYhTMwTRQ) code: 8gin) , 也可以从 [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) 官方仓库下载。
| Class | Pretrained ONNX Files | Rename or Converted From (Repo) | Size |
| :---------------------------------: | :-------------------: | :-------------------------------------------------------: | :---: |
| *lite::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32.onnx | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp16.onnx | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 7.2Mb |
| *lite::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32.onnx | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::cv::matting::RobustVideoMatting* | rvm_resnet50_fp16.onnx | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 100Mb |
### 3.2 MNN模型文件
可以从我提供的链接下载 ([Baidu Drive](https://pan.baidu.com/s/1KyO-bCYUv6qPq2M8BH_Okg) code: 9v63)
| Class | Pretrained MNN Files | Rename or Converted From (Repo) | Size |
| :---------------------------------: | :-------------------: | :-------------------------------------------------------: | :---: |
| *lite::mnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32.mnn | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::mnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-480-480.mnn | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::mnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-480-640.mnn | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::mnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-640-480.mnn | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::mnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-1080-1920.mnn | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::mnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32.mnn | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::mnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-480-480.mnn | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::mnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-480-640.mnn | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::mnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-640-480.mnn | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::mnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-1080-1920.mnn | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
### 3.3 NCNN模型文件
可以从我提供的链接下载 ([Baidu Drive](https://pan.baidu.com/s/1hlnqyNsFbMseGFWscgVhgQ) code: sc7f)
| Class | Pretrained NCNN Files | Rename or Converted From (Repo) | Size |
| :---------------------------------: | :-------------------: | :-------------------------------------------------------: | :---: |
| *lite::ncnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-opt.param&bin | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::ncnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-480-480-opt.param&bin | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::ncnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-480-640-opt.param&bin | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::ncnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-640-480-opt.param&bin | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::ncnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-1080-1920-opt.param&bin | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::ncnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-opt.param&bin | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::ncnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-480-480-opt.param&bin | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::ncnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-480-640-opt.param&bin | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::ncnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-640-480-opt.param&bin | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::ncnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-1080-1920-opt.param&bin | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
### 3.4 TNN模型文件
可以从我提供的链接下载 ([Baidu Drive](https://pan.baidu.com/s/1lvM2YKyUbEc5HKVtqITpcw) code: 6o6k)
| Class | Pretrained TNN Files | Rename or Converted From (Repo) | Size |
| :---------------------------------: | :-------------------: | :-------------------------------------------------------: | :---: |
| *lite::tnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-480-480-sim.tnnproto&tnnmodel | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::tnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-480-640-sim.tnnproto&tnnmodel | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::tnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-640-480-sim.tnnproto&tnnmodel | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::tnn::cv::matting::RobustVideoMatting* | rvm_mobilenetv3_fp32-1080-1920-sim.tnnproto&tnnmodel | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 14Mb |
| *lite::tnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-480-480-sim.tnnproto&tnnmodel | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::tnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-480-640-sim.tnnproto&tnnmodel | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::tnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-640-480-sim.tnnproto&tnnmodel | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
| *lite::tnn::cv::matting::RobustVideoMatting* | rvm_resnet50_fp32-1080-1920-sim.tnnproto&tnnmodel | [RobustVideoMatting](https://github.com/PeterL1n/RobustVideoMatting) | 50Mb |
## 4. 接口文档
[lite.ai.toolkit](https://github.com/DefTruth/lite.ai.toolkit) 中,RobustVideoMatting的实现类为:
```c++
class LITE_EXPORTS lite::cv::matting::RobustVideoMatting;
class LITE_EXPORTS lite::mnn::cv::matting::RobustVideoMatting;
class LITE_EXPORTS lite::tnn::cv::matting::RobustVideoMatting;
class LITE_EXPORTS lite::ncnn::cv::matting::RobustVideoMatting;
```
该类型目前包含两个公共接口,分别是`detect`和`detect_video`,前者用于图像抠图,后者用于视频抠图。不同推理引擎的实现,接口基本相同。TNN、MNN和NCNN版本的接口不含downsample_ratio,因为转换时,我是按照静态维度转换的,并且在转换模型时固定了一个合适的downsample_ratio,不需要再推理时再设置。具体区别可以跳转到c++实现的源码查看。
```c++
/**
* Image Matting Using RVM(https://github.com/PeterL1n/RobustVideoMatting)
* @param mat: cv::Mat BGR HWC
* @param content: types::MattingContent to catch the detected results.
* @param downsample_ratio: 0.25 by default.
* See https://github.com/PeterL1n/RobustVideoMatting/blob/master/documentation/inference_zh_Hans.md
*/
void detect(const cv::Mat &mat, types::MattingContent &content,
float downsample_ratio = 0.25f);
/**
* Video Matting Using RVM(https://github.com/PeterL1n/RobustVideoMatting)
* @param video_path: eg. xxx/xxx/input.mp4
* @param output_path: eg. xxx/xxx/output.mp4
* @param contents: vector of MattingContent to catch the detected results.
* @param save_contents: false by default, whether to save MattingContent.
* @param downsample_ratio: 0.25 by default.
* See https://github.com/PeterL1n/RobustVideoMatting/blob/master/documentation/inference_zh_Hans.md
* @param writer_fps: FPS for VideoWriter, 20 by default.
*/
void detect_video(const std::string &video_path,
const std::string &output_path,
std::vector<types::MattingContent> &contents,
bool save_contents = false,
float downsample_ratio = 0.25f,
unsigned int writer_fps = 20);
```
* `detect`接口输入参数说明:
* mat: cv::Mat BGR格式图像
* content: types::MattingContent类型,用来保存检测的结果,包含类型为cv::Mat的三个成员,分别是
* `fgr_mat`: `cv::Mat (H,W,C=3) BGR` 格式,值范围为0~255 的 `CV_8UC3`, 用于保存估计的前景
* `pha_mat`:` cv::Mat (H,W,C=1)` 值范围为0.~1.的 `CV_32FC1`, 用于保存估计的alpha(matte)值
* `merge_mat`: `cv::Mat (H,W,C=3) BGR` 格式,值范围为0~255 的 `CV_8UC3`, 用于保存根据pha融合前景背景的合成图像
* `flag`: bool 类型标志位,表示是否检测成功
* downsample_ratio: float,下采样比率,默认0.25f,值的设置可以参考[官方文档](https://github.com/PeterL1n/RobustVideoMatting/blob/master/documentation/inference_zh_Hans.md) , 如下:
| 分辨率 | 人像 | 全身 |
| ------------- | ------------- | -------------- |
| <= 512x512 | 1 | 1 |
| 1280x720 | 0.375 | 0.6 |
| 1920x1080 | 0.25 | 0.4 |
| 3840x2160 | 0.125 | 0.2 |
模型在内部将高分辨率输入缩小做初步的处理,然后再放大做细分处理。 建议设置 `downsample_ratio` 使缩小后的分辨率维持在 256 到 512 像素之间. 例如,`1920x1080` 的输入用 `downsample_ratio=0.25`,缩小后的分辨率 `480x270` 在 256 到 512 像素之间。 根据视频内容调整 `downsample_ratio`。若视频是上身人像,低 `downsample_ratio` 足矣。若视频是全身像,建议尝试更高的 `downsample_ratio`。但注意,过高的 `downsample_ratio` 反而会降低效果。
* `detect_video`接口输入参数说明:
* video_path: string, 输入的视频路径
* output_path: string, 输出的视频路径
* contents:MattingContent类型的vector,用来保存每帧检测的结果
* save_contents:bool,是否保存每一帧的结果,默认false。当分辨率很大时,保存所有的结果将会占用非常多内存
* downsample_ratio: float,下采样比率,默认0.25f,同上。
* writer_fps:int 视频写出的帧率,默认20
## 5. 使用案例
这里测试使用的是mobilenetv3版本的rvm模型,如果你使用resnet50版本的模型,将会得到更高精度的结果。
### 5.1 图像抠图案例
```c++
#include "lite/lite.h"
// Image Matting Interface
static void test_image()
{
std::string onnx_path = "../hub/onnx/cv/rvm_mobilenetv3_fp32.onnx";
std::string img_path = "../examples/lite/resources/test.jpg";
std::string save_fgr_path = "../logs/test_lite_rvm_fgr.jpg";
std::string save_pha_path = "../logs/test_rvm_pha.jpg";
std::string save_merge_path = "../logs/test_lite_rvm_merge.jpg";
auto *rvm = new lite::matting::RobustVideoMatting(onnx_path, 16); // 16 threads
lite::types::MattingContent content;
cv::Mat img_bgr = cv::imread(img_path);
// 1. image matting.
rvm->detect(img_bgr, content, 0.25f);
if (content.flag)
{
if (!content.fgr_mat.empty()) cv::imwrite(save_fgr_path, content.fgr_mat); // 预测的前景fgr
if (!content.pha_mat.empty()) cv::imwrite(save_pha_path, content.pha_mat * 255.); // 预测的前景pha
if (!content.merge_mat.empty()) cv::imwrite(save_merge_path, content.merge_mat); // 合成图
}
delete rvm;
}
```
* 输出结果为: (依次为原图、预测的pha、预测的前景fgr、合成图)
<div align='center'>
<img src='resources/test.jpg' height="160px" width="160px">
<img src='resources/test_rvm_pha.jpg' height="160px" width="160px">
<img src='resources/test_rvm_fgr.jpg' height="160px" width="160px">
<img src='resources/test_rvm_merge.jpg' height="160px" width="160px">
</div>
### 5.2 视频抠图案例
#### 5.2.1 ONNXRuntime版本
```c++
#include "lite/lite.h"
// Video Matting Interface
static void test_video()
{
std::string onnx_path = "../hub/onnx/cv/rvm_mobilenetv3_fp32.onnx";
std::string video_path = "../examples/lite/resources/tesla.mp4";
std::string output_path = "../logs/tesla_onnx.mp4";
auto *rvm = new lite::cv::matting::RobustVideoMatting(onnx_path, 16); // 16 threads
std::vector<lite::types::MattingContent> contents;
// 1. video matting.
rvm->detect_video(video_path, output_path, contents, false, 0.4f);
delete rvm;
}
```
#### 5.2.2 MNN版本
```c++
static void test_mnn()
{
#ifdef ENABLE_MNN
std::string mnn_path = "../hub/mnn/cv/rvm_mobilenetv3_fp32-480-640.mnn";
std::string video_path = "../examples/lite/resources/tesla.mp4";
std::string output_path = "../logs/tesla_mnn.mp4";
auto *rvm = new lite::mnn::cv::matting::RobustVideoMatting(mnn_path, 16, 0); // 16 threads
std::vector<lite::types::MattingContent> contents;
// 1. video matting.
rvm->detect_video(video_path, output_path, contents, false);
delete rvm;
#endif
}
```
#### 5.2.3 TNN版本
```C++
static void test_tnn()
{
#ifdef ENABLE_TNN
std::string proto_path = "../hub/tnn/cv/rvm_mobilenetv3_fp32-480-480-sim.opt.tnnproto";
std::string model_path = "../hub/tnn/cv/rvm_mobilenetv3_fp32-480-480-sim.opt.tnnmodel";
std::string video_path = "../examples/lite/resources/test_lite_rvm_1.mp4";
std::string output_path = "../logs/test_lite_rvm_1_tnn.mp4";
auto *rvm = new lite::tnn::cv::matting::RobustVideoMatting(
proto_path, model_path, 16); // 16 threads
std::vector<lite::types::MattingContent> contents;
// 1. video matting.
rvm->detect_video(video_path, output_path, contents, false);
delete rvm;
#endif
}
```
* 输出结果为:
<div align='center'>
<img src='resources/interviewi.gif' height="80px" width="160px">
<img src='resources/interview.gif' height="80px" width="160px">
<img src='resources/dance3i.gif' height="80px" width="160px">
<img src='resources/dance3.gif' height="80px" width="160px">
<br>
<img src='resources/teslai.gif' height="80px" width="160px">
<img src='resources/tesla.gif' height="80px" width="160px">
<img src='resources/b5i.gif' height="80px" width="160px">
<img src='resources/b5.gif' height="80px" width="160px">
</div>
## 6. 编译运行
在MacOS下可以直接编译运行本项目,无需下载其他依赖库。其他系统则需要从[lite.ai.toolkit](https://github.com/DefTruth/lite.ai.toolkit) 中下载源码先编译*lite.ai.toolkit.v0.1.0*动态库。
```shell
git clone --depth=1 https://github.com/DefTruth/RobustVideoMatting.lite.ai.toolkit.git
cd RobustVideoMatting.lite.ai.toolkit
sh ./build.sh
```
* CMakeLists.txt设置
```cmake
cmake_minimum_required(VERSION 3.17)
project(RobustVideoMatting.lite.ai.toolkit)
set(CMAKE_CXX_STANDARD 11)
# setting up lite.ai.toolkit
set(LITE_AI_DIR ${CMAKE_SOURCE_DIR}/lite.ai.toolkit)
set(LITE_AI_INCLUDE_DIR ${LITE_AI_DIR}/include)
set(LITE_AI_LIBRARY_DIR ${LITE_AI_DIR}/lib)
include_directories(${LITE_AI_INCLUDE_DIR})
link_directories(${LITE_AI_LIBRARY_DIR})
set(OpenCV_LIBS
opencv_highgui
opencv_core
opencv_imgcodecs
opencv_imgproc
opencv_video
opencv_videoio
)
# add your executable
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/examples/build)
add_executable(lite_rvm examples/test_lite_rvm.cpp)
target_link_libraries(lite_rvm
lite.ai.toolkit
onnxruntime
MNN # need, if built lite.ai.toolkit with ENABLE_MNN=ON, default OFF
ncnn # need, if built lite.ai.toolkit with ENABLE_NCNN=ON, default OFF
TNN # need, if built lite.ai.toolkit with ENABLE_TNN=ON, default OFF
${OpenCV_LIBS}) # link lite.ai.toolkit & other libs.
```
* building && testing information:
```shell
-- Generating done
-- Build files have been written to: /Users/xxx/Desktop/xxx/RobustVideoMatting.lite.ai.toolkit/examples/build
[ 50%] Building CXX object CMakeFiles/lite_rvm.dir/examples/test_lite_rvm.cpp.o
[100%] Linking CXX executable lite_rvm
[100%] Built target lite_rvm
Testing Start ...
Load ../hub/onnx/cv/rvm_mobilenetv3_fp32.onnx done!
write done! 1/774 done!
write done! 2/774 done!
write done! 3/774 done!
write done! 4/774 done!
write done! 5/774 done!
write done! 6/774 done!
...
write done! 724/774 done!
Testing Successful !
```
![](resources/teslab.gif)
... ...
#!/bin/bash
if [ ! -d ./examples/build ]; then
mkdir ./examples/build
else
rm -rf ./examples/build/*
fi
cd ./examples/build && cmake \
-DCMAKE_BUILD_TYPE=Realese\
-DINCLUDE_OPENCV=ON\
-DENABLE_MNN=OFF\
-DENABLE_NCNN=OFF\
-DENABLE_TNN=OFF\
../.. && make -j1
echo "Testing Start ..."
./lite_rvm
echo "Testing Successful !"
\ No newline at end of file
... ...
rvm_resnet50_fp16.onnx
rvm_resnet50_fp32.onnx
rvm_mobilenetv3_fp16.onnx
\ No newline at end of file
... ...
This file is too large to display.
*.mp4
*.jpg
\ No newline at end of file
... ...
asianboss2.mp4
b5.mp4
dance3.mp4
... ...
This file is too large to display.
不能预览此文件类型
不能预览此文件类型
不能预览此文件类型
//
// Created by DefTruth on 2021/9/20.
//
#include "lite/lite.h"
// Video Matting Interface
static void test_video()
{
std::string onnx_path = "../hub/onnx/cv/rvm_mobilenetv3_fp32.onnx";
std::string video_path = "../resources/interview.mp4";
std::string output_path = "../logs/interview_onnx.mp4";
auto *rvm = new lite::cv::matting::RobustVideoMatting(onnx_path, 16); // 16 threads
std::vector<lite::types::MattingContent> contents;
// 1. video matting.
rvm->detect_video(video_path, output_path, contents, false, 0.25f);
delete rvm;
}
// Image Matting Interface
static void test_image()
{
std::string onnx_path = "../hub/onnx/cv/rvm_mobilenetv3_fp32.onnx";
std::string img_path = "../resources/test.jpg";
std::string img_path_2 = "../resources/test2.png";
std::string save_fgr_path = "../logs/test_rvm_fgr.jpg";
std::string save_pha_path = "../logs/test_rvm_pha.jpg";
std::string save_merge_path = "../logs/test_rvm_merge.jpg";
std::string save_fgr_path_2 = "../logs/test_rvm_fgr_2.jpg";
std::string save_pha_path_2 = "../logs/test_rvm_pha_2.jpg";
std::string save_merge_path_2 = "../logs/test_rvm_merge_2.jpg";
auto *rvm = new lite::cv::matting::RobustVideoMatting(onnx_path, 16); // 16 threads
lite::types::MattingContent content, content_2;
cv::Mat img_bgr = cv::imread(img_path);
cv::Mat img_bgr_2 = cv::imread(img_path_2);
// 1. image matting.
rvm->detect(img_bgr, content, 0.25f);
rvm->detect(img_bgr_2, content_2, 0.25f);
if (content.flag)
{
if (!content.fgr_mat.empty()) cv::imwrite(save_fgr_path, content.fgr_mat);
if (!content.pha_mat.empty()) cv::imwrite(save_pha_path, content.pha_mat * 255.);
if (!content.merge_mat.empty()) cv::imwrite(save_merge_path, content.merge_mat);
std::cout << "Saved " << save_merge_path << "\n";
}
if (content_2.flag)
{
if (!content_2.fgr_mat.empty()) cv::imwrite(save_fgr_path_2, content_2.fgr_mat);
if (!content_2.pha_mat.empty()) cv::imwrite(save_pha_path_2, content_2.pha_mat * 255.);
if (!content_2.merge_mat.empty()) cv::imwrite(save_merge_path_2, content_2.merge_mat);
std::cout << "Saved " << save_merge_path_2 << "\n";
}
delete rvm;
}
static void test_rvm()
{
test_video();
test_image();
}
int main(__unused int argc, __unused char *argv[])
{
test_rvm();
return 0;
}
... ...
//
// AutoTime.hpp
// MNN
//
// Created by MNN on 2018/07/27.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef AutoTime_hpp
#define AutoTime_hpp
#include <stdint.h>
#include <stdio.h>
#include <MNN/MNNDefine.h>
namespace MNN {
class MNN_PUBLIC Timer {
public:
Timer();
~Timer();
Timer(const Timer&) = delete;
Timer(const Timer&&) = delete;
Timer& operator=(const Timer&) = delete;
Timer& operator=(const Timer&&) = delete;
// reset timer
void reset();
// get duration (us) from init or latest reset.
uint64_t durationInUs();
protected:
uint64_t mLastResetTime;
};
/** time tracing util. prints duration between init and deinit. */
class MNN_PUBLIC AutoTime : Timer {
public:
AutoTime(int line, const char* func);
~AutoTime();
AutoTime(const AutoTime&) = delete;
AutoTime(const AutoTime&&) = delete;
AutoTime& operator=(const AutoTime&) = delete;
AutoTime& operator=(const AutoTime&&) = delete;
private:
int mLine;
char* mName;
};
} // namespace MNN
#ifdef MNN_OPEN_TIME_TRACE
#define AUTOTIME MNN::AutoTime ___t(__LINE__, __func__)
#else
#define AUTOTIME
#endif
#endif /* AutoTime_hpp */
... ...
//
// ErrorCode.hpp
// MNN
//
// Created by MNN on 2018/09/18.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef ErrorCode_h
#define ErrorCode_h
namespace MNN {
enum ErrorCode {
#ifdef NO_ERROR
#undef NO_ERROR
#endif // NO_ERROR
NO_ERROR = 0,
OUT_OF_MEMORY = 1,
NOT_SUPPORT = 2,
COMPUTE_SIZE_ERROR = 3,
NO_EXECUTION = 4,
INVALID_VALUE = 5,
// User error
INPUT_DATA_ERROR = 10,
CALL_BACK_STOP = 11,
// Op Resize Error
TENSOR_NOT_SUPPORT = 20,
TENSOR_NEED_DIVIDE = 21,
};
} // namespace MNN
#endif /* ErrorCode_h */
... ...
#ifndef HALIDE_HALIDERUNTIME_H
#define HALIDE_HALIDERUNTIME_H
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
// Note that you should not use "inline" along with HALIDE_ALWAYS_INLINE;
// it is not necessary, and may produce warnings for some build configurations.
#ifdef _MSC_VER
#define HALIDE_ALWAYS_INLINE __forceinline
#define HALIDE_NEVER_INLINE __declspec(noinline)
#else
#define HALIDE_ALWAYS_INLINE __attribute__((always_inline)) inline
#define HALIDE_NEVER_INLINE __attribute__((noinline))
#endif
/** \file
*
* This file declares the routines used by Halide internally in its
* runtime. On platforms that support weak linking, these can be
* replaced with user-defined versions by defining an extern "C"
* function with the same name and signature.
*
* When doing Just In Time (JIT) compilation methods on the Func being
* compiled must be called instead. The corresponding methods are
* documented below.
*
* All of these functions take a "void *user_context" parameter as their
* first argument; if the Halide kernel that calls back to any of these
* functions has been compiled with the UserContext feature set on its Target,
* then the value of that pointer passed from the code that calls the
* Halide kernel is piped through to the function.
*
* Some of these are also useful to call when using the default
* implementation. E.g. halide_shutdown_thread_pool.
*
* Note that even on platforms with weak linking, some linker setups
* may not respect the override you provide. E.g. if the override is
* in a shared library and the halide object files are linked directly
* into the output, the builtin versions of the runtime functions will
* be called. See your linker documentation for more details. On
* Linux, LD_DYNAMIC_WEAK=1 may help.
*
*/
// Forward-declare to suppress warnings if compiling as C.
struct halide_buffer_t;
/** Types in the halide type system. They can be ints, unsigned ints,
* or floats (of various bit-widths), or a handle (which is always 64-bits).
* Note that the int/uint/float values do not imply a specific bit width
* (the bit width is expected to be encoded in a separate value).
*/
typedef enum halide_type_code_t
{
halide_type_int = 0, //!< signed integers
halide_type_uint = 1, //!< unsigned integers
halide_type_float = 2, //!< floating point numbers
halide_type_handle = 3 //!< opaque pointer type (void *)
} halide_type_code_t;
// Note that while __attribute__ can go before or after the declaration,
// __declspec apparently is only allowed before.
#ifndef HALIDE_ATTRIBUTE_ALIGN
#ifdef _MSC_VER
#define HALIDE_ATTRIBUTE_ALIGN(x) __declspec(align(x))
#else
#define HALIDE_ATTRIBUTE_ALIGN(x) __attribute__((aligned(x)))
#endif
#endif
/** A runtime tag for a type in the halide type system. Can be ints,
* unsigned ints, or floats of various bit-widths (the 'bits'
* field). Can also be vectors of the same (by setting the 'lanes'
* field to something larger than one). This struct should be
* exactly 32-bits in size. */
struct halide_type_t {
/** The basic type code: signed integer, unsigned integer, or floating point. */
#if __cplusplus >= 201103L
HALIDE_ATTRIBUTE_ALIGN(1) halide_type_code_t code; // halide_type_code_t
#else
HALIDE_ATTRIBUTE_ALIGN(1) uint8_t code; // halide_type_code_t
#endif
/** The number of bits of precision of a single scalar value of this type. */
HALIDE_ATTRIBUTE_ALIGN(1) uint8_t bits;
/** How many elements in a vector. This is 1 for scalar types. */
HALIDE_ATTRIBUTE_ALIGN(2) uint16_t lanes;
#ifdef __cplusplus
/** Construct a runtime representation of a Halide type from:
* code: The fundamental type from an enum.
* bits: The bit size of one element.
* lanes: The number of vector elements in the type. */
HALIDE_ALWAYS_INLINE halide_type_t(halide_type_code_t code, uint8_t bits, uint16_t lanes = 1)
: code(code), bits(bits), lanes(lanes) {
}
/** Default constructor is required e.g. to declare halide_trace_event
* instances. */
HALIDE_ALWAYS_INLINE halide_type_t() : code((halide_type_code_t)0), bits(0), lanes(0) {}
/** Compare two types for equality. */
HALIDE_ALWAYS_INLINE bool operator==(const halide_type_t &other) const {
return (code == other.code &&
bits == other.bits &&
lanes == other.lanes);
}
HALIDE_ALWAYS_INLINE bool operator!=(const halide_type_t &other) const {
return !(*this == other);
}
/** Size in bytes for a single element, even if width is not 1, of this type. */
HALIDE_ALWAYS_INLINE int bytes() const { return (bits + 7) / 8; }
#endif
};
/** An opaque struct containing per-GPU API implementations of the
* device functions. */
struct halide_device_interface_impl_t;
/** Each GPU API provides a halide_device_interface_t struct pointing
* to the code that manages device allocations. You can access these
* functions directly from the struct member function pointers, or by
* calling the functions declared below. Note that the global
* functions are not available when using Halide as a JIT compiler.
* If you are using raw halide_buffer_t in that context you must use
* the function pointers in the device_interface struct.
*
* The function pointers below are currently the same for every GPU
* API; only the impl field varies. These top-level functions do the
* bookkeeping that is common across all GPU APIs, and then dispatch
* to more API-specific functions via another set of function pointers
* hidden inside the impl field.
*/
struct halide_device_interface_t {
int (*device_malloc)(void *user_context, struct halide_buffer_t *buf,
const struct halide_device_interface_t *device_interface);
int (*device_free)(void *user_context, struct halide_buffer_t *buf);
int (*device_sync)(void *user_context, struct halide_buffer_t *buf);
void (*device_release)(void *user_context,
const struct halide_device_interface_t *device_interface);
int (*copy_to_host)(void *user_context, struct halide_buffer_t *buf);
int (*copy_to_device)(void *user_context, struct halide_buffer_t *buf,
const struct halide_device_interface_t *device_interface);
int (*device_and_host_malloc)(void *user_context, struct halide_buffer_t *buf,
const struct halide_device_interface_t *device_interface);
int (*device_and_host_free)(void *user_context, struct halide_buffer_t *buf);
int (*buffer_copy)(void *user_context, struct halide_buffer_t *src,
const struct halide_device_interface_t *dst_device_interface, struct halide_buffer_t *dst);
int (*device_crop)(void *user_context, const struct halide_buffer_t *src,
struct halide_buffer_t *dst);
int (*device_release_crop)(void *user_context, struct halide_buffer_t *buf);
int (*wrap_native)(void *user_context, struct halide_buffer_t *buf, uint64_t handle,
const struct halide_device_interface_t *device_interface);
int (*detach_native)(void *user_context, struct halide_buffer_t *buf);
const struct halide_device_interface_impl_t *impl;
};
typedef struct halide_dimension_t {
int32_t min, extent, stride;
// Per-dimension flags. None are defined yet (This is reserved for future use).
uint32_t flags;
#ifdef __cplusplus
HALIDE_ALWAYS_INLINE halide_dimension_t() : min(0), extent(0), stride(0), flags(0) {}
HALIDE_ALWAYS_INLINE halide_dimension_t(int32_t m, int32_t e, int32_t s, uint32_t f = 0) :
min(m), extent(e), stride(s), flags(f) {}
HALIDE_ALWAYS_INLINE bool operator==(const halide_dimension_t &other) const {
return (min == other.min) &&
(extent == other.extent) &&
(stride == other.stride) &&
(flags == other.flags);
}
HALIDE_ALWAYS_INLINE bool operator!=(const halide_dimension_t &other) const {
return !(*this == other);
}
#endif
} halide_dimension_t;
#ifdef __cplusplus
} // extern "C"
#endif
typedef enum {halide_buffer_flag_host_dirty = 1,
halide_buffer_flag_device_dirty = 2} halide_buffer_flags;
/**
* The raw representation of an image passed around by generated
* Halide code. It includes some stuff to track whether the image is
* not actually in main memory, but instead on a device (like a
* GPU). For a more convenient C++ wrapper, use Halide::Buffer<T>. */
typedef struct halide_buffer_t {
/** A device-handle for e.g. GPU memory used to back this buffer. */
uint64_t device;
/** The interface used to interpret the above handle. */
const struct halide_device_interface_t *device_interface;
/** A pointer to the start of the data in main memory. In terms of
* the Halide coordinate system, this is the address of the min
* coordinates (defined below). */
uint8_t* host;
/** flags with various meanings. */
uint64_t flags;
/** The type of each buffer element. */
struct halide_type_t type;
/** The dimensionality of the buffer. */
int32_t dimensions;
/** The shape of the buffer. Halide does not own this array - you
* must manage the memory for it yourself. */
halide_dimension_t *dim;
/** Pads the buffer up to a multiple of 8 bytes */
void *padding;
} halide_buffer_t;
#ifdef __cplusplus
namespace {
template<typename T> struct check_is_pointer;
template<typename T> struct check_is_pointer<T *> {};
}
/** Construct the halide equivalent of a C type */
template<typename T>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of() {
// Create a compile-time error if T is not a pointer (without
// using any includes - this code goes into the runtime).
check_is_pointer<T> check;
(void)check;
return halide_type_t(halide_type_handle, 64);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<float>() {
return halide_type_t(halide_type_float, 32);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<double>() {
return halide_type_t(halide_type_float, 64);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<bool>() {
return halide_type_t(halide_type_uint, 1);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<uint8_t>() {
return halide_type_t(halide_type_uint, 8);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<uint16_t>() {
return halide_type_t(halide_type_uint, 16);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<uint32_t>() {
return halide_type_t(halide_type_uint, 32);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<uint64_t>() {
return halide_type_t(halide_type_uint, 64);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<int8_t>() {
return halide_type_t(halide_type_int, 8);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<int16_t>() {
return halide_type_t(halide_type_int, 16);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<int32_t>() {
return halide_type_t(halide_type_int, 32);
}
template<>
HALIDE_ALWAYS_INLINE halide_type_t halide_type_of<int64_t>() {
return halide_type_t(halide_type_int, 64);
}
#endif
#endif // HALIDE_HALIDERUNTIME_H
... ...
//
// ImageProcess.hpp
// MNN
//
// Created by MNN on 2018/09/19.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef ImageProcess_hpp
#define ImageProcess_hpp
#include <MNN/ErrorCode.hpp>
#include <MNN/Matrix.h>
#include <MNN/Tensor.hpp>
namespace MNN {
namespace CV {
enum ImageFormat {
RGBA = 0,
RGB,
BGR,
GRAY,
BGRA,
YUV_NV21 = 11,
YUV_NV12 = 12,
YUV_I420 = 13,
};
enum Filter { NEAREST = 0, BILINEAR = 1, BICUBIC = 2 };
enum Wrap { CLAMP_TO_EDGE = 0, ZERO = 1, REPEAT = 2 };
/**
* handle image process for tensor.
* step:
* 1: Do transform compute and get points
* 2: Sample line and do format convert
* 3: Turn RGBA to float tensor, and do sub and normalize
*/
class MNN_PUBLIC ImageProcess {
public:
struct Inside;
struct Config {
/** data filter */
Filter filterType = NEAREST;
/** format of source data */
ImageFormat sourceFormat = RGBA;
/** format of destination data */
ImageFormat destFormat = RGBA;
// Only valid if the dest type is float
float mean[4] = {0.0f, 0.0f, 0.0f, 0.0f};
float normal[4] = {1.0f, 1.0f, 1.0f, 1.0f};
/** edge wrapper */
Wrap wrap = CLAMP_TO_EDGE;
};
public:
/**
* @brief create image process with given config for given tensor.
* @param config given config.
* @param dstTensor given tensor.
* @return image processor.
*/
static ImageProcess* create(const Config& config, const Tensor* dstTensor = nullptr);
/**
* @brief create image process with given config for given tensor.
* @param means given means
* @param meanCount given means count
* @param normals given normals
* @param normalCount given normal count
* @param sourceFormat format of source data
* @param destFormat format of destination data
* @param dstTensor given tensor.
* @return image processor.
*/
static ImageProcess* create(const ImageFormat sourceFormat = RGBA, const ImageFormat destFormat = RGBA,
const float* means = nullptr, const int meanCount = 0, const float* normals = nullptr,
const int normalCount = 0, const Tensor* dstTensor = nullptr);
~ImageProcess();
/**
* @brief get affine transform matrix.
* @return affine transform matrix.
*/
inline const Matrix& matrix() const {
return mTransform;
}
void setMatrix(const Matrix& matrix);
/**
* @brief convert source data to given tensor.
* @param source source data.
* @param iw source width.
* @param ih source height.
* @param stride number of elements per row. eg: 100 width RGB contains at least 300 elements.
* @param dest given tensor.
* @return result code.
*/
ErrorCode convert(const uint8_t* source, int iw, int ih, int stride, Tensor* dest);
/**
* @brief convert source data to given tensor.
* @param source source data.
* @param iw source width.
* @param ih source height.
* @param stride number of elements per row. eg: 100 width RGB contains at least 300 elements.
* @param dest dest data.
* @param ow output width.
* @param oh output height.
* @param outputBpp output bpp, if 0, set as the save and config.destFormat.
* @param outputStride output stride, if 0, set as ow * outputBpp.
* @param type Only support halide_type_of<uint8_t> and halide_type_of<float>.
* @return result code.
*/
ErrorCode convert(const uint8_t* source, int iw, int ih, int stride, void* dest, int ow, int oh, int outputBpp = 0,
int outputStride = 0, halide_type_t type = halide_type_of<float>());
/**
* @brief create tensor with given data.
* @param w image width.
* @param h image height.
* @param bpp bytes per pixel.
* @param p pixel data pointer.
* @return created tensor.
*/
template <typename T>
static Tensor* createImageTensor(int w, int h, int bpp, void* p = nullptr) {
return createImageTensor(halide_type_of<T>(), w, h, bpp, p);
}
static Tensor* createImageTensor(halide_type_t type, int w, int h, int bpp, void* p = nullptr);
/**
* @brief set padding value when wrap=ZERO.
* @param value padding value.
* @return void.
*/
void setPadding(uint8_t value) {
mPaddingValue = value;
}
private:
ImageProcess(const Config& config);
Matrix mTransform;
Matrix mTransformInvert;
Inside* mInside;
uint8_t mPaddingValue = 0;
};
} // namespace CV
} // namespace MNN
#endif /* ImageProcess_hpp */
... ...
//
// Interpreter.hpp
// MNN
//
// Created by MNN on 2018/07/23.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef Interpreter_hpp
#define Interpreter_hpp
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <MNN/ErrorCode.hpp>
#include <MNN/MNNForwardType.h>
#include <MNN/Tensor.hpp>
namespace MNN {
/** session schedule config */
struct ScheduleConfig {
/** which tensor should be kept */
std::vector<std::string> saveTensors;
/** forward type */
MNNForwardType type = MNN_FORWARD_CPU;
/** CPU:number of threads in parallel , Or GPU: mode setting*/
union {
int numThread = 4;
int mode;
};
/** subpath to run */
struct Path {
std::vector<std::string> inputs;
std::vector<std::string> outputs;
enum Mode {
/**
* Op Mode
* - inputs means the source op, can NOT be empty.
* - outputs means the sink op, can be empty.
* The path will start from source op, then flow when encounter the sink op.
* The sink op will not be compute in this path.
*/
Op = 0,
/**
* Tensor Mode
* - inputs means the inputs tensors, can NOT be empty.
* - outputs means the outputs tensors, can NOT be empty.
* It will find the pipeline that compute outputs from inputs.
*/
Tensor = 1
};
/** running mode */
Mode mode = Op;
};
Path path;
/** backup backend used to create execution when desinated backend do NOT support any op */
MNNForwardType backupType = MNN_FORWARD_CPU;
/** extra backend config */
BackendConfig* backendConfig = nullptr;
};
class Session;
struct Content;
class Tensor;
class Backend;
class Runtime;
class MNN_PUBLIC OperatorInfo {
struct Info;
public:
/** Operator's name*/
const std::string& name() const;
/** Operator's type*/
const std::string& type() const;
/** Operator's flops, in M*/
float flops() const;
protected:
OperatorInfo();
~OperatorInfo();
Info* mContent;
};
typedef std::function<bool(const std::vector<Tensor*>&, const std::string& /*opName*/)> TensorCallBack;
typedef std::function<bool(const std::vector<Tensor*>&, const OperatorInfo*)> TensorCallBackWithInfo;
typedef std::pair<std::map<MNNForwardType, std::shared_ptr<Runtime>>, std::shared_ptr<Runtime>> RuntimeInfo;
/** net data holder. multiple sessions could share same net. */
class MNN_PUBLIC Interpreter {
public:
/**
* @brief create net from file.
* @param file given file.
* @return created net if success, NULL otherwise.
*/
static Interpreter* createFromFile(const char* file);
/**
* @brief create net from buffer.
* @param buffer given data buffer.
* @param size size of data buffer.
* @return created net if success, NULL otherwise.
*/
static Interpreter* createFromBuffer(const void* buffer, size_t size);
~Interpreter();
enum SessionMode {
/** About CallBack, Default Session_Debug*/
/** runSessionWithCallBack is allowed and can get internal op info*/
Session_Debug = 0,
/** runSessionWithCallBack is not valid and can't get any info of op in session*/
Session_Release = 1,
/** About input tenosr, Default Session_Input_Inside*/
/** The input tensor is alloced by session, input data after session resized*/
Session_Input_Inside = 2,
/** The input tensor is alloced by user, set input data before session resize*/
Session_Input_User = 3,
};
/**
* @brief The API shoud be called before create session.
* @param mode session mode
*/
void setSessionMode(SessionMode mode);
/**
* @brief The API shoud be called before create session.
* If the cache exist, try to load cache from file.
* After createSession, try to save cache to file.
* @param cacheFile cache file name
* @param keySize the first `keySize` bytes used as the key to check if the `cacheFile` exists.
*/
void setCacheFile(const char* cacheFile, size_t keySize = 128);
/**
* @brief The API shoud be called after last resize session.
* If resize session generate new cache info, try to rewrite cache file.
* If resize session do not generate any new cache info, just do nothing.
* @param session giveb session
* @param flag Protected param, not used now
*/
ErrorCode updateCacheFile(Session *session, int flag = 0);
public:
/**
* @brief create runtimeInfo seperately with schedule config.
* @param configs session schedule configs.
*/
static RuntimeInfo createRuntime(const std::vector<ScheduleConfig>& configs);
/**
* @brief create session with schedule config. created session will be managed in net.
* @param config session schedule config.
* @return created session if success, NULL otherwise.
*/
Session* createSession(const ScheduleConfig& config);
/**
* @brief create session with schedule config and user-specified runtime.
* @param config session schedule config, runtime runtimeInfo used by the created session.
* @return created session if success, NULL otherwise.
*/
Session* createSession(const ScheduleConfig& config, const RuntimeInfo& runtime);
/**
* @brief create multi-path session with schedule configs. created session will be managed in net.
* @param configs session schedule configs.
* @return created session if success, NULL otherwise.
*/
Session* createMultiPathSession(const std::vector<ScheduleConfig>& configs);
/**
* @brief create multi-path session with schedule configs and user-specified runtime.
created session will be managed in net.
* @param configs session schedule configs.
* @return created session if success, NULL otherwise.
*/
Session* createMultiPathSession(const std::vector<ScheduleConfig>& configs, const RuntimeInfo& runtime);
/**
* @brief release session.
* @param session given session.
* @return true if given session is held by net and is freed.
*/
bool releaseSession(Session* session);
/**
* @brief call this function to get tensors ready. output tensor buffer (host or deviceId) should be retrieved
* after resize of any input tensor.
* @param session given session.
*/
void resizeSession(Session* session);
/**
* @brief call this function if don't need resize or create session any more, it will save a few memory that equal
* to the size of model buffer
*/
void releaseModel();
/**
* @brief Get the model buffer for user to save
* @return std::make_pair(modleBuffer, modelSize).
* @example:
* std::ofstream output("trainResult.alinn")
* auto buffer = net->getModelBuffer();
* output.write((const char*)buffer.first, buffer.second);
*/
std::pair<const void*, size_t> getModelBuffer() const;
/**
* @brief update Session's Tensor to model's Const Op
* @param session given session.
* @return result of running.
*/
ErrorCode updateSessionToModel(Session* session);
/**
* @brief run session.
* @param session given session.
* @return result of running.
*/
ErrorCode runSession(Session* session) const;
/*
* @brief run session.
* @param session given session.
* @param before callback before each op. return true to run the op; return false to skip the op.
* @param after callback after each op. return true to continue running; return false to interrupt the session.
* @param sync synchronously wait for finish of execution or not.
* @return result of running.
*/
ErrorCode runSessionWithCallBack(const Session* session, const TensorCallBack& before, const TensorCallBack& end,
bool sync = false) const;
/*
* @brief run session.
* @param session given session.
* @param before callback before each op. return true to run the op; return false to skip the op.
* @param after callback after each op. return true to continue running; return false to interrupt the session.
* @param sync synchronously wait for finish of execution or not.
* @return result of running.
*/
ErrorCode runSessionWithCallBackInfo(const Session* session, const TensorCallBackWithInfo& before,
const TensorCallBackWithInfo& end, bool sync = false) const;
/**
* @brief get input tensor for given name.
* @param session given session.
* @param name given name. if NULL, return first input.
* @return tensor if found, NULL otherwise.
*/
Tensor* getSessionInput(const Session* session, const char* name);
/**
* @brief get output tensor for given name.
* @param session given session.
* @param name given name. if NULL, return first output.
* @return tensor if found, NULL otherwise.
*/
Tensor* getSessionOutput(const Session* session, const char* name);
enum SessionInfoCode {
/** memory session used in MB, float* */
MEMORY = 0,
/** float operation needed in session in M, float* */
FLOPS = 1,
/** Backends in session in M, int*, length >= 1 + number of configs when create session */
BACKENDS = 2,
ALL
};
/**
* @brief get session info
* @param session given session.
* @param code given info code.
* @param ptr given info ptr, see SessionInfoCode for detail
* @return true if support the code, false otherwise.
*/
bool getSessionInfo(const Session* session, SessionInfoCode code, void* ptr);
/**
* @brief get all output tensors.
* @param session given session.
* @return all output tensors mapped with name.
*/
const std::map<std::string, Tensor*>& getSessionOutputAll(const Session* session) const;
/**
* @brief get all input tensors.
* @param session given session.
* @return all input tensors mapped with name.
*/
const std::map<std::string, Tensor*>& getSessionInputAll(const Session* session) const;
public:
/**
* @brief resize given tensor.
* @param tensor given tensor.
* @param dims new dims. at most 6 dims.
*/
void resizeTensor(Tensor* tensor, const std::vector<int>& dims);
/**
* @brief resize given tensor by nchw.
* @param batch / N.
* @param channel / C.
* @param height / H.
* @param width / W
*/
void resizeTensor(Tensor* tensor, int batch, int channel, int height, int width);
/**
* @brief get backend used to create given tensor.
* @param session given session.
* @param tensor given tensor.
* @return backend used to create given tensor, may be NULL.
*/
const Backend* getBackend(const Session* session, const Tensor* tensor) const;
/**
* @brief get business code (model identifier).
* @return business code.
*/
const char* bizCode() const;
private:
static Interpreter* createFromBufferInternal(Content* net);
Content* mNet = nullptr;
Interpreter(Content* net);
Interpreter(const Interpreter&) = delete;
Interpreter(const Interpreter&&) = delete;
Interpreter& operator=(const Interpreter&) = delete;
Interpreter& operator=(const Interpreter&&) = delete;
};
} // namespace MNN
#endif /* Interpreter_hpp */
... ...
//
// MNNDefine.h
// MNN
//
// Created by MNN on 2018/08/09.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef MNNDefine_h
#define MNNDefine_h
#include <assert.h>
#include <stdio.h>
#if defined(__APPLE__)
#include <TargetConditionals.h>
#if TARGET_OS_IPHONE
#define MNN_BUILD_FOR_IOS
#endif
#endif
#ifdef MNN_USE_LOGCAT
#include <android/log.h>
#define MNN_ERROR(format, ...) __android_log_print(ANDROID_LOG_ERROR, "MNNJNI", format, ##__VA_ARGS__)
#define MNN_PRINT(format, ...) __android_log_print(ANDROID_LOG_INFO, "MNNJNI", format, ##__VA_ARGS__)
#else
#define MNN_PRINT(format, ...) printf(format, ##__VA_ARGS__)
#define MNN_ERROR(format, ...) printf(format, ##__VA_ARGS__)
#endif
#ifdef DEBUG
#define MNN_ASSERT(x) \
{ \
int res = (x); \
if (!res) { \
MNN_ERROR("Error for %s, %d\n", __FILE__, __LINE__); \
assert(res); \
} \
}
#else
#define MNN_ASSERT(x)
#endif
#define FUNC_PRINT(x) MNN_PRINT(#x "=%d in %s, %d \n", x, __func__, __LINE__);
#define FUNC_PRINT_ALL(x, type) MNN_PRINT(#x "=" #type " %" #type " in %s, %d \n", x, __func__, __LINE__);
#define MNN_CHECK(success, log) \
if(!(success)){ \
MNN_ERROR("Check failed: %s ==> %s\n", #success, #log); \
}
#if defined(_MSC_VER)
#if defined(BUILDING_MNN_DLL)
#define MNN_PUBLIC __declspec(dllexport)
#elif defined(USING_MNN_DLL)
#define MNN_PUBLIC __declspec(dllimport)
#else
#define MNN_PUBLIC
#endif
#else
#define MNN_PUBLIC __attribute__((visibility("default")))
#endif
#endif /* MNNDefine_h */
... ...
//
// MNNForwardType.h
// MNN
//
// Created by MNN on 2019/01/19.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef MNNForwardType_h
#define MNNForwardType_h
#include <stdint.h>
#include <stddef.h>
typedef enum {
MNN_FORWARD_CPU = 0,
/*
Firtly find the first available backends not equal to CPU
If no other backends, use cpu
*/
MNN_FORWARD_AUTO = 4,
/*Hand write metal*/
MNN_FORWARD_METAL = 1,
/*NVIDIA GPU API*/
MNN_FORWARD_CUDA = 2,
/*Android / Common Device GPU API*/
MNN_FORWARD_OPENCL = 3,
MNN_FORWARD_OPENGL = 6,
MNN_FORWARD_VULKAN = 7,
/*Android 8.1's NNAPI, Not Support yet. CoreML Now*/
MNN_FORWARD_NN = 5,
/*User can use API from Backend.hpp to add or search Backend*/
MNN_FORWARD_USER_0 = 8,
MNN_FORWARD_USER_1 = 9,
MNN_FORWARD_USER_2 = 10,
MNN_FORWARD_USER_3 = 11,
MNN_FORWARD_ALL,
/* Apply arm extension instruction set to accelerate some Ops, this forward type
is only used in MNN internal, and will be active automatically when user set forward type
to be MNN_FORWARD_CPU and extension instruction set is valid on hardware.
*/
MNN_FORWARD_CPU_EXTENSION
} MNNForwardType;
typedef enum {
// choose one tuning mode Only
MNN_GPU_TUNING_NONE = 1 << 0,/* Forbidden tuning, performance not good */
MNN_GPU_TUNING_HEAVY = 1 << 1,/* heavily tuning, usually not suggested */
MNN_GPU_TUNING_WIDE = 1 << 2,/* widely tuning, performance good. Default */
MNN_GPU_TUNING_NORMAL = 1 << 3,/* normal tuning, performance may be ok */
MNN_GPU_TUNING_FAST = 1 << 4,/* fast tuning, performance may not good */
// choose one opencl memory mode Only
/* User can try OpenCL_MEMORY_BUFFER and OpenCL_MEMORY_IMAGE both,
then choose the better one according to performance*/
MNN_GPU_MEMORY_BUFFER = 1 << 6,/* User assign mode */
MNN_GPU_MEMORY_IMAGE = 1 << 7,/* User assign mode */
} MNNGpuMode;
#ifdef __cplusplus
namespace MNN {
struct BackendConfig {
enum MemoryMode { Memory_Normal = 0, Memory_High, Memory_Low };
MemoryMode memory = Memory_Normal;
enum PowerMode { Power_Normal = 0, Power_High, Power_Low };
PowerMode power = Power_Normal;
enum PrecisionMode { Precision_Normal = 0, Precision_High, Precision_Low };
PrecisionMode precision = Precision_Normal;
/** user defined context */
union {
void* sharedContext = nullptr;
size_t flags; // Valid for CPU Backend
};
};
}; // namespace MNN
#endif
#endif /* MNNForwardType_h */
... ...
//
// MNNSharedContext.h
// MNN
//
// Created by MNN on 2018/10/11.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef MNNSharedContext_h
#define MNNSharedContext_h
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h> /*uint32_t*/
#ifndef VK_DEFINE_HANDLE
#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object;
VK_DEFINE_HANDLE(VkInstance)
VK_DEFINE_HANDLE(VkPhysicalDevice)
VK_DEFINE_HANDLE(VkDevice)
VK_DEFINE_HANDLE(VkQueue)
#endif
struct MNNVulkanContext {
VkInstance pInstance;
VkPhysicalDevice pPhysicalDevice;
VkDevice pDevice;
VkQueue pQueue;
uint32_t iQueueFamilyIndex;
};
#ifdef __cplusplus
}
#endif
#endif /* MNNSharedContext_h */
... ...
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/Matrix.h and docs/SkMatrix_Reference.bmh
on 2018-07-13 08:15:11. Additional documentation and examples can be found at:
https://skia.org/user/api/SkMatrix_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkMatrix_Reference.bmh, run:
bookmaker -b docs -i include/core/Matrix.h -p
to create an updated version of this file.
*/
//
// Modified by jiangxiaotang on 2018/09/19.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef SkMatrix_DEFINED
#define SkMatrix_DEFINED
#include <string.h>
#include <cstdint>
#include <MNN/Rect.h>
namespace MNN {
namespace CV {
/** \class Matrix
Matrix holds a 3x3 matrix for transforming coordinates. This allows mapping
Point and vectors with translation, scaling, skewing, rotation, and
perspective.
Matrix elements are in row major order. Matrix does not have a constructor,
so it must be explicitly initialized. setIdentity() initializes Matrix
so it has no effect. setTranslate(), setScale(), setSkew(), setRotate(), set9 and setAll()
initializes all Matrix elements with the corresponding mapping.
Matrix includes a hidden variable that classifies the type of matrix to
improve performance. Matrix is not thread safe unless getType() is called first.
*/
class MNN_PUBLIC Matrix {
public:
Matrix() {
setIdentity();
}
/** Sets Matrix to scale by (sx, sy). Returned matrix is:
| sx 0 0 |
| 0 sy 0 |
| 0 0 1 |
@param sx horizontal scale factor
@param sy vertical scale factor
@return Matrix with scale
*/
static Matrix MakeScale(float sx, float sy) {
Matrix m;
m.setScale(sx, sy);
return m;
}
/** Sets Matrix to scale by (scale, scale). Returned matrix is:
| scale 0 0 |
| 0 scale 0 |
| 0 0 1 |
@param scale horizontal and vertical scale factor
@return Matrix with scale
*/
static Matrix MakeScale(float scale) {
Matrix m;
m.setScale(scale, scale);
return m;
}
/** Sets Matrix to translate by (dx, dy). Returned matrix is:
| 1 0 dx |
| 0 1 dy |
| 0 0 1 |
@param dx horizontal translation
@param dy vertical translation
@return Matrix with translation
*/
static Matrix MakeTrans(float dx, float dy) {
Matrix m;
m.setTranslate(dx, dy);
return m;
}
/** Sets Matrix to:
| scaleX skewX transX |
| skewY scaleY transY |
| pers0 pers1 pers2 |
@param scaleX horizontal scale factor
@param skewX horizontal skew factor
@param transX horizontal translation
@param skewY vertical skew factor
@param scaleY vertical scale factor
@param transY vertical translation
@param pers0 input x-axis perspective factor
@param pers1 input y-axis perspective factor
@param pers2 perspective scale factor
@return Matrix constructed from parameters
*/
static Matrix MakeAll(float scaleX, float skewX, float transX, float skewY, float scaleY, float transY, float pers0,
float pers1, float pers2) {
Matrix m;
m.setAll(scaleX, skewX, transX, skewY, scaleY, transY, pers0, pers1, pers2);
return m;
}
/** \enum Matrix::TypeMask
Enum of bit fields for mask returned by getType().
Used to identify the complexity of Matrix, to optimize performance.
*/
enum TypeMask {
kIdentity_Mask = 0, //!< identity Matrix; all bits clear
kTranslate_Mask = 0x01, //!< translation Matrix
kScale_Mask = 0x02, //!< scale Matrix
kAffine_Mask = 0x04, //!< skew or rotate Matrix
kPerspective_Mask = 0x08, //!< perspective Matrix
};
/** Returns a bit field describing the transformations the matrix may
perform. The bit field is computed conservatively, so it may include
false positives. For example, when kPerspective_Mask is set, all
other bits are set.
@return kIdentity_Mask, or combinations of: kTranslate_Mask, kScale_Mask,
kAffine_Mask, kPerspective_Mask
*/
TypeMask getType() const {
if (fTypeMask & kUnknown_Mask) {
fTypeMask = this->computeTypeMask();
}
// only return the public masks
return (TypeMask)(fTypeMask & 0xF);
}
/** Returns true if Matrix is identity. Identity matrix is:
| 1 0 0 |
| 0 1 0 |
| 0 0 1 |
@return true if Matrix has no effect
*/
bool isIdentity() const {
return this->getType() == 0;
}
/** Returns true if Matrix at most scales and translates. Matrix may be identity,
contain only scale elements, only translate elements, or both. Matrix form is:
| scale-x 0 translate-x |
| 0 scale-y translate-y |
| 0 0 1 |
@return true if Matrix is identity; or scales, translates, or both
*/
bool isScaleTranslate() const {
return !(this->getType() & ~(kScale_Mask | kTranslate_Mask));
}
/** Returns true if Matrix is identity, or translates. Matrix form is:
| 1 0 translate-x |
| 0 1 translate-y |
| 0 0 1 |
@return true if Matrix is identity, or translates
*/
bool isTranslate() const {
return !(this->getType() & ~(kTranslate_Mask));
}
/** Returns true Matrix maps Rect to another Rect. If true, Matrix is identity,
or scales, or rotates a multiple of 90 degrees, or mirrors on axes. In all
cases, Matrix may also have translation. Matrix form is either:
| scale-x 0 translate-x |
| 0 scale-y translate-y |
| 0 0 1 |
or
| 0 rotate-x translate-x |
| rotate-y 0 translate-y |
| 0 0 1 |
for non-zero values of scale-x, scale-y, rotate-x, and rotate-y.
Also called preservesAxisAlignment(); use the one that provides better inline
documentation.
@return true if Matrix maps one Rect into another
*/
bool rectStaysRect() const {
if (fTypeMask & kUnknown_Mask) {
fTypeMask = this->computeTypeMask();
}
return (fTypeMask & kRectStaysRect_Mask) != 0;
}
/** Returns true Matrix maps Rect to another Rect. If true, Matrix is identity,
or scales, or rotates a multiple of 90 degrees, or mirrors on axes. In all
cases, Matrix may also have translation. Matrix form is either:
| scale-x 0 translate-x |
| 0 scale-y translate-y |
| 0 0 1 |
or
| 0 rotate-x translate-x |
| rotate-y 0 translate-y |
| 0 0 1 |
for non-zero values of scale-x, scale-y, rotate-x, and rotate-y.
Also called rectStaysRect(); use the one that provides better inline
documentation.
@return true if Matrix maps one Rect into another
*/
bool preservesAxisAlignment() const {
return this->rectStaysRect();
}
/** Matrix organizes its values in row order. These members correspond to
each value in Matrix.
*/
static constexpr int kMScaleX = 0; //!< horizontal scale factor
static constexpr int kMSkewX = 1; //!< horizontal skew factor
static constexpr int kMTransX = 2; //!< horizontal translation
static constexpr int kMSkewY = 3; //!< vertical skew factor
static constexpr int kMScaleY = 4; //!< vertical scale factor
static constexpr int kMTransY = 5; //!< vertical translation
static constexpr int kMPersp0 = 6; //!< input x perspective factor
static constexpr int kMPersp1 = 7; //!< input y perspective factor
static constexpr int kMPersp2 = 8; //!< perspective bias
/** Affine arrays are in column major order to match the matrix used by
PDF and XPS.
*/
static constexpr int kAScaleX = 0; //!< horizontal scale factor
static constexpr int kASkewY = 1; //!< vertical skew factor
static constexpr int kASkewX = 2; //!< horizontal skew factor
static constexpr int kAScaleY = 3; //!< vertical scale factor
static constexpr int kATransX = 4; //!< horizontal translation
static constexpr int kATransY = 5; //!< vertical translation
/** Returns one matrix value. Asserts if index is out of range and SK_DEBUG is
defined.
@param index one of: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY,
kMPersp0, kMPersp1, kMPersp2
@return value corresponding to index
*/
float operator[](int index) const {
MNN_ASSERT((unsigned)index < 9);
return fMat[index];
}
/** Returns one matrix value. Asserts if index is out of range and SK_DEBUG is
defined.
@param index one of: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY,
kMPersp0, kMPersp1, kMPersp2
@return value corresponding to index
*/
float get(int index) const {
MNN_ASSERT((unsigned)index < 9);
return fMat[index];
}
/** Returns scale factor multiplied by x-axis input, contributing to x-axis output.
With mapPoints(), scales Point along the x-axis.
@return horizontal scale factor
*/
float getScaleX() const {
return fMat[kMScaleX];
}
/** Returns scale factor multiplied by y-axis input, contributing to y-axis output.
With mapPoints(), scales Point along the y-axis.
@return vertical scale factor
*/
float getScaleY() const {
return fMat[kMScaleY];
}
/** Returns scale factor multiplied by x-axis input, contributing to y-axis output.
With mapPoints(), skews Point along the y-axis.
Skewing both axes can rotate Point.
@return vertical skew factor
*/
float getSkewY() const {
return fMat[kMSkewY];
}
/** Returns scale factor multiplied by y-axis input, contributing to x-axis output.
With mapPoints(), skews Point along the x-axis.
Skewing both axes can rotate Point.
@return horizontal scale factor
*/
float getSkewX() const {
return fMat[kMSkewX];
}
/** Returns translation contributing to x-axis output.
With mapPoints(), moves Point along the x-axis.
@return horizontal translation factor
*/
float getTranslateX() const {
return fMat[kMTransX];
}
/** Returns translation contributing to y-axis output.
With mapPoints(), moves Point along the y-axis.
@return vertical translation factor
*/
float getTranslateY() const {
return fMat[kMTransY];
}
/** Returns factor scaling input x-axis relative to input y-axis.
@return input x-axis perspective factor
*/
float getPerspX() const {
return fMat[kMPersp0];
}
/** Returns factor scaling input y-axis relative to input x-axis.
@return input y-axis perspective factor
*/
float getPerspY() const {
return fMat[kMPersp1];
}
/** Returns writable Matrix value. Asserts if index is out of range and SK_DEBUG is
defined. Clears internal cache anticipating that caller will change Matrix value.
Next call to read Matrix state may recompute cache; subsequent writes to Matrix
value must be followed by dirtyMatrixTypeCache().
@param index one of: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY,
kMPersp0, kMPersp1, kMPersp2
@return writable value corresponding to index
*/
float& operator[](int index) {
MNN_ASSERT((unsigned)index < 9);
this->setTypeMask(kUnknown_Mask);
return fMat[index];
}
/** Sets Matrix value. Asserts if index is out of range and SK_DEBUG is
defined. Safer than operator[]; internal cache is always maintained.
@param index one of: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY,
kMPersp0, kMPersp1, kMPersp2
@param value scalar to store in Matrix
*/
void set(int index, float value) {
MNN_ASSERT((unsigned)index < 9);
fMat[index] = value;
this->setTypeMask(kUnknown_Mask);
}
/** Sets horizontal scale factor.
@param v horizontal scale factor to store
*/
void setScaleX(float v) {
this->set(kMScaleX, v);
}
/** Sets vertical scale factor.
@param v vertical scale factor to store
*/
void setScaleY(float v) {
this->set(kMScaleY, v);
}
/** Sets vertical skew factor.
@param v vertical skew factor to store
*/
void setSkewY(float v) {
this->set(kMSkewY, v);
}
/** Sets horizontal skew factor.
@param v horizontal skew factor to store
*/
void setSkewX(float v) {
this->set(kMSkewX, v);
}
/** Sets horizontal translation.
@param v horizontal translation to store
*/
void setTranslateX(float v) {
this->set(kMTransX, v);
}
/** Sets vertical translation.
@param v vertical translation to store
*/
void setTranslateY(float v) {
this->set(kMTransY, v);
}
/** Sets input x-axis perspective factor, which causes mapXY() to vary input x-axis values
inversely proportional to input y-axis values.
@param v perspective factor
*/
void setPerspX(float v) {
this->set(kMPersp0, v);
}
/** Sets input y-axis perspective factor, which causes mapXY() to vary input y-axis values
inversely proportional to input x-axis values.
@param v perspective factor
*/
void setPerspY(float v) {
this->set(kMPersp1, v);
}
/** Sets all values from parameters. Sets matrix to:
| scaleX skewX transX |
| skewY scaleY transY |
| persp0 persp1 persp2 |
@param scaleX horizontal scale factor to store
@param skewX horizontal skew factor to store
@param transX horizontal translation to store
@param skewY vertical skew factor to store
@param scaleY vertical scale factor to store
@param transY vertical translation to store
@param persp0 input x-axis values perspective factor to store
@param persp1 input y-axis values perspective factor to store
@param persp2 perspective scale factor to store
*/
void setAll(float scaleX, float skewX, float transX, float skewY, float scaleY, float transY, float persp0,
float persp1, float persp2) {
fMat[kMScaleX] = scaleX;
fMat[kMSkewX] = skewX;
fMat[kMTransX] = transX;
fMat[kMSkewY] = skewY;
fMat[kMScaleY] = scaleY;
fMat[kMTransY] = transY;
fMat[kMPersp0] = persp0;
fMat[kMPersp1] = persp1;
fMat[kMPersp2] = persp2;
this->setTypeMask(kUnknown_Mask);
}
/** Copies nine scalar values contained by Matrix into buffer, in member value
ascending order: kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY,
kMPersp0, kMPersp1, kMPersp2.
@param buffer storage for nine scalar values
*/
void get9(float buffer[9]) const {
memcpy(buffer, fMat, 9 * sizeof(float));
}
/** Sets Matrix to nine scalar values in buffer, in member value ascending order:
kMScaleX, kMSkewX, kMTransX, kMSkewY, kMScaleY, kMTransY, kMPersp0, kMPersp1,
kMPersp2.
Sets matrix to:
| buffer[0] buffer[1] buffer[2] |
| buffer[3] buffer[4] buffer[5] |
| buffer[6] buffer[7] buffer[8] |
In the future, set9 followed by get9 may not return the same values. Since Matrix
maps non-homogeneous coordinates, scaling all nine values produces an equivalent
transformation, possibly improving precision.
@param buffer nine scalar values
*/
void set9(const float buffer[9]);
/** Sets Matrix to identity; which has no effect on mapped Point. Sets Matrix to:
| 1 0 0 |
| 0 1 0 |
| 0 0 1 |
Also called setIdentity(); use the one that provides better inline
documentation.
*/
void reset();
/** Sets Matrix to identity; which has no effect on mapped Point. Sets Matrix to:
| 1 0 0 |
| 0 1 0 |
| 0 0 1 |
Also called reset(); use the one that provides better inline
documentation.
*/
void setIdentity() {
this->reset();
}
/** Sets Matrix to translate by (dx, dy).
@param dx horizontal translation
@param dy vertical translation
*/
void setTranslate(float dx, float dy);
/** Sets Matrix to scale by sx and sy, about a pivot point at (px, py).
The pivot point is unchanged when mapped with Matrix.
@param sx horizontal scale factor
@param sy vertical scale factor
@param px pivot x
@param py pivot y
*/
void setScale(float sx, float sy, float px, float py);
/** Sets Matrix to scale by sx and sy about at pivot point at (0, 0).
@param sx horizontal scale factor
@param sy vertical scale factor
*/
void setScale(float sx, float sy);
/** Sets Matrix to rotate by degrees about a pivot point at (px, py).
The pivot point is unchanged when mapped with Matrix.
Positive degrees rotates clockwise.
@param degrees angle of axes relative to upright axes
@param px pivot x
@param py pivot y
*/
void setRotate(float degrees, float px, float py);
/** Sets Matrix to rotate by degrees about a pivot point at (0, 0).
Positive degrees rotates clockwise.
@param degrees angle of axes relative to upright axes
*/
void setRotate(float degrees);
/** Sets Matrix to rotate by sinValue and cosValue, about a pivot point at (px, py).
The pivot point is unchanged when mapped with Matrix.
Vector (sinValue, cosValue) describes the angle of rotation relative to (0, 1).
Vector length specifies scale.
@param sinValue rotation vector x-axis component
@param cosValue rotation vector y-axis component
@param px pivot x-axis
@param py pivot y-axis
*/
void setSinCos(float sinValue, float cosValue, float px, float py);
/** Sets Matrix to rotate by sinValue and cosValue, about a pivot point at (0, 0).
Vector (sinValue, cosValue) describes the angle of rotation relative to (0, 1).
Vector length specifies scale.
@param sinValue rotation vector x-axis component
@param cosValue rotation vector y-axis component
*/
void setSinCos(float sinValue, float cosValue);
/** Sets Matrix to skew by kx and ky, about a pivot point at (px, py).
The pivot point is unchanged when mapped with Matrix.
@param kx horizontal skew factor
@param ky vertical skew factor
@param px pivot x
@param py pivot y
*/
void setSkew(float kx, float ky, float px, float py);
/** Sets Matrix to skew by kx and ky, about a pivot point at (0, 0).
@param kx horizontal skew factor
@param ky vertical skew factor
*/
void setSkew(float kx, float ky);
/** Sets Matrix to Matrix a multiplied by Matrix b. Either a or b may be this.
Given:
| A B C | | J K L |
a = | D E F |, b = | M N O |
| G H I | | P Q R |
sets Matrix to:
| A B C | | J K L | | AJ+BM+CP AK+BN+CQ AL+BO+CR |
a * b = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR |
| G H I | | P Q R | | GJ+HM+IP GK+HN+IQ GL+HO+IR |
@param a Matrix on left side of multiply expression
@param b Matrix on right side of multiply expression
*/
void setConcat(const Matrix& a, const Matrix& b);
/** Sets Matrix to Matrix multiplied by Matrix constructed from translation (dx, dy).
This can be thought of as moving the point to be mapped before applying Matrix.
Given:
| A B C | | 1 0 dx |
Matrix = | D E F |, T(dx, dy) = | 0 1 dy |
| G H I | | 0 0 1 |
sets Matrix to:
| A B C | | 1 0 dx | | A B A*dx+B*dy+C |
Matrix * T(dx, dy) = | D E F | | 0 1 dy | = | D E D*dx+E*dy+F |
| G H I | | 0 0 1 | | G H G*dx+H*dy+I |
@param dx x-axis translation before applying Matrix
@param dy y-axis translation before applying Matrix
*/
void preTranslate(float dx, float dy);
/** Sets Matrix to Matrix multiplied by Matrix constructed from scaling by (sx, sy)
about pivot point (px, py).
This can be thought of as scaling about a pivot point before applying Matrix.
Given:
| A B C | | sx 0 dx |
Matrix = | D E F |, S(sx, sy, px, py) = | 0 sy dy |
| G H I | | 0 0 1 |
where
dx = px - sx * px
dy = py - sy * py
sets Matrix to:
| A B C | | sx 0 dx | | A*sx B*sy A*dx+B*dy+C |
Matrix * S(sx, sy, px, py) = | D E F | | 0 sy dy | = | D*sx E*sy D*dx+E*dy+F |
| G H I | | 0 0 1 | | G*sx H*sy G*dx+H*dy+I |
@param sx horizontal scale factor
@param sy vertical scale factor
@param px pivot x
@param py pivot y
*/
void preScale(float sx, float sy, float px, float py);
/** Sets Matrix to Matrix multiplied by Matrix constructed from scaling by (sx, sy)
about pivot point (0, 0).
This can be thought of as scaling about the origin before applying Matrix.
Given:
| A B C | | sx 0 0 |
Matrix = | D E F |, S(sx, sy) = | 0 sy 0 |
| G H I | | 0 0 1 |
sets Matrix to:
| A B C | | sx 0 0 | | A*sx B*sy C |
Matrix * S(sx, sy) = | D E F | | 0 sy 0 | = | D*sx E*sy F |
| G H I | | 0 0 1 | | G*sx H*sy I |
@param sx horizontal scale factor
@param sy vertical scale factor
*/
void preScale(float sx, float sy);
/** Sets Matrix to Matrix multiplied by Matrix constructed from rotating by degrees
about pivot point (px, py).
This can be thought of as rotating about a pivot point before applying Matrix.
Positive degrees rotates clockwise.
Given:
| A B C | | c -s dx |
Matrix = | D E F |, R(degrees, px, py) = | s c dy |
| G H I | | 0 0 1 |
where
c = cos(degrees)
s = sin(degrees)
dx = s * py + (1 - c) * px
dy = -s * px + (1 - c) * py
sets Matrix to:
| A B C | | c -s dx | | Ac+Bs -As+Bc A*dx+B*dy+C |
Matrix * R(degrees, px, py) = | D E F | | s c dy | = | Dc+Es -Ds+Ec D*dx+E*dy+F |
| G H I | | 0 0 1 | | Gc+Hs -Gs+Hc G*dx+H*dy+I |
@param degrees angle of axes relative to upright axes
@param px pivot x
@param py pivot y
*/
void preRotate(float degrees, float px, float py);
/** Sets Matrix to Matrix multiplied by Matrix constructed from rotating by degrees
about pivot point (0, 0).
This can be thought of as rotating about the origin before applying Matrix.
Positive degrees rotates clockwise.
Given:
| A B C | | c -s 0 |
Matrix = | D E F |, R(degrees, px, py) = | s c 0 |
| G H I | | 0 0 1 |
where
c = cos(degrees)
s = sin(degrees)
sets Matrix to:
| A B C | | c -s 0 | | Ac+Bs -As+Bc C |
Matrix * R(degrees, px, py) = | D E F | | s c 0 | = | Dc+Es -Ds+Ec F |
| G H I | | 0 0 1 | | Gc+Hs -Gs+Hc I |
@param degrees angle of axes relative to upright axes
*/
void preRotate(float degrees);
/** Sets Matrix to Matrix multiplied by Matrix constructed from skewing by (kx, ky)
about pivot point (px, py).
This can be thought of as skewing about a pivot point before applying Matrix.
Given:
| A B C | | 1 kx dx |
Matrix = | D E F |, K(kx, ky, px, py) = | ky 1 dy |
| G H I | | 0 0 1 |
where
dx = -kx * py
dy = -ky * px
sets Matrix to:
| A B C | | 1 kx dx | | A+B*ky A*kx+B A*dx+B*dy+C |
Matrix * K(kx, ky, px, py) = | D E F | | ky 1 dy | = | D+E*ky D*kx+E D*dx+E*dy+F |
| G H I | | 0 0 1 | | G+H*ky G*kx+H G*dx+H*dy+I |
@param kx horizontal skew factor
@param ky vertical skew factor
@param px pivot x
@param py pivot y
*/
void preSkew(float kx, float ky, float px, float py);
/** Sets Matrix to Matrix multiplied by Matrix constructed from skewing by (kx, ky)
about pivot point (0, 0).
This can be thought of as skewing about the origin before applying Matrix.
Given:
| A B C | | 1 kx 0 |
Matrix = | D E F |, K(kx, ky) = | ky 1 0 |
| G H I | | 0 0 1 |
sets Matrix to:
| A B C | | 1 kx 0 | | A+B*ky A*kx+B C |
Matrix * K(kx, ky) = | D E F | | ky 1 0 | = | D+E*ky D*kx+E F |
| G H I | | 0 0 1 | | G+H*ky G*kx+H I |
@param kx horizontal skew factor
@param ky vertical skew factor
*/
void preSkew(float kx, float ky);
/** Sets Matrix to Matrix multiplied by Matrix other.
This can be thought of mapping by other before applying Matrix.
Given:
| A B C | | J K L |
Matrix = | D E F |, other = | M N O |
| G H I | | P Q R |
sets Matrix to:
| A B C | | J K L | | AJ+BM+CP AK+BN+CQ AL+BO+CR |
Matrix * other = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR |
| G H I | | P Q R | | GJ+HM+IP GK+HN+IQ GL+HO+IR |
@param other Matrix on right side of multiply expression
*/
void preConcat(const Matrix& other);
/** Sets Matrix to Matrix constructed from translation (dx, dy) multiplied by Matrix.
This can be thought of as moving the point to be mapped after applying Matrix.
Given:
| J K L | | 1 0 dx |
Matrix = | M N O |, T(dx, dy) = | 0 1 dy |
| P Q R | | 0 0 1 |
sets Matrix to:
| 1 0 dx | | J K L | | J+dx*P K+dx*Q L+dx*R |
T(dx, dy) * Matrix = | 0 1 dy | | M N O | = | M+dy*P N+dy*Q O+dy*R |
| 0 0 1 | | P Q R | | P Q R |
@param dx x-axis translation after applying Matrix
@param dy y-axis translation after applying Matrix
*/
void postTranslate(float dx, float dy);
/** Sets Matrix to Matrix constructed from scaling by (sx, sy) about pivot point
(px, py), multiplied by Matrix.
This can be thought of as scaling about a pivot point after applying Matrix.
Given:
| J K L | | sx 0 dx |
Matrix = | M N O |, S(sx, sy, px, py) = | 0 sy dy |
| P Q R | | 0 0 1 |
where
dx = px - sx * px
dy = py - sy * py
sets Matrix to:
| sx 0 dx | | J K L | | sx*J+dx*P sx*K+dx*Q sx*L+dx+R |
S(sx, sy, px, py) * Matrix = | 0 sy dy | | M N O | = | sy*M+dy*P sy*N+dy*Q sy*O+dy*R |
| 0 0 1 | | P Q R | | P Q R |
@param sx horizontal scale factor
@param sy vertical scale factor
@param px pivot x
@param py pivot y
*/
void postScale(float sx, float sy, float px, float py);
/** Sets Matrix to Matrix constructed from scaling by (sx, sy) about pivot point
(0, 0), multiplied by Matrix.
This can be thought of as scaling about the origin after applying Matrix.
Given:
| J K L | | sx 0 0 |
Matrix = | M N O |, S(sx, sy) = | 0 sy 0 |
| P Q R | | 0 0 1 |
sets Matrix to:
| sx 0 0 | | J K L | | sx*J sx*K sx*L |
S(sx, sy) * Matrix = | 0 sy 0 | | M N O | = | sy*M sy*N sy*O |
| 0 0 1 | | P Q R | | P Q R |
@param sx horizontal scale factor
@param sy vertical scale factor
*/
void postScale(float sx, float sy);
/** Sets Matrix to Matrix constructed from scaling by (1/divx, 1/divy) about pivot point (px, py), multiplied by
Matrix.
Returns false if either divx or divy is zero.
Given:
| J K L | | sx 0 0 |
Matrix = | M N O |, I(divx, divy) = | 0 sy 0 |
| P Q R | | 0 0 1 |
where
sx = 1 / divx
sy = 1 / divy
sets Matrix to:
| sx 0 0 | | J K L | | sx*J sx*K sx*L |
I(divx, divy) * Matrix = | 0 sy 0 | | M N O | = | sy*M sy*N sy*O |
| 0 0 1 | | P Q R | | P Q R |
@param divx integer divisor for inverse scale in x
@param divy integer divisor for inverse scale in y
@return true on successful scale
*/
bool postIDiv(int divx, int divy);
/** Sets Matrix to Matrix constructed from rotating by degrees about pivot point
(px, py), multiplied by Matrix.
This can be thought of as rotating about a pivot point after applying Matrix.
Positive degrees rotates clockwise.
Given:
| J K L | | c -s dx |
Matrix = | M N O |, R(degrees, px, py) = | s c dy |
| P Q R | | 0 0 1 |
where
c = cos(degrees)
s = sin(degrees)
dx = s * py + (1 - c) * px
dy = -s * px + (1 - c) * py
sets Matrix to:
|c -s dx| |J K L| |cJ-sM+dx*P cK-sN+dx*Q cL-sO+dx+R|
R(degrees, px, py) * Matrix = |s c dy| |M N O| = |sJ+cM+dy*P sK+cN+dy*Q sL+cO+dy*R|
|0 0 1| |P Q R| | P Q R|
@param degrees angle of axes relative to upright axes
@param px pivot x
@param py pivot y
*/
void postRotate(float degrees, float px, float py);
/** Sets Matrix to Matrix constructed from rotating by degrees about pivot point
(0, 0), multiplied by Matrix.
This can be thought of as rotating about the origin after applying Matrix.
Positive degrees rotates clockwise.
Given:
| J K L | | c -s 0 |
Matrix = | M N O |, R(degrees, px, py) = | s c 0 |
| P Q R | | 0 0 1 |
where
c = cos(degrees)
s = sin(degrees)
sets Matrix to:
| c -s dx | | J K L | | cJ-sM cK-sN cL-sO |
R(degrees, px, py) * Matrix = | s c dy | | M N O | = | sJ+cM sK+cN sL+cO |
| 0 0 1 | | P Q R | | P Q R |
@param degrees angle of axes relative to upright axes
*/
void postRotate(float degrees);
/** Sets Matrix to Matrix constructed from skewing by (kx, ky) about pivot point
(px, py), multiplied by Matrix.
This can be thought of as skewing about a pivot point after applying Matrix.
Given:
| J K L | | 1 kx dx |
Matrix = | M N O |, K(kx, ky, px, py) = | ky 1 dy |
| P Q R | | 0 0 1 |
where
dx = -kx * py
dy = -ky * px
sets Matrix to:
| 1 kx dx| |J K L| |J+kx*M+dx*P K+kx*N+dx*Q L+kx*O+dx+R|
K(kx, ky, px, py) * Matrix = |ky 1 dy| |M N O| = |ky*J+M+dy*P ky*K+N+dy*Q ky*L+O+dy*R|
| 0 0 1| |P Q R| | P Q R|
@param kx horizontal skew factor
@param ky vertical skew factor
@param px pivot x
@param py pivot y
*/
void postSkew(float kx, float ky, float px, float py);
/** Sets Matrix to Matrix constructed from skewing by (kx, ky) about pivot point
(0, 0), multiplied by Matrix.
This can be thought of as skewing about the origin after applying Matrix.
Given:
| J K L | | 1 kx 0 |
Matrix = | M N O |, K(kx, ky) = | ky 1 0 |
| P Q R | | 0 0 1 |
sets Matrix to:
| 1 kx 0 | | J K L | | J+kx*M K+kx*N L+kx*O |
K(kx, ky) * Matrix = | ky 1 0 | | M N O | = | ky*J+M ky*K+N ky*L+O |
| 0 0 1 | | P Q R | | P Q R |
@param kx horizontal skew factor
@param ky vertical skew factor
*/
void postSkew(float kx, float ky);
/** Sets Matrix to Matrix other multiplied by Matrix.
This can be thought of mapping by other after applying Matrix.
Given:
| J K L | | A B C |
Matrix = | M N O |, other = | D E F |
| P Q R | | G H I |
sets Matrix to:
| A B C | | J K L | | AJ+BM+CP AK+BN+CQ AL+BO+CR |
other * Matrix = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR |
| G H I | | P Q R | | GJ+HM+IP GK+HN+IQ GL+HO+IR |
@param other Matrix on left side of multiply expression
*/
void postConcat(const Matrix& other);
/** \enum Matrix::ScaleToFit
ScaleToFit describes how Matrix is constructed to map one Rect to another.
ScaleToFit may allow Matrix to have unequal horizontal and vertical scaling,
or may restrict Matrix to square scaling. If restricted, ScaleToFit specifies
how Matrix maps to the side or center of the destination Rect.
*/
enum ScaleToFit {
kFill_ScaleToFit, //!< scales in x and y to fill destination Rect
kStart_ScaleToFit, //!< scales and aligns to left and top
kCenter_ScaleToFit, //!< scales and aligns to center
kEnd_ScaleToFit, //!< scales and aligns to right and bottom
};
/** Sets Matrix to scale and translate src Rect to dst Rect. stf selects whether
mapping completely fills dst or preserves the aspect ratio, and how to align
src within dst. Returns false if src is empty, and sets Matrix to identity.
Returns true if dst is empty, and sets Matrix to:
| 0 0 0 |
| 0 0 0 |
| 0 0 1 |
@param src Rect to map from
@param dst Rect to map to
@param stf one of: kFill_ScaleToFit, kStart_ScaleToFit,
kCenter_ScaleToFit, kEnd_ScaleToFit
@return true if Matrix can represent Rect mapping
*/
bool setRectToRect(const Rect& src, const Rect& dst, ScaleToFit stf);
/** Returns Matrix set to scale and translate src Rect to dst Rect. stf selects
whether mapping completely fills dst or preserves the aspect ratio, and how to
align src within dst. Returns the identity Matrix if src is empty. If dst is
empty, returns Matrix set to:
| 0 0 0 |
| 0 0 0 |
| 0 0 1 |
@param src Rect to map from
@param dst Rect to map to
@param stf one of: kFill_ScaleToFit, kStart_ScaleToFit,
kCenter_ScaleToFit, kEnd_ScaleToFit
@return Matrix mapping src to dst
*/
static Matrix MakeRectToRect(const Rect& src, const Rect& dst, ScaleToFit stf) {
Matrix m;
m.setRectToRect(src, dst, stf);
return m;
}
/** Sets Matrix to map src to dst. count must be zero or greater, and four or less.
If count is zero, sets Matrix to identity and returns true.
If count is one, sets Matrix to translate and returns true.
If count is two or more, sets Matrix to map Point if possible; returns false
if Matrix cannot be constructed. If count is four, Matrix may include
perspective.
@param src Point to map from
@param dst Point to map to
@param count number of Point in src and dst
@return true if Matrix was constructed successfully
*/
bool setPolyToPoly(const Point src[], const Point dst[], int count);
/** Sets inverse to reciprocal matrix, returning true if Matrix can be inverted.
Geometrically, if Matrix maps from source to destination, inverse Matrix
maps from destination to source. If Matrix can not be inverted, inverse is
unchanged.
@param inverse storage for inverted Matrix; may be nullptr
@return true if Matrix can be inverted
*/
bool invert(Matrix* inverse) const {
// Allow the trivial case to be inlined.
if (this->isIdentity()) {
if (inverse) {
inverse->reset();
}
return true;
}
return this->invertNonIdentity(inverse);
}
/** Fills affine with identity values in column major order.
Sets affine to:
| 1 0 0 |
| 0 1 0 |
Affine 3x2 matrices in column major order are used by OpenGL and XPS.
@param affine storage for 3x2 affine matrix
*/
static void SetAffineIdentity(float affine[6]);
/** Fills affine in column major order. Sets affine to:
| scale-x skew-x translate-x |
| skew-y scale-y translate-y |
If Matrix contains perspective, returns false and leaves affine unchanged.
@param affine storage for 3x2 affine matrix; may be nullptr
@return true if Matrix does not contain perspective
*/
bool asAffine(float affine[6]) const;
/** Sets Matrix to affine values, passed in column major order. Given affine,
column, then row, as:
| scale-x skew-x translate-x |
| skew-y scale-y translate-y |
Matrix is set, row, then column, to:
| scale-x skew-x translate-x |
| skew-y scale-y translate-y |
| 0 0 1 |
@param affine 3x2 affine matrix
*/
void setAffine(const float affine[6]);
/** Maps src Point array of length count to dst Point array of equal or greater
length. Point are mapped by multiplying each Point by Matrix. Given:
| A B C | | x |
Matrix = | D E F |, pt = | y |
| G H I | | 1 |
where
for (i = 0; i < count; ++i) {
x = src[i].fX
y = src[i].fY
}
each dst Point is computed as:
|A B C| |x| Ax+By+C Dx+Ey+F
Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , -------
|G H I| |1| Gx+Hy+I Gx+Hy+I
src and dst may point to the same storage.
@param dst storage for mapped Point
@param src Point to transform
@param count number of Point to transform
*/
void mapPoints(Point dst[], const Point src[], int count) const {
MNN_ASSERT((dst && src && count > 0) || 0 == count);
// no partial overlap
MNN_ASSERT(src == dst || &dst[count] <= &src[0] || &src[count] <= &dst[0]);
this->getMapPtsProc()(*this, dst, src, count);
}
/** Maps pts Point array of length count in place. Point are mapped by multiplying
each Point by Matrix. Given:
| A B C | | x |
Matrix = | D E F |, pt = | y |
| G H I | | 1 |
where
for (i = 0; i < count; ++i) {
x = pts[i].fX
y = pts[i].fY
}
each resulting pts Point is computed as:
|A B C| |x| Ax+By+C Dx+Ey+F
Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , -------
|G H I| |1| Gx+Hy+I Gx+Hy+I
@param pts storage for mapped Point
@param count number of Point to transform
*/
void mapPoints(Point pts[], int count) const {
this->mapPoints(pts, pts, count);
}
/** Maps Point (x, y) to result. Point is mapped by multiplying by Matrix. Given:
| A B C | | x |
Matrix = | D E F |, pt = | y |
| G H I | | 1 |
result is computed as:
|A B C| |x| Ax+By+C Dx+Ey+F
Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , -------
|G H I| |1| Gx+Hy+I Gx+Hy+I
@param x x-axis value of Point to map
@param y y-axis value of Point to map
@param result storage for mapped Point
*/
void mapXY(float x, float y, Point* result) const {
this->getMapXYProc()(*this, x, y, result);
}
/** Returns Point (x, y) multiplied by Matrix. Given:
| A B C | | x |
Matrix = | D E F |, pt = | y |
| G H I | | 1 |
result is computed as:
|A B C| |x| Ax+By+C Dx+Ey+F
Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , -------
|G H I| |1| Gx+Hy+I Gx+Hy+I
@param x x-axis value of Point to map
@param y y-axis value of Point to map
@return mapped Point
*/
Point mapXY(float x, float y) const {
Point result;
this->getMapXYProc()(*this, x, y, &result);
return result;
}
/** Sets dst to bounds of src corners mapped by Matrix.
Returns true if mapped corners are dst corners.
Returned value is the same as calling rectStaysRect().
@param dst storage for bounds of mapped Point
@param src Rect to map
@return true if dst is equivalent to mapped src
*/
bool mapRect(Rect* dst, const Rect& src) const;
/** Sets rect to bounds of rect corners mapped by Matrix.
Returns true if mapped corners are computed rect corners.
Returned value is the same as calling rectStaysRect().
@param rect rectangle to map, and storage for bounds of mapped corners
@return true if result is equivalent to mapped src
*/
bool mapRect(Rect* rect) const {
return this->mapRect(rect, *rect);
}
/** Returns bounds of src corners mapped by Matrix.
@param src rectangle to map
@return mapped bounds
*/
Rect mapRect(const Rect& src) const {
Rect dst;
(void)this->mapRect(&dst, src);
return dst;
}
/** Sets dst to bounds of src corners mapped by Matrix. If matrix contains
elements other than scale or translate: asserts if SK_DEBUG is defined;
otherwise, results are undefined.
@param dst storage for bounds of mapped Point
@param src Rect to map
*/
void mapRectScaleTranslate(Rect* dst, const Rect& src) const;
/** Returns true if Matrix equals m, using an efficient comparison.
Returns false when the sign of zero values is the different; when one
matrix has positive zero value and the other has negative zero value.
Returns true even when both Matrix contain NaN.
NaN never equals any value, including itself. To improve performance, NaN values
are treated as bit patterns that are equal if their bit patterns are equal.
@param m Matrix to compare
@return true if m and Matrix are represented by identical bit patterns
*/
bool cheapEqualTo(const Matrix& m) const {
return 0 == memcmp(fMat, m.fMat, sizeof(fMat));
}
/** Compares a and b; returns true if a and b are numerically equal. Returns true
even if sign of zero values are different. Returns false if either Matrix
contains NaN, even if the other Matrix also contains NaN.
@param a Matrix to compare
@param b Matrix to compare
@return true if Matrix a and Matrix b are numerically equal
*/
friend MNN_PUBLIC bool operator==(const Matrix& a, const Matrix& b);
/** Compares a and b; returns true if a and b are not numerically equal. Returns false
even if sign of zero values are different. Returns true if either Matrix
contains NaN, even if the other Matrix also contains NaN.
@param a Matrix to compare
@param b Matrix to compare
@return true if Matrix a and Matrix b are numerically not equal
*/
friend MNN_PUBLIC bool operator!=(const Matrix& a, const Matrix& b) {
return !(a == b);
}
/** Writes text representation of Matrix to standard output. Floating point values
are written with limited precision; it may not be possible to reconstruct
original Matrix from output.
*/
void dump() const;
/** Returns the minimum scaling factor of Matrix by decomposing the scaling and
skewing elements.
Returns -1 if scale factor overflows or Matrix contains perspective.
@return minimum scale factor
*/
float getMinScale() const;
/** Returns the maximum scaling factor of Matrix by decomposing the scaling and
skewing elements.
Returns -1 if scale factor overflows or Matrix contains perspective.
@return maximum scale factor
*/
float getMaxScale() const;
/** Sets scaleFactors[0] to the minimum scaling factor, and scaleFactors[1] to the
maximum scaling factor. Scaling factors are computed by decomposing
the Matrix scaling and skewing elements.
Returns true if scaleFactors are found; otherwise, returns false and sets
scaleFactors to undefined values.
@param scaleFactors storage for minimum and maximum scale factors
@return true if scale factors were computed correctly
*/
bool getMinMaxScales(float scaleFactors[2]) const;
/** Returns reference to const identity Matrix. Returned Matrix is set to:
| 1 0 0 |
| 0 1 0 |
| 0 0 1 |
@return const identity Matrix
*/
static const Matrix& I();
/** Returns reference to a const Matrix with invalid values. Returned Matrix is set
to:
| SK_ScalarMax SK_ScalarMax SK_ScalarMax |
| SK_ScalarMax SK_ScalarMax SK_ScalarMax |
| SK_ScalarMax SK_ScalarMax SK_ScalarMax |
@return const invalid Matrix
*/
static const Matrix& InvalidMatrix();
/** Returns Matrix a multiplied by Matrix b.
Given:
| A B C | | J K L |
a = | D E F |, b = | M N O |
| G H I | | P Q R |
sets Matrix to:
| A B C | | J K L | | AJ+BM+CP AK+BN+CQ AL+BO+CR |
a * b = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR |
| G H I | | P Q R | | GJ+HM+IP GK+HN+IQ GL+HO+IR |
@param a Matrix on left side of multiply expression
@param b Matrix on right side of multiply expression
@return Matrix computed from a times b
*/
static Matrix Concat(const Matrix& a, const Matrix& b) {
Matrix result;
result.setConcat(a, b);
return result;
}
/** Sets internal cache to unknown state. Use to force update after repeated
modifications to Matrix element reference returned by operator[](int index).
*/
void dirtyMatrixTypeCache() {
this->setTypeMask(kUnknown_Mask);
}
/** Initializes Matrix with scale and translate elements.
| sx 0 tx |
| 0 sy ty |
| 0 0 1 |
@param sx horizontal scale factor to store
@param sy vertical scale factor to store
@param tx horizontal translation to store
@param ty vertical translation to store
*/
void setScaleTranslate(float sx, float sy, float tx, float ty) {
fMat[kMScaleX] = sx;
fMat[kMSkewX] = 0;
fMat[kMTransX] = tx;
fMat[kMSkewY] = 0;
fMat[kMScaleY] = sy;
fMat[kMTransY] = ty;
fMat[kMPersp0] = 0;
fMat[kMPersp1] = 0;
fMat[kMPersp2] = 1;
unsigned mask = 0;
if (sx != 1 || sy != 1) {
mask |= kScale_Mask;
}
if (tx || ty) {
mask |= kTranslate_Mask;
}
this->setTypeMask(mask | kRectStaysRect_Mask);
}
/** Returns true if all elements of the matrix are finite. Returns false if any
element is infinity, or NaN.
@return true if matrix has only finite elements
*/
private:
/** Set if the matrix will map a rectangle to another rectangle. This
can be true if the matrix is scale-only, or rotates a multiple of
90 degrees.
This bit will be set on identity matrices
*/
static constexpr int kRectStaysRect_Mask = 0x10;
/** Set if the perspective bit is valid even though the rest of
the matrix is Unknown.
*/
static constexpr int kOnlyPerspectiveValid_Mask = 0x40;
static constexpr int kUnknown_Mask = 0x80;
static constexpr int kORableMasks = kTranslate_Mask | kScale_Mask | kAffine_Mask | kPerspective_Mask;
static constexpr int kAllMasks =
kTranslate_Mask | kScale_Mask | kAffine_Mask | kPerspective_Mask | kRectStaysRect_Mask;
float fMat[9];
mutable uint32_t fTypeMask;
static void ComputeInv(float dst[9], const float src[9], double invDet, bool isPersp);
uint8_t computeTypeMask() const;
uint8_t computePerspectiveTypeMask() const;
void setTypeMask(int mask) {
// allow kUnknown or a valid mask
MNN_ASSERT(kUnknown_Mask == mask || (mask & kAllMasks) == mask ||
((kUnknown_Mask | kOnlyPerspectiveValid_Mask) & mask) ==
(kUnknown_Mask | kOnlyPerspectiveValid_Mask));
fTypeMask = (uint8_t)(mask);
}
void orTypeMask(int mask) {
MNN_ASSERT((mask & kORableMasks) == mask);
fTypeMask = (uint8_t)(fTypeMask | mask);
}
void clearTypeMask(int mask) {
// only allow a valid mask
MNN_ASSERT((mask & kAllMasks) == mask);
fTypeMask = fTypeMask & ~mask;
}
TypeMask getPerspectiveTypeMaskOnly() const {
if ((fTypeMask & kUnknown_Mask) && !(fTypeMask & kOnlyPerspectiveValid_Mask)) {
fTypeMask = this->computePerspectiveTypeMask();
}
return (TypeMask)(fTypeMask & 0xF);
}
/** Returns true if we already know that the matrix is identity;
false otherwise.
*/
bool isTriviallyIdentity() const {
if (fTypeMask & kUnknown_Mask) {
return false;
}
return ((fTypeMask & 0xF) == 0);
}
inline void updateTranslateMask() {
if ((fMat[kMTransX] != 0) | (fMat[kMTransY] != 0)) {
fTypeMask |= kTranslate_Mask;
} else {
fTypeMask &= ~kTranslate_Mask;
}
}
typedef void (*MapXYProc)(const Matrix& mat, float x, float y, Point* result);
static MapXYProc GetMapXYProc(TypeMask mask) {
MNN_ASSERT((mask & ~kAllMasks) == 0);
return gMapXYProcs[mask & kAllMasks];
}
MapXYProc getMapXYProc() const {
return GetMapXYProc(this->getType());
}
typedef void (*MapPtsProc)(const Matrix& mat, Point dst[], const Point src[], int count);
static MapPtsProc GetMapPtsProc(TypeMask mask) {
MNN_ASSERT((mask & ~kAllMasks) == 0);
return gMapPtsProcs[mask & kAllMasks];
}
MapPtsProc getMapPtsProc() const {
return GetMapPtsProc(this->getType());
}
bool invertNonIdentity(Matrix* inverse) const;
static void Identity_xy(const Matrix&, float, float, Point*);
static void Trans_xy(const Matrix&, float, float, Point*);
static void Scale_xy(const Matrix&, float, float, Point*);
static void ScaleTrans_xy(const Matrix&, float, float, Point*);
static void Rot_xy(const Matrix&, float, float, Point*);
static void RotTrans_xy(const Matrix&, float, float, Point*);
static void Persp_xy(const Matrix&, float, float, Point*);
static const MapXYProc gMapXYProcs[];
static void Identity_pts(const Matrix&, Point[], const Point[], int);
static void Trans_pts(const Matrix&, Point dst[], const Point[], int);
static void Scale_pts(const Matrix&, Point dst[], const Point[], int);
static void ScaleTrans_pts(const Matrix&, Point dst[], const Point[], int count);
static void Persp_pts(const Matrix&, Point dst[], const Point[], int);
static void Affine_vpts(const Matrix&, Point dst[], const Point[], int);
static const MapPtsProc gMapPtsProcs[];
static bool Poly2Proc(const Point srcPt[], Matrix* dst);
static bool Poly3Proc(const Point srcPt[], Matrix* dst);
static bool Poly4Proc(const Point srcPt[], Matrix* dst);
};
} // namespace CV
} // namespace MNN
#endif
... ...
//
// Rect.h
// MNN
//
// Modified by jiangxiaotang on 2018/09/19.
// Copyright © 2018, Alibaba Group Holding Limited
//
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/Rect.h and docs/SkRect_Reference.bmh
on 2018-07-13 08:15:11. Additional documentation and examples can be found at:
https://skia.org/user/api/SkRect_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkRect_Reference.bmh, run:
bookmaker -b docs -i include/core/Rect.h -p
to create an updated version of this file.
*/
#ifndef SkRect_DEFINED
#define SkRect_DEFINED
#include <math.h>
#include <algorithm>
#include <utility>
#include <MNN/MNNDefine.h>
namespace MNN {
namespace CV {
struct Point {
float fX;
float fY;
void set(float x, float y) {
fX = x;
fY = y;
}
};
/** \struct Rect
Rect holds four float coordinates describing the upper and
lower bounds of a rectangle. Rect may be created from outer bounds or
from position, width, and height. Rect describes an area; if its right
is less than or equal to its left, or if its bottom is less than or equal to
its top, it is considered empty.
*/
struct MNN_PUBLIC Rect {
float fLeft; //!< smaller x-axis bounds
float fTop; //!< smaller y-axis bounds
float fRight; //!< larger x-axis bounds
float fBottom; //!< larger y-axis bounds
/** Returns constructed Rect set to (0, 0, 0, 0).
Many other rectangles are empty; if left is equal to or greater than right,
or if top is equal to or greater than bottom. Setting all members to zero
is a convenience, but does not designate a special empty rectangle.
@return bounds (0, 0, 0, 0)
*/
static constexpr Rect MakeEmpty() {
return Rect{0, 0, 0, 0};
}
#ifdef SK_SUPPORT_LEGACY_RECTMAKELARGEST
/** Deprecated.
*/
static Rect MakeLargest() {
return {SK_ScalarMin, SK_ScalarMin, SK_ScalarMax, SK_ScalarMax};
}
#endif
/** Returns constructed Rect set to float values (0, 0, w, h). Does not
validate input; w or h may be negative.
Passing integer values may generate a compiler warning since Rect cannot
represent 32-bit integers exactly. Use SkIRect for an exact integer rectangle.
@param w float width of constructed Rect
@param h float height of constructed Rect
@return bounds (0, 0, w, h)
*/
static constexpr Rect MakeWH(float w, float h) {
return Rect{0, 0, w, h};
}
/** Returns constructed Rect set to integer values (0, 0, w, h). Does not validate
input; w or h may be negative.
Use to avoid a compiler warning that input may lose precision when stored.
Use SkIRect for an exact integer rectangle.
@param w integer width of constructed Rect
@param h integer height of constructed Rect
@return bounds (0, 0, w, h)
*/
static Rect MakeIWH(int w, int h) {
Rect r;
r.set(0, 0, (float)(w), (float)(h));
return r;
}
/** Returns constructed Rect set to (l, t, r, b). Does not sort input; Rect may
result in fLeft greater than fRight, or fTop greater than fBottom.
@param l float stored in fLeft
@param t float stored in fTop
@param r float stored in fRight
@param b float stored in fBottom
@return bounds (l, t, r, b)
*/
static constexpr Rect MakeLTRB(float l, float t, float r, float b) {
return Rect{l, t, r, b};
}
/** Returns constructed Rect set to (x, y, x + w, y + h). Does not validate input;
w or h may be negative.
@param x stored in fLeft
@param y stored in fTop
@param w added to x and stored in fRight
@param h added to y and stored in fBottom
@return bounds at (x, y) with width w and height h
*/
static constexpr Rect MakeXYWH(float x, float y, float w, float h) {
return Rect{x, y, x + w, y + h};
}
/** Returns true if fLeft is equal to or greater than fRight, or if fTop is equal
to or greater than fBottom. Call sort() to reverse rectangles with negative
width() or height().
@return true if width() or height() are zero or negative
*/
bool isEmpty() const {
// We write it as the NOT of a non-empty rect, so we will return true if any values
// are NaN.
return !(fLeft < fRight && fTop < fBottom);
}
/** Returns true if fLeft is equal to or less than fRight, or if fTop is equal
to or less than fBottom. Call sort() to reverse rectangles with negative
width() or height().
@return true if width() or height() are zero or positive
*/
bool isSorted() const {
return fLeft <= fRight && fTop <= fBottom;
}
/** Returns left edge of Rect, if sorted. Call isSorted() to see if Rect is valid.
Call sort() to reverse fLeft and fRight if needed.
@return fLeft
*/
float x() const {
return fLeft;
}
/** Returns top edge of Rect, if sorted. Call isEmpty() to see if Rect may be invalid,
and sort() to reverse fTop and fBottom if needed.
@return fTop
*/
float y() const {
return fTop;
}
/** Returns left edge of Rect, if sorted. Call isSorted() to see if Rect is valid.
Call sort() to reverse fLeft and fRight if needed.
@return fLeft
*/
float left() const {
return fLeft;
}
/** Returns top edge of Rect, if sorted. Call isEmpty() to see if Rect may be invalid,
and sort() to reverse fTop and fBottom if needed.
@return fTop
*/
float top() const {
return fTop;
}
/** Returns right edge of Rect, if sorted. Call isSorted() to see if Rect is valid.
Call sort() to reverse fLeft and fRight if needed.
@return fRight
*/
float right() const {
return fRight;
}
/** Returns bottom edge of Rect, if sorted. Call isEmpty() to see if Rect may be invalid,
and sort() to reverse fTop and fBottom if needed.
@return fBottom
*/
float bottom() const {
return fBottom;
}
/** Returns span on the x-axis. This does not check if Rect is sorted, or if
result fits in 32-bit float; result may be negative or infinity.
@return fRight minus fLeft
*/
float width() const {
return fRight - fLeft;
}
/** Returns span on the y-axis. This does not check if Rect is sorted, or if
result fits in 32-bit float; result may be negative or infinity.
@return fBottom minus fTop
*/
float height() const {
return fBottom - fTop;
}
/** Returns average of left edge and right edge. Result does not change if Rect
is sorted. Result may overflow to infinity if Rect is far from the origin.
@return midpoint in x
*/
float centerX() const {
// don't use floatHalf(fLeft + fBottom) as that might overflow before the 0.5
return 0.5f * (fLeft) + 0.5f * (fRight);
}
/** Returns average of top edge and bottom edge. Result does not change if Rect
is sorted.
@return midpoint in y
*/
float centerY() const {
// don't use floatHalf(fTop + fBottom) as that might overflow before the 0.5
return 0.5f * (fTop) + 0.5f * (fBottom);
}
/** Sets Rect to (0, 0, 0, 0).
Many other rectangles are empty; if left is equal to or greater than right,
or if top is equal to or greater than bottom. Setting all members to zero
is a convenience, but does not designate a special empty rectangle.
*/
void setEmpty() {
*this = MakeEmpty();
}
/** Sets Rect to (left, top, right, bottom).
left and right are not sorted; left is not necessarily less than right.
top and bottom are not sorted; top is not necessarily less than bottom.
@param left stored in fLeft
@param top stored in fTop
@param right stored in fRight
@param bottom stored in fBottom
*/
void set(float left, float top, float right, float bottom) {
fLeft = left;
fTop = top;
fRight = right;
fBottom = bottom;
}
/** Sets Rect to (left, top, right, bottom).
left and right are not sorted; left is not necessarily less than right.
top and bottom are not sorted; top is not necessarily less than bottom.
@param left stored in fLeft
@param top stored in fTop
@param right stored in fRight
@param bottom stored in fBottom
*/
void setLTRB(float left, float top, float right, float bottom) {
this->set(left, top, right, bottom);
}
/** Sets Rect to (left, top, right, bottom).
All parameters are promoted from integer to scalar.
left and right are not sorted; left is not necessarily less than right.
top and bottom are not sorted; top is not necessarily less than bottom.
@param left promoted to float and stored in fLeft
@param top promoted to float and stored in fTop
@param right promoted to float and stored in fRight
@param bottom promoted to float and stored in fBottom
*/
void iset(int left, int top, int right, int bottom) {
fLeft = (float)(left);
fTop = (float)(top);
fRight = (float)(right);
fBottom = (float)(bottom);
}
/** Sets Rect to (0, 0, width, height).
width and height may be zero or negative. width and height are promoted from
integer to float, large values may lose precision.
@param width promoted to float and stored in fRight
@param height promoted to float and stored in fBottom
*/
void isetWH(int width, int height) {
fLeft = fTop = 0;
fRight = (float)(width);
fBottom = (float)(height);
}
/** Sets Rect to (x, y, x + width, y + height). Does not validate input;
width or height may be negative.
@param x stored in fLeft
@param y stored in fTop
@param width added to x and stored in fRight
@param height added to y and stored in fBottom
*/
void setXYWH(float x, float y, float width, float height) {
fLeft = x;
fTop = y;
fRight = x + width;
fBottom = y + height;
}
/** Sets Rect to (0, 0, width, height). Does not validate input;
width or height may be negative.
@param width stored in fRight
@param height stored in fBottom
*/
void setWH(float width, float height) {
fLeft = 0;
fTop = 0;
fRight = width;
fBottom = height;
}
/** Returns Rect offset by (dx, dy).
If dx is negative, Rect returned is moved to the left.
If dx is positive, Rect returned is moved to the right.
If dy is negative, Rect returned is moved upward.
If dy is positive, Rect returned is moved downward.
@param dx added to fLeft and fRight
@param dy added to fTop and fBottom
@return Rect offset on axes, with original width and height
*/
Rect makeOffset(float dx, float dy) const {
return MakeLTRB(fLeft + dx, fTop + dy, fRight + dx, fBottom + dy);
}
/** Returns Rect, inset by (dx, dy).
If dx is negative, Rect returned is wider.
If dx is positive, Rect returned is narrower.
If dy is negative, Rect returned is taller.
If dy is positive, Rect returned is shorter.
@param dx added to fLeft and subtracted from fRight
@param dy added to fTop and subtracted from fBottom
@return Rect inset symmetrically left and right, top and bottom
*/
Rect makeInset(float dx, float dy) const {
return MakeLTRB(fLeft + dx, fTop + dy, fRight - dx, fBottom - dy);
}
/** Returns Rect, outset by (dx, dy).
If dx is negative, Rect returned is narrower.
If dx is positive, Rect returned is wider.
If dy is negative, Rect returned is shorter.
If dy is positive, Rect returned is taller.
@param dx subtracted to fLeft and added from fRight
@param dy subtracted to fTop and added from fBottom
@return Rect outset symmetrically left and right, top and bottom
*/
Rect makeOutset(float dx, float dy) const {
return MakeLTRB(fLeft - dx, fTop - dy, fRight + dx, fBottom + dy);
}
/** Offsets Rect by adding dx to fLeft, fRight; and by adding dy to fTop, fBottom.
If dx is negative, moves Rect to the left.
If dx is positive, moves Rect to the right.
If dy is negative, moves Rect upward.
If dy is positive, moves Rect downward.
@param dx offset added to fLeft and fRight
@param dy offset added to fTop and fBottom
*/
void offset(float dx, float dy) {
fLeft += dx;
fTop += dy;
fRight += dx;
fBottom += dy;
}
/** Offsets Rect so that fLeft equals newX, and fTop equals newY. width and height
are unchanged.
@param newX stored in fLeft, preserving width()
@param newY stored in fTop, preserving height()
*/
void offsetTo(float newX, float newY) {
fRight += newX - fLeft;
fBottom += newY - fTop;
fLeft = newX;
fTop = newY;
}
/** Insets Rect by (dx, dy).
If dx is positive, makes Rect narrower.
If dx is negative, makes Rect wider.
If dy is positive, makes Rect shorter.
If dy is negative, makes Rect taller.
@param dx added to fLeft and subtracted from fRight
@param dy added to fTop and subtracted from fBottom
*/
void inset(float dx, float dy) {
fLeft += dx;
fTop += dy;
fRight -= dx;
fBottom -= dy;
}
/** Outsets Rect by (dx, dy).
If dx is positive, makes Rect wider.
If dx is negative, makes Rect narrower.
If dy is positive, makes Rect taller.
If dy is negative, makes Rect shorter.
@param dx subtracted to fLeft and added from fRight
@param dy subtracted to fTop and added from fBottom
*/
void outset(float dx, float dy) {
this->inset(-dx, -dy);
}
private:
static bool Intersects(float al, float at, float ar, float ab, float bl, float bt, float br, float bb) {
float L = std::max(al, bl);
float R = std::min(ar, br);
float T = std::max(at, bt);
float B = std::min(ab, bb);
return L < R && T < B;
}
public:
/** Constructs Rect to intersect from (left, top, right, bottom). Does not sort
construction.
Returns true if Rect intersects construction.
Returns false if either construction or Rect is empty, or do not intersect.
@param left x-axis minimum of constructed Rect
@param top y-axis minimum of constructed Rect
@param right x-axis maximum of constructed Rect
@param bottom y-axis maximum of constructed Rect
@return true if construction and Rect have area in common
*/
bool intersects(float left, float top, float right, float bottom) const {
return Intersects(fLeft, fTop, fRight, fBottom, left, top, right, bottom);
}
/** Returns true if Rect intersects r.
Returns false if either r or Rect is empty, or do not intersect.
@param r Rect to intersect
@return true if r and Rect have area in common
*/
bool intersects(const Rect& r) const {
return Intersects(fLeft, fTop, fRight, fBottom, r.fLeft, r.fTop, r.fRight, r.fBottom);
}
/** Returns true if a intersects b.
Returns false if either a or b is empty, or do not intersect.
@param a Rect to intersect
@param b Rect to intersect
@return true if a and b have area in common
*/
static bool Intersects(const Rect& a, const Rect& b) {
return Intersects(a.fLeft, a.fTop, a.fRight, a.fBottom, b.fLeft, b.fTop, b.fRight, b.fBottom);
}
/** Sets Rect to the union of itself and r.
Asserts if r is empty and SK_DEBUG is defined.
If Rect is empty, sets Rect to r.
May produce incorrect results if r is empty.
@param r expansion Rect
*/
void joinNonEmptyArg(const Rect& r) {
MNN_ASSERT(!r.isEmpty());
// if we are empty, just assign
if (fLeft >= fRight || fTop >= fBottom) {
*this = r;
} else {
this->joinPossiblyEmptyRect(r);
}
}
/** Sets Rect to the union of itself and the construction.
May produce incorrect results if Rect or r is empty.
@param r expansion Rect
*/
void joinPossiblyEmptyRect(const Rect& r) {
fLeft = std::min(fLeft, r.left());
fTop = std::min(fTop, r.top());
fRight = std::max(fRight, r.right());
fBottom = std::max(fBottom, r.bottom());
}
/** Returns true if: fLeft <= x < fRight && fTop <= y < fBottom.
Returns false if Rect is empty.
@param x test Point x-coordinate
@param y test Point y-coordinate
@return true if (x, y) is inside Rect
*/
bool contains(float x, float y) const {
return x >= fLeft && x < fRight && y >= fTop && y < fBottom;
}
/** Swaps fLeft and fRight if fLeft is greater than fRight; and swaps
fTop and fBottom if fTop is greater than fBottom. Result may be empty;
and width() and height() will be zero or positive.
*/
void sort() {
using std::swap;
if (fLeft > fRight) {
swap(fLeft, fRight);
}
if (fTop > fBottom) {
swap(fTop, fBottom);
}
}
/** Returns Rect with fLeft and fRight swapped if fLeft is greater than fRight; and
with fTop and fBottom swapped if fTop is greater than fBottom. Result may be empty;
and width() and height() will be zero or positive.
@return sorted Rect
*/
Rect makeSorted() const {
return MakeLTRB(std::min(fLeft, fRight), std::min(fTop, fBottom), std::max(fLeft, fRight),
std::max(fTop, fBottom));
}
/** Returns pointer to first scalar in Rect, to treat it as an array with four
entries.
@return pointer to fLeft
*/
const float* asScalars() const {
return &fLeft;
}
};
} // namespace CV
} // namespace MNN
#endif
... ...
//
// Tensor.hpp
// MNN
//
// Created by MNN on 2018/08/14.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef Tensor_hpp
#define Tensor_hpp
#include <vector>
#include <MNN/HalideRuntime.h>
#include <MNN/MNNDefine.h>
#define MNN_MAX_TENSOR_DIM 6
namespace MNN {
/**
* data container.
* data for host tensor is saved in `host` field. its memory is allocated malloc directly.
* data for device tensor is saved in `deviceId` field. its memory is allocated by session's backend.
* usually, device tensors are created by engine (like net, session).
* meanwhile, host tensors could be created by engine or user.
*/
class MNN_PUBLIC Tensor {
public:
struct InsideDescribe;
/** dimension type used to create tensor */
enum DimensionType {
/** for tensorflow net type. uses NHWC as data format. */
TENSORFLOW,
/** for caffe net type. uses NCHW as data format. */
CAFFE,
/** for caffe net type. uses NC4HW4 as data format. */
CAFFE_C4
};
/** handle type */
enum HandleDataType {
/** default handle type */
HANDLE_NONE = 0,
/** string handle type */
HANDLE_STRING = 1
};
/** Tensor map type : Read or Write*/
enum MapType {
/** map Tensor for writing data*/
MAP_TENSOR_WRITE = 0,
MAP_TENSOR_READ = 1
};
public:
/**
* @brief create a tensor with dimension size and type without acquire memory for data.
* @param dimSize dimension size.
* @param type dimension type.
*/
Tensor(int dimSize = 4, DimensionType type = CAFFE);
/**
* @brief create a tensor with same shape as given tensor.
* @param tensor shape provider.
* @param type dimension type.
* @param allocMemory acquire memory for data or not.
* @warning tensor data won't be copied.
*/
Tensor(const Tensor* tensor, DimensionType type = CAFFE, bool allocMemory = true);
/** deinitializer */
~Tensor();
private:
// remove all assignment operator
Tensor(const Tensor& tensor) = delete;
Tensor(const Tensor&& tensor) = delete;
Tensor& operator=(const Tensor&) = delete;
Tensor& operator=(const Tensor&&) = delete;
public:
/**
* @brief create tensor with shape, data type and dimension type.
* @param shape tensor shape.
* @param type data type.
* @param dimType dimension type.
* @return created tensor.
* @warning memory for data won't be acquired. call backend's onAcquireBuffer to get memory ready.
*/
static Tensor* createDevice(const std::vector<int>& shape, halide_type_t type, DimensionType dimType = TENSORFLOW);
/**
* @brief create tensor with shape and dimension type. data type is represented by `T`.
* @param shape tensor shape.
* @param dimType dimension type.
* @return created tensor.
* @warning memory for data won't be acquired. call backend's onAcquireBuffer to get memory ready.
*/
template <typename T>
static Tensor* createDevice(const std::vector<int>& shape, DimensionType dimType = TENSORFLOW) {
return createDevice(shape, halide_type_of<T>(), dimType);
}
/**
* @brief create tensor with shape, data type, data and dimension type.
* @param shape tensor shape.
* @param type data type.
* @param data data to save.
* @param dimType dimension type.
* @return created tensor.
*/
static Tensor* create(const std::vector<int>& shape, halide_type_t type, void* data = NULL,
DimensionType dimType = TENSORFLOW);
/**
* @brief create tensor with shape, data and dimension type. data type is represented by `T`.
* @param shape tensor shape.
* @param data data to save.
* @param dimType dimension type.
* @return created tensor.
*/
template <typename T>
static Tensor* create(const std::vector<int>& shape, void* data = NULL, DimensionType dimType = TENSORFLOW) {
return create(shape, halide_type_of<T>(), data, dimType);
}
public:
/**
* @brief for DEVICE tensor, copy data from given host tensor.
* @param hostTensor host tensor, the data provider.
* @return true for DEVICE tensor, and false for HOST tensor.
*/
bool copyFromHostTensor(const Tensor* hostTensor);
/**
* @brief for DEVICE tensor, copy data to given host tensor.
* @param hostTensor host tensor, the data consumer.
* @return true for DEVICE tensor, and false for HOST tensor.
*/
bool copyToHostTensor(Tensor* hostTensor) const;
/**
* @brief create HOST tensor from DEVICE tensor, with or without data copying.
* @param deviceTensor given device tensor.
* @param copyData copy data or not.
* @return created host tensor.
*/
static Tensor* createHostTensorFromDevice(const Tensor* deviceTensor, bool copyData = true);
public:
const halide_buffer_t& buffer() const {
return mBuffer;
}
halide_buffer_t& buffer() {
return mBuffer;
}
/**
* @brief get dimension type.
* @return dimension type.
*/
DimensionType getDimensionType() const;
/**
* @brief handle data type. used when data type code is halide_type_handle.
* @return handle data type.
*/
HandleDataType getHandleDataType() const;
/**
* @brief set data type.
* @param type data type defined in 'Type_generated.h'.
*/
void setType(int type);
/**
* @brief get data type.
* @return data type.
*/
inline halide_type_t getType() const {
return mBuffer.type;
}
/**
* @brief visit host memory, data type is represented by `T`.
* @return data point in `T` type.
*/
template <typename T>
T* host() const {
return (T*)mBuffer.host;
}
/**
* @brief visit device memory.
* @return device data ID. what the ID means varies between backends.
*/
uint64_t deviceId() const {
return mBuffer.device;
}
public:
int dimensions() const {
return mBuffer.dimensions;
}
/**
* @brief get all dimensions' extent.
* @return dimensions' extent.
*/
std::vector<int> shape() const;
/**
* @brief calculate number of bytes needed to store data taking reordering flag into account.
* @return bytes needed to store data
*/
int size() const;
/**
* @brief calculate number of elements needed to store data taking reordering flag into account.
* @return elements needed to store data
*/
inline int elementSize() const {
return size() / mBuffer.type.bytes();
}
public:
inline int width() const {
if (getDimensionType() == TENSORFLOW) {
return mBuffer.dim[2].extent;
}
return mBuffer.dim[3].extent;
}
inline int height() const {
if (getDimensionType() == TENSORFLOW) {
return mBuffer.dim[1].extent;
}
return mBuffer.dim[2].extent;
}
inline int channel() const {
if (getDimensionType() == TENSORFLOW) {
return mBuffer.dim[3].extent;
}
return mBuffer.dim[1].extent;
}
inline int batch() const {
return mBuffer.dim[0].extent;
}
// visit dimension's extent & stride
inline int stride(int index) const {
return mBuffer.dim[index].stride;
}
inline int length(int index) const {
return mBuffer.dim[index].extent;
}
inline void setStride(int index, int stride) {
mBuffer.dim[index].stride = stride;
}
inline void setLength(int index, int length) {
mBuffer.dim[index].extent = length;
}
public:
/**
* @brief print tensor data. for DEBUG use only.
*/
void print() const;
/**
*@brief print tensor shape
*/
void printShape() const;
public:
/**
* @brief map/umap GPU Tensor, to get host ptr
*/
void* map(MapType mtype, DimensionType dtype);
void unmap(MapType mtype, DimensionType dtype, void* mapPtr);
private:
halide_buffer_t mBuffer;
struct InsideDescribe* mDescribe;
private:
friend class TensorUtils;
};
} // namespace MNN
#endif /* Tensor_hpp */
... ...
//
// Executor.hpp
// MNN
//
// Created by MNN on 2019/07/25.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef Executor_hpp
#define Executor_hpp
#include <MNN/ErrorCode.hpp>
#include <MNN/expr/Expr.hpp>
#include <MNN/Tensor.hpp>
#include <MNN/Interpreter.hpp>
#include <vector>
#include <mutex>
#include <set>
#include <MNN/MNNForwardType.h>
namespace MNN {
class Backend;
class Execution;
class Runtime;
struct Op;
namespace Express {
class MNN_PUBLIC Executor {
public:
class ComputeCache;
struct Unit;
static void setShapeDirty(ComputeCache* cache);
static void setContentDirty(ComputeCache* cache);
static Tensor* getOutput(ComputeCache* cache, int offset);
static void* mapOutput(ComputeCache* cache, int offset, Tensor* dest);
struct Requirement {
std::vector<bool> contentNeedContent;
std::vector<bool> shapeNeedContent;
};
~Executor();
Requirement getRequirement(Expr* expr) const;
ErrorCode computeInfo(Expr* expr);
void makeCache(const std::vector<EXPRP>& expr, bool forceCPU = false);
ErrorCode runCache(std::shared_ptr<ComputeCache> cache);
void setGlobalExecutorConfig(MNNForwardType type, const BackendConfig& config, int numberThread);
enum GCFlag {
FULL,
PART
};
void gc(GCFlag flag = FULL);
static std::shared_ptr<Executor> getGlobalExecutor();
static std::shared_ptr<Executor> newExecutor(MNNForwardType type,
const BackendConfig& config,
int numberThread);
void resetProfile();
void dumpProfile();
void addOpCostTime(int op, float costTime);
void addOpCostTime(const std::string& type, float costTime);
void addOpFlops(const std::string& type, float flops);
class Profiler;
static RuntimeInfo getRuntime();
struct Cache;
class RuntimeManager {
public:
RuntimeManager(std::vector<ScheduleConfig> &configs);
~RuntimeManager() {};
/**
* @param configs: schedule configs.
* @param cacheName: full path for cache file. Note: should choose location for reading and writing.
*/
static RuntimeManager* createRuntimeManager(std::vector<ScheduleConfig> &configs);
/**
* @brief set cache file. when file not exist -- create it, when file exist -- load it.
* When should use : When choose GPU backend or use AUTO backend.
* Calling Position: calling after createRuntimeManager.
*/
void setCache(std::string cacheName);
/**
* @brief update cache file
* When should use : Together with setCache API. calling for first inference and when input shape is changed.
* Calling Position : calling after inference done.
*/
void updateCache();
std::vector<bool> isBackendSupport(const std::vector<MNNForwardType> type);
RuntimeInfo getRuntimeInfo() {
return mRuntime;
}
private:
RuntimeInfo mRuntime;
std::shared_ptr<Runtime> mInfo;
std::shared_ptr<Cache> mCache;
};
private:
void _makeCache(const std::vector<EXPRP>& outputs, bool forceCPU);
void _create(const std::vector<EXPRP>& outputs, std::set<std::shared_ptr<Executor::ComputeCache>>&& inputCaches, std::set<std::shared_ptr<Expr::Inside>>&& inputNode, bool forceCPU);
void _visit(EXPRP expr, std::set<std::shared_ptr<Executor::ComputeCache>>& inputCaches, std::set<std::shared_ptr<Expr::Inside>>& inputNode);
Executor(std::shared_ptr<Runtime> backend, MNNForwardType type);
std::pair<std::shared_ptr<Runtime>, MNNForwardType> mRuntime;
std::pair<std::shared_ptr<Runtime>, MNNForwardType> mBackupRuntime;
std::mutex mMutex;
std::shared_ptr<Profiler> mProfiler;
};
} // namespace Express
} // namespace MNN
#endif
... ...
//
// ExecutorScope.hpp
// MNN
//
// Created by MNN on 2020/10/26.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef MNN_EXPR_EXECUTOR_SCOPE_HPP_
#define MNN_EXPR_EXECUTOR_SCOPE_HPP_
#include <MNN/expr/Executor.hpp>
namespace MNN {
namespace Express {
struct MNN_PUBLIC ExecutorScope final {
public:
ExecutorScope() = delete;
explicit ExecutorScope(const ExecutorScope&) = delete;
explicit ExecutorScope(const std::shared_ptr<Executor>& current);
explicit ExecutorScope(const std::string& scope_name,
const std::shared_ptr<Executor>& current);
virtual ~ExecutorScope();
static const std::shared_ptr<Executor> Current();
};
} // namespace MNN
} // namespace Express
#endif // MNN_EXPR_EXECUTOR_SCOPE_HPP_
... ...