[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>."
  },
  {
    "path": "README.md",
    "content": "# Robust Video Matting (RVM)\n\n![Teaser](/documentation/image/teaser.gif)\n\n<p align=\"center\">English | <a href=\"README_zh_Hans.md\">中文</a></p>\n\nOfficial repository for the paper [Robust High-Resolution Video Matting with Temporal Guidance](https://peterl1n.github.io/RobustVideoMatting/). RVM is specifically designed for robust human video matting. Unlike existing neural models that process frames as independent images, RVM uses a recurrent neural network to process videos with temporal memory. RVM can perform matting in real-time on any videos without additional inputs. It achieves **4K 76FPS** and **HD 104FPS** on an Nvidia GTX 1080 Ti GPU. The project was developed at [ByteDance Inc.](https://www.bytedance.com/)\n\n<br>\n\n## News\n\n* [Nov 03 2021] Fixed a bug in [train.py](https://github.com/PeterL1n/RobustVideoMatting/commit/48effc91576a9e0e7a8519f3da687c0d3522045f).\n* [Sep 16 2021] Code is re-released under GPL-3.0 license.\n* [Aug 25 2021] Source code and pretrained models are published.\n* [Jul 27 2021] Paper is accepted by WACV 2022.\n\n<br>\n\n## Showreel\nWatch the showreel video ([YouTube](https://youtu.be/Jvzltozpbpk), [Bilibili](https://www.bilibili.com/video/BV1Z3411B7g7/)) to see the model's performance. \n\n<p align=\"center\">\n    <a href=\"https://youtu.be/Jvzltozpbpk\">\n        <img src=\"documentation/image/showreel.gif\">\n    </a>\n</p>\n\nAll footage in the video are available in [Google Drive](https://drive.google.com/drive/folders/1VFnWwuu-YXDKG-N6vcjK_nL7YZMFapMU?usp=sharing).\n\n<br>\n\n\n## Demo\n* [Webcam Demo](https://peterl1n.github.io/RobustVideoMatting/#/demo): Run the model live in your browser. Visualize recurrent states.\n* [Colab Demo](https://colab.research.google.com/drive/10z-pNKRnVNsp0Lq9tH1J_XPZ7CBC_uHm?usp=sharing): Test our model on your own videos with free GPU. \n\n<br>\n\n## Download\n\nWe recommend MobileNetv3 models for most use cases. ResNet50 models are the larger variant with small performance improvements. Our model is available on various inference frameworks. See [inference documentation](documentation/inference.md) for more instructions.\n\n<table>\n    <thead>\n        <tr>\n            <td>Framework</td>\n            <td>Download</td>\n            <td>Notes</td>\n        </tr>\n    </thead>\n    <tbody>\n        <tr>\n            <td>PyTorch</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3.pth\">rvm_mobilenetv3.pth</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50.pth\">rvm_resnet50.pth</a>\n            </td>\n            <td>\n                Official weights for PyTorch. <a href=\"documentation/inference.md#pytorch\">Doc</a>\n            </td>\n        </tr>\n        <tr>\n            <td>TorchHub</td>\n            <td>\n                Nothing to Download.\n            </td>\n            <td>\n                Easiest way to use our model in your PyTorch project. <a href=\"documentation/inference.md#torchhub\">Doc</a>\n            </td>\n        </tr>\n        <tr>\n            <td>TorchScript</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_fp32.torchscript\">rvm_mobilenetv3_fp32.torchscript</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_fp16.torchscript\">rvm_mobilenetv3_fp16.torchscript</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50_fp32.torchscript\">rvm_resnet50_fp32.torchscript</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50_fp16.torchscript\">rvm_resnet50_fp16.torchscript</a>\n            </td>\n            <td>\n                If inference on mobile, consider export int8 quantized models yourself. <a href=\"documentation/inference.md#torchscript\">Doc</a>\n            </td>\n        </tr>\n        <tr>\n            <td>ONNX</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_fp32.onnx\">rvm_mobilenetv3_fp32.onnx</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_fp16.onnx\">rvm_mobilenetv3_fp16.onnx</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50_fp32.onnx\">rvm_resnet50_fp32.onnx</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50_fp16.onnx\">rvm_resnet50_fp16.onnx</a>\n            </td>\n            <td>\n                Tested on ONNX Runtime with CPU and CUDA backends. Provided models use opset 12. <a href=\"documentation/inference.md#onnx\">Doc</a>, <a href=\"https://github.com/PeterL1n/RobustVideoMatting/tree/onnx\">Exporter</a>.\n            </td>\n        </tr>\n        <tr>\n            <td>TensorFlow</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_tf.zip\">rvm_mobilenetv3_tf.zip</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50_tf.zip\">rvm_resnet50_tf.zip</a>\n            </td>\n            <td>\n                TensorFlow 2 SavedModel. <a href=\"documentation/inference.md#tensorflow\">Doc</a>\n            </td>\n        </tr>\n        <tr>\n            <td>TensorFlow.js</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_tfjs_int8.zip\">rvm_mobilenetv3_tfjs_int8.zip</a><br>\n            </td>\n            <td>\n                Run the model on the web. <a href=\"https://peterl1n.github.io/RobustVideoMatting/#/demo\">Demo</a>, <a href=\"https://github.com/PeterL1n/RobustVideoMatting/tree/tfjs\">Starter Code</a>\n            </td>\n        </tr>\n        <tr>\n            <td>CoreML</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_1280x720_s0.375_fp16.mlmodel\">rvm_mobilenetv3_1280x720_s0.375_fp16.mlmodel</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_1280x720_s0.375_int8.mlmodel\">rvm_mobilenetv3_1280x720_s0.375_int8.mlmodel</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_1920x1080_s0.25_fp16.mlmodel\">rvm_mobilenetv3_1920x1080_s0.25_fp16.mlmodel</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_1920x1080_s0.25_int8.mlmodel\">rvm_mobilenetv3_1920x1080_s0.25_int8.mlmodel</a><br>\n            </td>\n            <td>\n                CoreML does not support dynamic resolution. Other resolutions can be exported yourself. Models require iOS 13+. <code>s</code> denotes <code>downsample_ratio</code>. <a href=\"documentation/inference.md#coreml\">Doc</a>, <a href=\"https://github.com/PeterL1n/RobustVideoMatting/tree/coreml\">Exporter</a>\n            </td>\n        </tr>\n    </tbody>\n</table>\n\nAll models are available in [Google Drive](https://drive.google.com/drive/folders/1pBsG-SCTatv-95SnEuxmnvvlRx208VKj?usp=sharing) and [Baidu Pan](https://pan.baidu.com/s/1puPSxQqgBFOVpW4W7AolkA) (code: gym7).\n\n<br>\n\n## PyTorch Example\n\n1. Install dependencies:\n```sh\npip install -r requirements_inference.txt\n```\n\n2. Load the model:\n\n```python\nimport torch\nfrom model import MattingNetwork\n\nmodel = MattingNetwork('mobilenetv3').eval().cuda()  # or \"resnet50\"\nmodel.load_state_dict(torch.load('rvm_mobilenetv3.pth'))\n```\n\n3. To convert videos, we provide a simple conversion API:\n\n```python\nfrom inference import convert_video\n\nconvert_video(\n    model,                           # The model, can be on any device (cpu or cuda).\n    input_source='input.mp4',        # A video file or an image sequence directory.\n    output_type='video',             # Choose \"video\" or \"png_sequence\"\n    output_composition='com.mp4',    # File path if video; directory path if png sequence.\n    output_alpha=\"pha.mp4\",          # [Optional] Output the raw alpha prediction.\n    output_foreground=\"fgr.mp4\",     # [Optional] Output the raw foreground prediction.\n    output_video_mbps=4,             # Output video mbps. Not needed for png sequence.\n    downsample_ratio=None,           # A hyperparameter to adjust or use None for auto.\n    seq_chunk=12,                    # Process n frames at once for better parallelism.\n)\n```\n\n4. Or write your own inference code:\n```python\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms import ToTensor\nfrom inference_utils import VideoReader, VideoWriter\n\nreader = VideoReader('input.mp4', transform=ToTensor())\nwriter = VideoWriter('output.mp4', frame_rate=30)\n\nbgr = torch.tensor([.47, 1, .6]).view(3, 1, 1).cuda()  # Green background.\nrec = [None] * 4                                       # Initial recurrent states.\ndownsample_ratio = 0.25                                # Adjust based on your video.\n\nwith torch.no_grad():\n    for src in DataLoader(reader):                     # RGB tensor normalized to 0 ~ 1.\n        fgr, pha, *rec = model(src.cuda(), *rec, downsample_ratio)  # Cycle the recurrent states.\n        com = fgr * pha + bgr * (1 - pha)              # Composite to green background. \n        writer.write(com)                              # Write frame.\n```\n\n5. The models and converter API are also available through TorchHub.\n\n```python\n# Load the model.\nmodel = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"mobilenetv3\") # or \"resnet50\"\n\n# Converter API.\nconvert_video = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"converter\")\n```\n\nPlease see [inference documentation](documentation/inference.md) for details on `downsample_ratio` hyperparameter, more converter arguments, and more advanced usage.\n\n<br>\n\n## Training and Evaluation\n\nPlease refer to the [training documentation](documentation/training.md) to train and evaluate your own model.\n\n<br>\n\n## Speed\n\nSpeed is measured with `inference_speed_test.py` for reference.\n\n| GPU            | dType | HD (1920x1080) | 4K (3840x2160) |\n| -------------- | ----- | -------------- |----------------|\n| RTX 3090       | FP16  | 172 FPS        | 154 FPS        |\n| RTX 2060 Super | FP16  | 134 FPS        | 108 FPS        |\n| GTX 1080 Ti    | FP32  | 104 FPS        | 74 FPS         |\n\n* Note 1: HD uses `downsample_ratio=0.25`, 4K uses `downsample_ratio=0.125`. All tests use batch size 1 and frame chunk 1.\n* Note 2: GPUs before Turing architecture does not support FP16 inference, so GTX 1080 Ti uses FP32.\n* Note 3: We only measure tensor throughput. The provided video conversion script in this repo is expected to be much slower, because it does not utilize hardware video encoding/decoding and does not have the tensor transfer done on parallel threads. If you are interested in implementing hardware video encoding/decoding in Python, please refer to [PyNvCodec](https://github.com/NVIDIA/VideoProcessingFramework).\n\n<br>  \n\n## Project Members\n* [Shanchuan Lin](https://www.linkedin.com/in/shanchuanlin/)\n* [Linjie Yang](https://sites.google.com/site/linjieyang89/)\n* [Imran Saleemi](https://www.linkedin.com/in/imran-saleemi/)\n* [Soumyadip Sengupta](https://homes.cs.washington.edu/~soumya91/)\n\n<br>\n\n## Third-Party Projects\n\n* [NCNN C++ Android](https://github.com/FeiGeChuanShu/ncnn_Android_RobustVideoMatting) ([@FeiGeChuanShu](https://github.com/FeiGeChuanShu))\n* [lite.ai.toolkit](https://github.com/DefTruth/RobustVideoMatting.lite.ai.toolkit) ([@DefTruth](https://github.com/DefTruth))\n* [Gradio Web Demo](https://huggingface.co/spaces/akhaliq/Robust-Video-Matting) ([@AK391](https://github.com/AK391))\n* [Unity Engine demo with NatML](https://hub.natml.ai/@natsuite/robust-video-matting) ([@natsuite](https://github.com/natsuite))  \n* [MNN C++ Demo](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/mnn/cv/mnn_rvm.cpp) ([@DefTruth](https://github.com/DefTruth))\n* [TNN C++ Demo](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/tnn/cv/tnn_rvm.cpp) ([@DefTruth](https://github.com/DefTruth))\n\n"
  },
  {
    "path": "README_zh_Hans.md",
    "content": "# 稳定视频抠像 (RVM)\n\n![Teaser](/documentation/image/teaser.gif)\n\n<p align=\"center\"><a href=\"README.md\">English</a> | 中文</p>\n\n论文 [Robust High-Resolution Video Matting with Temporal Guidance](https://peterl1n.github.io/RobustVideoMatting/) 的官方 GitHub 库。RVM 专为稳定人物视频抠像设计。不同于现有神经网络将每一帧作为单独图片处理，RVM 使用循环神经网络，在处理视频流时有时间记忆。RVM 可在任意视频上做实时高清抠像。在 Nvidia GTX 1080Ti 上实现 **4K 76FPS** 和 **HD 104FPS**。此研究项目来自[字节跳动](https://www.bytedance.com/)。\n\n<br>\n\n## 更新\n\n* [2021年11月3日] 修复了 [train.py](https://github.com/PeterL1n/RobustVideoMatting/commit/48effc91576a9e0e7a8519f3da687c0d3522045f) 的 bug。\n* [2021年9月16日] 代码重新以 GPL-3.0 许可发布。\n* [2021年8月25日] 公开代码和模型。\n* [2021年7月27日] 论文被 WACV 2022 收录。\n\n<br>\n\n## 展示视频\n观看展示视频 ([YouTube](https://youtu.be/Jvzltozpbpk), [Bilibili](https://www.bilibili.com/video/BV1Z3411B7g7/))，了解模型能力。\n<p align=\"center\">\n    <a href=\"https://youtu.be/Jvzltozpbpk\">\n        <img src=\"documentation/image/showreel.gif\">\n    </a>\n</p>\n\n视频中的所有素材都提供下载，可用于测试模型：[Google Drive](https://drive.google.com/drive/folders/1VFnWwuu-YXDKG-N6vcjK_nL7YZMFapMU?usp=sharing)\n\n<br>\n\n\n## Demo\n* [网页](https://peterl1n.github.io/RobustVideoMatting/#/demo): 在浏览器里看摄像头抠像效果，展示模型内部循环记忆值。\n* [Colab](https://colab.research.google.com/drive/10z-pNKRnVNsp0Lq9tH1J_XPZ7CBC_uHm?usp=sharing): 用我们的模型转换你的视频。\n\n<br>\n\n## 下载\n\n推荐在通常情况下使用 MobileNetV3 的模型。ResNet50 的模型大很多，效果稍有提高。我们的模型支持很多框架。详情请阅读[推断文档](documentation/inference_zh_Hans.md)。\n\n<table>\n    <thead>\n        <tr>\n            <td>框架</td>\n            <td>下载</td>\n            <td>备注</td>\n        </tr>\n    </thead>\n    <tbody>\n        <tr>\n            <td>PyTorch</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3.pth\">rvm_mobilenetv3.pth</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50.pth\">rvm_resnet50.pth</a>\n            </td>\n            <td>\n                官方 PyTorch 模型权值。<a href=\"documentation/inference_zh_Hans.md#pytorch\">文档</a>\n            </td>\n        </tr>\n        <tr>\n            <td>TorchHub</td>\n            <td>\n                无需手动下载。\n            </td>\n            <td>\n                更方便地在你的 PyTorch 项目里使用此模型。<a href=\"documentation/inference_zh_Hans.md#torchhub\">文档</a>\n            </td>\n        </tr>\n        <tr>\n            <td>TorchScript</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_fp32.torchscript\">rvm_mobilenetv3_fp32.torchscript</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_fp16.torchscript\">rvm_mobilenetv3_fp16.torchscript</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50_fp32.torchscript\">rvm_resnet50_fp32.torchscript</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50_fp16.torchscript\">rvm_resnet50_fp16.torchscript</a>\n            </td>\n            <td>\n                若需在移动端推断，可以考虑自行导出 int8 量化的模型。<a href=\"documentation/inference_zh_Hans.md#torchscript\">文档</a>\n            </td>\n        </tr>\n        <tr>\n            <td>ONNX</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_fp32.onnx\">rvm_mobilenetv3_fp32.onnx</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_fp16.onnx\">rvm_mobilenetv3_fp16.onnx</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50_fp32.onnx\">rvm_resnet50_fp32.onnx</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50_fp16.onnx\">rvm_resnet50_fp16.onnx</a>\n            </td>\n            <td>\n                在 ONNX Runtime 的 CPU 和 CUDA backend 上测试过。提供的模型用 opset 12。<a href=\"documentation/inference_zh_Hans.md#onnx\">文档</a>，<a href=\"https://github.com/PeterL1n/RobustVideoMatting/tree/onnx\">导出</a>\n            </td>\n        </tr>\n        <tr>\n            <td>TensorFlow</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_tf.zip\">rvm_mobilenetv3_tf.zip</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50_tf.zip\">rvm_resnet50_tf.zip</a>\n            </td>\n            <td>\n                TensorFlow 2 SavedModel 格式。<a href=\"documentation/inference_zh_Hans.md#tensorflow\">文档</a>\n            </td>\n        </tr>\n        <tr>\n            <td>TensorFlow.js</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_tfjs_int8.zip\">rvm_mobilenetv3_tfjs_int8.zip</a><br>\n            </td>\n            <td>\n                在网页上跑模型。<a href=\"https://peterl1n.github.io/RobustVideoMatting/#/demo\">展示</a>，<a href=\"https://github.com/PeterL1n/RobustVideoMatting/tree/tfjs\">示范代码</a>\n            </td>\n        </tr>\n        <tr>\n            <td>CoreML</td>\n            <td>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_1280x720_s0.375_fp16.mlmodel\">rvm_mobilenetv3_1280x720_s0.375_fp16.mlmodel</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_1280x720_s0.375_int8.mlmodel\">rvm_mobilenetv3_1280x720_s0.375_int8.mlmodel</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_1920x1080_s0.25_fp16.mlmodel\">rvm_mobilenetv3_1920x1080_s0.25_fp16.mlmodel</a><br>\n                <a  href=\"https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3_1920x1080_s0.25_int8.mlmodel\">rvm_mobilenetv3_1920x1080_s0.25_int8.mlmodel</a><br>\n            </td>\n            <td>\n                CoreML 只能导出固定分辨率，其他分辨率可自行导出。支持 iOS 13+。<code>s</code> 代表下采样比。<a href=\"documentation/inference_zh_Hans.md#coreml\">文档</a>，<a href=\"https://github.com/PeterL1n/RobustVideoMatting/tree/coreml\">导出</a>\n            </td>\n        </tr>\n    </tbody>\n</table>\n\n所有模型可在 [Google Drive](https://drive.google.com/drive/folders/1pBsG-SCTatv-95SnEuxmnvvlRx208VKj?usp=sharing) 或[百度网盘](https://pan.baidu.com/s/1puPSxQqgBFOVpW4W7AolkA)（密码: gym7）上下载。\n\n<br>\n\n## PyTorch 范例\n\n1. 安装 Python 库:\n```sh\npip install -r requirements_inference.txt\n```\n\n2. 加载模型:\n\n```python\nimport torch\nfrom model import MattingNetwork\n\nmodel = MattingNetwork('mobilenetv3').eval().cuda()  # 或 \"resnet50\"\nmodel.load_state_dict(torch.load('rvm_mobilenetv3.pth'))\n```\n\n3. 若只需要做视频抠像处理，我们提供简单的 API:\n\n```python\nfrom inference import convert_video\n\nconvert_video(\n    model,                           # 模型，可以加载到任何设备（cpu 或 cuda）\n    input_source='input.mp4',        # 视频文件，或图片序列文件夹\n    output_type='video',             # 可选 \"video\"（视频）或 \"png_sequence\"（PNG 序列）\n    output_composition='com.mp4',    # 若导出视频，提供文件路径。若导出 PNG 序列，提供文件夹路径\n    output_alpha=\"pha.mp4\",          # [可选项] 输出透明度预测\n    output_foreground=\"fgr.mp4\",     # [可选项] 输出前景预测\n    output_video_mbps=4,             # 若导出视频，提供视频码率\n    downsample_ratio=None,           # 下采样比，可根据具体视频调节，或 None 选择自动\n    seq_chunk=12,                    # 设置多帧并行计算\n)\n```\n\n4. 或自己写推断逻辑:\n```python\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms import ToTensor\nfrom inference_utils import VideoReader, VideoWriter\n\nreader = VideoReader('input.mp4', transform=ToTensor())\nwriter = VideoWriter('output.mp4', frame_rate=30)\n\nbgr = torch.tensor([.47, 1, .6]).view(3, 1, 1).cuda()  # 绿背景\nrec = [None] * 4                                       # 初始循环记忆（Recurrent States）\ndownsample_ratio = 0.25                                # 下采样比，根据视频调节\n\nwith torch.no_grad():\n    for src in DataLoader(reader):                     # 输入张量，RGB通道，范围为 0～1\n        fgr, pha, *rec = model(src.cuda(), *rec, downsample_ratio)  # 将上一帧的记忆给下一帧\n        com = fgr * pha + bgr * (1 - pha)              # 将前景合成到绿色背景\n        writer.write(com)                              # 输出帧\n```\n\n5. 模型和 API 也可通过 TorchHub 快速载入。\n\n```python\n# 加载模型\nmodel = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"mobilenetv3\") # 或 \"resnet50\"\n\n# 转换 API\nconvert_video = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"converter\")\n```\n\n[推断文档](documentation/inference_zh_Hans.md)里有对 `downsample_ratio` 参数，API 使用，和高阶使用的讲解。\n\n<br>\n\n## 训练和评估\n\n请参照[训练文档（英文）](documentation/training.md)。\n\n<br>\n\n## 速度\n\n速度用 `inference_speed_test.py` 测量以供参考。\n\n| GPU            | dType | HD (1920x1080) | 4K (3840x2160) |\n| -------------- | ----- | -------------- |----------------|\n| RTX 3090       | FP16  | 172 FPS        | 154 FPS        |\n| RTX 2060 Super | FP16  | 134 FPS        | 108 FPS        |\n| GTX 1080 Ti    | FP32  | 104 FPS        | 74 FPS         |\n\n* 注释1：HD 使用 `downsample_ratio=0.25`，4K 使用 `downsample_ratio=0.125`。 所有测试都使用 batch size 1 和 frame chunk 1。\n* 注释2：图灵架构之前的 GPU 不支持 FP16 推理，所以 GTX 1080 Ti 使用 FP32。\n* 注释3：我们只测量张量吞吐量（tensor throughput）。 提供的视频转换脚本会慢得多，因为它不使用硬件视频编码/解码，也没有在并行线程上完成张量传输。如果您有兴趣在 Python 中实现硬件视频编码/解码，请参考 [PyNvCodec](https://github.com/NVIDIA/VideoProcessingFramework)。\n\n<br>\n\n## 项目成员\n* [Shanchuan Lin](https://www.linkedin.com/in/shanchuanlin/)\n* [Linjie Yang](https://sites.google.com/site/linjieyang89/)\n* [Imran Saleemi](https://www.linkedin.com/in/imran-saleemi/)\n* [Soumyadip Sengupta](https://homes.cs.washington.edu/~soumya91/)\n\n<br>\n\n## 第三方资源\n\n* [NCNN C++ Android](https://github.com/FeiGeChuanShu/ncnn_Android_RobustVideoMatting) ([@FeiGeChuanShu](https://github.com/FeiGeChuanShu))\n* [lite.ai.toolkit](https://github.com/DefTruth/RobustVideoMatting.lite.ai.toolkit) ([@DefTruth](https://github.com/DefTruth))\n* [Gradio Web Demo](https://huggingface.co/spaces/akhaliq/Robust-Video-Matting) ([@AK391](https://github.com/AK391))\n* [带有 NatML 的 Unity 引擎](https://hub.natml.ai/@natsuite/robust-video-matting) ([@natsuite](https://github.com/natsuite))  \n* [MNN C++ Demo](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/mnn/cv/mnn_rvm.cpp) ([@DefTruth](https://github.com/DefTruth))\n* [TNN C++ Demo](https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/tnn/cv/tnn_rvm.cpp) ([@DefTruth](https://github.com/DefTruth))\n\n"
  },
  {
    "path": "dataset/augmentation.py",
    "content": "import easing_functions as ef\nimport random\nimport torch\nfrom torchvision import transforms\nfrom torchvision.transforms import functional as F\n\n\nclass MotionAugmentation:\n    def __init__(self,\n                 size,\n                 prob_fgr_affine,\n                 prob_bgr_affine,\n                 prob_noise,\n                 prob_color_jitter,\n                 prob_grayscale,\n                 prob_sharpness,\n                 prob_blur,\n                 prob_hflip,\n                 prob_pause,\n                 static_affine=True,\n                 aspect_ratio_range=(0.9, 1.1)):\n        self.size = size\n        self.prob_fgr_affine = prob_fgr_affine\n        self.prob_bgr_affine = prob_bgr_affine\n        self.prob_noise = prob_noise\n        self.prob_color_jitter = prob_color_jitter\n        self.prob_grayscale = prob_grayscale\n        self.prob_sharpness = prob_sharpness\n        self.prob_blur = prob_blur\n        self.prob_hflip = prob_hflip\n        self.prob_pause = prob_pause\n        self.static_affine = static_affine\n        self.aspect_ratio_range = aspect_ratio_range\n        \n    def __call__(self, fgrs, phas, bgrs):\n        # Foreground affine\n        if random.random() < self.prob_fgr_affine:\n            fgrs, phas = self._motion_affine(fgrs, phas)\n\n        # Background affine\n        if random.random() < self.prob_bgr_affine / 2:\n            bgrs = self._motion_affine(bgrs)\n        if random.random() < self.prob_bgr_affine / 2:\n            fgrs, phas, bgrs = self._motion_affine(fgrs, phas, bgrs)\n                \n        # Still Affine\n        if self.static_affine:\n            fgrs, phas = self._static_affine(fgrs, phas, scale_ranges=(0.5, 1))\n            bgrs = self._static_affine(bgrs, scale_ranges=(1, 1.5))\n        \n        # To tensor\n        fgrs = torch.stack([F.to_tensor(fgr) for fgr in fgrs])\n        phas = torch.stack([F.to_tensor(pha) for pha in phas])\n        bgrs = torch.stack([F.to_tensor(bgr) for bgr in bgrs])\n        \n        # Resize\n        params = transforms.RandomResizedCrop.get_params(fgrs, scale=(1, 1), ratio=self.aspect_ratio_range)\n        fgrs = F.resized_crop(fgrs, *params, self.size, interpolation=F.InterpolationMode.BILINEAR)\n        phas = F.resized_crop(phas, *params, self.size, interpolation=F.InterpolationMode.BILINEAR)\n        params = transforms.RandomResizedCrop.get_params(bgrs, scale=(1, 1), ratio=self.aspect_ratio_range)\n        bgrs = F.resized_crop(bgrs, *params, self.size, interpolation=F.InterpolationMode.BILINEAR)\n\n        # Horizontal flip\n        if random.random() < self.prob_hflip:\n            fgrs = F.hflip(fgrs)\n            phas = F.hflip(phas)\n        if random.random() < self.prob_hflip:\n            bgrs = F.hflip(bgrs)\n\n        # Noise\n        if random.random() < self.prob_noise:\n            fgrs, bgrs = self._motion_noise(fgrs, bgrs)\n        \n        # Color jitter\n        if random.random() < self.prob_color_jitter:\n            fgrs = self._motion_color_jitter(fgrs)\n        if random.random() < self.prob_color_jitter:\n            bgrs = self._motion_color_jitter(bgrs)\n            \n        # Grayscale\n        if random.random() < self.prob_grayscale:\n            fgrs = F.rgb_to_grayscale(fgrs, num_output_channels=3).contiguous()\n            bgrs = F.rgb_to_grayscale(bgrs, num_output_channels=3).contiguous()\n            \n        # Sharpen\n        if random.random() < self.prob_sharpness:\n            sharpness = random.random() * 8\n            fgrs = F.adjust_sharpness(fgrs, sharpness)\n            phas = F.adjust_sharpness(phas, sharpness)\n            bgrs = F.adjust_sharpness(bgrs, sharpness)\n        \n        # Blur\n        if random.random() < self.prob_blur / 3:\n            fgrs, phas = self._motion_blur(fgrs, phas)\n        if random.random() < self.prob_blur / 3:\n            bgrs = self._motion_blur(bgrs)\n        if random.random() < self.prob_blur / 3:\n            fgrs, phas, bgrs = self._motion_blur(fgrs, phas, bgrs)\n\n        # Pause\n        if random.random() < self.prob_pause:\n            fgrs, phas, bgrs = self._motion_pause(fgrs, phas, bgrs)\n        \n        return fgrs, phas, bgrs\n    \n    def _static_affine(self, *imgs, scale_ranges):\n        params = transforms.RandomAffine.get_params(\n            degrees=(-10, 10), translate=(0.1, 0.1), scale_ranges=scale_ranges,\n            shears=(-5, 5), img_size=imgs[0][0].size)\n        imgs = [[F.affine(t, *params, F.InterpolationMode.BILINEAR) for t in img] for img in imgs]\n        return imgs if len(imgs) > 1 else imgs[0] \n    \n    def _motion_affine(self, *imgs):\n        config = dict(degrees=(-10, 10), translate=(0.1, 0.1),\n                      scale_ranges=(0.9, 1.1), shears=(-5, 5), img_size=imgs[0][0].size)\n        angleA, (transXA, transYA), scaleA, (shearXA, shearYA) = transforms.RandomAffine.get_params(**config)\n        angleB, (transXB, transYB), scaleB, (shearXB, shearYB) = transforms.RandomAffine.get_params(**config)\n        \n        T = len(imgs[0])\n        easing = random_easing_fn()\n        for t in range(T):\n            percentage = easing(t / (T - 1))\n            angle = lerp(angleA, angleB, percentage)\n            transX = lerp(transXA, transXB, percentage)\n            transY = lerp(transYA, transYB, percentage)\n            scale = lerp(scaleA, scaleB, percentage)\n            shearX = lerp(shearXA, shearXB, percentage)\n            shearY = lerp(shearYA, shearYB, percentage)\n            for img in imgs:\n                img[t] = F.affine(img[t], angle, (transX, transY), scale, (shearX, shearY), F.InterpolationMode.BILINEAR)\n        return imgs if len(imgs) > 1 else imgs[0]\n    \n    def _motion_noise(self, *imgs):\n        grain_size = random.random() * 3 + 1 # range 1 ~ 4\n        monochrome = random.random() < 0.5\n        for img in imgs:\n            T, C, H, W = img.shape\n            noise = torch.randn((T, 1 if monochrome else C, round(H / grain_size), round(W / grain_size)))\n            noise.mul_(random.random() * 0.2 / grain_size)\n            if grain_size != 1:\n                noise = F.resize(noise, (H, W))\n            img.add_(noise).clamp_(0, 1)\n        return imgs if len(imgs) > 1 else imgs[0]\n    \n    def _motion_color_jitter(self, *imgs):\n        brightnessA, brightnessB, contrastA, contrastB, saturationA, saturationB, hueA, hueB \\\n            = torch.randn(8).mul(0.1).tolist()\n        strength = random.random() * 0.2\n        easing = random_easing_fn()\n        T = len(imgs[0])\n        for t in range(T):\n            percentage = easing(t / (T - 1)) * strength\n            for img in imgs:\n                img[t] = F.adjust_brightness(img[t], max(1 + lerp(brightnessA, brightnessB, percentage), 0.1))\n                img[t] = F.adjust_contrast(img[t], max(1 + lerp(contrastA, contrastB, percentage), 0.1))\n                img[t] = F.adjust_saturation(img[t], max(1 + lerp(brightnessA, brightnessB, percentage), 0.1))\n                img[t] = F.adjust_hue(img[t], min(0.5, max(-0.5, lerp(hueA, hueB, percentage) * 0.1)))\n        return imgs if len(imgs) > 1 else imgs[0]\n    \n    def _motion_blur(self, *imgs):\n        blurA = random.random() * 10\n        blurB = random.random() * 10\n\n        T = len(imgs[0])\n        easing = random_easing_fn()\n        for t in range(T):\n            percentage = easing(t / (T - 1))\n            blur = max(lerp(blurA, blurB, percentage), 0)\n            if blur != 0:\n                kernel_size = int(blur * 2)\n                if kernel_size % 2 == 0:\n                    kernel_size += 1 # Make kernel_size odd\n                for img in imgs:\n                    img[t] = F.gaussian_blur(img[t], kernel_size, sigma=blur)\n    \n        return imgs if len(imgs) > 1 else imgs[0]\n    \n    def _motion_pause(self, *imgs):\n        T = len(imgs[0])\n        pause_frame = random.choice(range(T - 1))\n        pause_length = random.choice(range(T - pause_frame))\n        for img in imgs:\n            img[pause_frame + 1 : pause_frame + pause_length] = img[pause_frame]\n        return imgs if len(imgs) > 1 else imgs[0]\n    \n\ndef lerp(a, b, percentage):\n    return a * (1 - percentage) + b * percentage\n\n\ndef random_easing_fn():\n    if random.random() < 0.2:\n        return ef.LinearInOut()\n    else:\n        return random.choice([\n            ef.BackEaseIn,\n            ef.BackEaseOut,\n            ef.BackEaseInOut,\n            ef.BounceEaseIn,\n            ef.BounceEaseOut,\n            ef.BounceEaseInOut,\n            ef.CircularEaseIn,\n            ef.CircularEaseOut,\n            ef.CircularEaseInOut,\n            ef.CubicEaseIn,\n            ef.CubicEaseOut,\n            ef.CubicEaseInOut,\n            ef.ExponentialEaseIn,\n            ef.ExponentialEaseOut,\n            ef.ExponentialEaseInOut,\n            ef.ElasticEaseIn,\n            ef.ElasticEaseOut,\n            ef.ElasticEaseInOut,\n            ef.QuadEaseIn,\n            ef.QuadEaseOut,\n            ef.QuadEaseInOut,\n            ef.QuarticEaseIn,\n            ef.QuarticEaseOut,\n            ef.QuarticEaseInOut,\n            ef.QuinticEaseIn,\n            ef.QuinticEaseOut,\n            ef.QuinticEaseInOut,\n            ef.SineEaseIn,\n            ef.SineEaseOut,\n            ef.SineEaseInOut,\n            Step,\n        ])()\n\nclass Step: # Custom easing function for sudden change.\n    def __call__(self, value):\n        return 0 if value < 0.5 else 1\n\n\n# ---------------------------- Frame Sampler ----------------------------\n\n\nclass TrainFrameSampler:\n    def __init__(self, speed=[0.5, 1, 2, 3, 4, 5]):\n        self.speed = speed\n    \n    def __call__(self, seq_length):\n        frames = list(range(seq_length))\n        \n        # Speed up\n        speed = random.choice(self.speed)\n        frames = [int(f * speed) for f in frames]\n        \n        # Shift\n        shift = random.choice(range(seq_length))\n        frames = [f + shift for f in frames]\n        \n        # Reverse\n        if random.random() < 0.5:\n            frames = frames[::-1]\n\n        return frames\n    \nclass ValidFrameSampler:\n    def __call__(self, seq_length):\n        return range(seq_length)\n"
  },
  {
    "path": "dataset/coco.py",
    "content": "import os\nimport numpy as np\nimport random\nimport json\nimport os\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom torchvision.transforms import functional as F\nfrom PIL import Image\n\n\nclass CocoPanopticDataset(Dataset):\n    def __init__(self,\n                 imgdir: str,\n                 anndir: str,\n                 annfile: str,\n                 transform=None):\n        with open(annfile) as f:\n            self.data = json.load(f)['annotations']\n            self.data = list(filter(lambda data: any(info['category_id'] == 1 for info in data['segments_info']), self.data))\n        self.imgdir = imgdir\n        self.anndir = anndir\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.data)\n    \n    def __getitem__(self, idx):\n        data = self.data[idx]\n        img = self._load_img(data)\n        seg = self._load_seg(data)\n        \n        if self.transform is not None:\n            img, seg = self.transform(img, seg)\n            \n        return img, seg\n\n    def _load_img(self, data):\n        with Image.open(os.path.join(self.imgdir, data['file_name'].replace('.png', '.jpg'))) as img:\n            return img.convert('RGB')\n    \n    def _load_seg(self, data):\n        with Image.open(os.path.join(self.anndir, data['file_name'])) as ann:\n            ann.load()\n            \n        ann = np.array(ann, copy=False).astype(np.int32)\n        ann = ann[:, :, 0] + 256 * ann[:, :, 1] + 256 * 256 * ann[:, :, 2]\n        seg = np.zeros(ann.shape, np.uint8)\n        \n        for segments_info in data['segments_info']:\n            if segments_info['category_id'] in [1, 27, 32]: # person, backpack, tie\n                seg[ann == segments_info['id']] = 255\n        \n        return Image.fromarray(seg)\n    \n\nclass CocoPanopticTrainAugmentation:\n    def __init__(self, size):\n        self.size = size\n        self.jitter = transforms.ColorJitter(0.1, 0.1, 0.1, 0.1)\n    \n    def __call__(self, img, seg):\n        # Affine\n        params = transforms.RandomAffine.get_params(degrees=(-20, 20), translate=(0.1, 0.1),\n                                                    scale_ranges=(1, 1), shears=(-10, 10), img_size=img.size)\n        img = F.affine(img, *params, interpolation=F.InterpolationMode.BILINEAR)\n        seg = F.affine(seg, *params, interpolation=F.InterpolationMode.NEAREST)\n        \n        # Resize\n        params = transforms.RandomResizedCrop.get_params(img, scale=(0.5, 1), ratio=(0.7, 1.3))\n        img = F.resized_crop(img, *params, self.size, interpolation=F.InterpolationMode.BILINEAR)\n        seg = F.resized_crop(seg, *params, self.size, interpolation=F.InterpolationMode.NEAREST)\n        \n        # Horizontal flip\n        if random.random() < 0.5:\n            img = F.hflip(img)\n            seg = F.hflip(seg)\n        \n        # Color jitter\n        img = self.jitter(img)\n        \n        # To tensor\n        img = F.to_tensor(img)\n        seg = F.to_tensor(seg)\n        \n        return img, seg\n    \n\nclass CocoPanopticValidAugmentation:\n    def __init__(self, size):\n        self.size = size\n    \n    def __call__(self, img, seg):\n        # Resize\n        params = transforms.RandomResizedCrop.get_params(img, scale=(1, 1), ratio=(1., 1.))\n        img = F.resized_crop(img, *params, self.size, interpolation=F.InterpolationMode.BILINEAR)\n        seg = F.resized_crop(seg, *params, self.size, interpolation=F.InterpolationMode.NEAREST)\n        \n        # To tensor\n        img = F.to_tensor(img)\n        seg = F.to_tensor(seg)\n        \n        return img, seg"
  },
  {
    "path": "dataset/imagematte.py",
    "content": "import os\nimport random\nfrom torch.utils.data import Dataset\nfrom PIL import Image\n\nfrom .augmentation import MotionAugmentation\n\n\nclass ImageMatteDataset(Dataset):\n    def __init__(self,\n                 imagematte_dir,\n                 background_image_dir,\n                 background_video_dir,\n                 size,\n                 seq_length,\n                 seq_sampler,\n                 transform):\n        self.imagematte_dir = imagematte_dir\n        self.imagematte_files = os.listdir(os.path.join(imagematte_dir, 'fgr'))\n        self.background_image_dir = background_image_dir\n        self.background_image_files = os.listdir(background_image_dir)\n        self.background_video_dir = background_video_dir\n        self.background_video_clips = os.listdir(background_video_dir)\n        self.background_video_frames = [sorted(os.listdir(os.path.join(background_video_dir, clip)))\n                                        for clip in self.background_video_clips]\n        self.seq_length = seq_length\n        self.seq_sampler = seq_sampler\n        self.size = size\n        self.transform = transform\n        \n    def __len__(self):\n        return max(len(self.imagematte_files), len(self.background_image_files) + len(self.background_video_clips))\n    \n    def __getitem__(self, idx):\n        if random.random() < 0.5:\n            bgrs = self._get_random_image_background()\n        else:\n            bgrs = self._get_random_video_background()\n        \n        fgrs, phas = self._get_imagematte(idx)\n        \n        if self.transform is not None:\n            return self.transform(fgrs, phas, bgrs)\n        \n        return fgrs, phas, bgrs\n    \n    def _get_imagematte(self, idx):\n        with Image.open(os.path.join(self.imagematte_dir, 'fgr', self.imagematte_files[idx % len(self.imagematte_files)])) as fgr, \\\n             Image.open(os.path.join(self.imagematte_dir, 'pha', self.imagematte_files[idx % len(self.imagematte_files)])) as pha:\n            fgr = self._downsample_if_needed(fgr.convert('RGB'))\n            pha = self._downsample_if_needed(pha.convert('L'))\n        fgrs = [fgr] * self.seq_length\n        phas = [pha] * self.seq_length\n        return fgrs, phas\n    \n    def _get_random_image_background(self):\n        with Image.open(os.path.join(self.background_image_dir, self.background_image_files[random.choice(range(len(self.background_image_files)))])) as bgr:\n            bgr = self._downsample_if_needed(bgr.convert('RGB'))\n        bgrs = [bgr] * self.seq_length\n        return bgrs\n\n    def _get_random_video_background(self):\n        clip_idx = random.choice(range(len(self.background_video_clips)))\n        frame_count = len(self.background_video_frames[clip_idx])\n        frame_idx = random.choice(range(max(1, frame_count - self.seq_length)))\n        clip = self.background_video_clips[clip_idx]\n        bgrs = []\n        for i in self.seq_sampler(self.seq_length):\n            frame_idx_t = frame_idx + i\n            frame = self.background_video_frames[clip_idx][frame_idx_t % frame_count]\n            with Image.open(os.path.join(self.background_video_dir, clip, frame)) as bgr:\n                bgr = self._downsample_if_needed(bgr.convert('RGB'))\n            bgrs.append(bgr)\n        return bgrs\n    \n    def _downsample_if_needed(self, img):\n        w, h = img.size\n        if min(w, h) > self.size:\n            scale = self.size / min(w, h)\n            w = int(scale * w)\n            h = int(scale * h)\n            img = img.resize((w, h))\n        return img\n\nclass ImageMatteAugmentation(MotionAugmentation):\n    def __init__(self, size):\n        super().__init__(\n            size=size,\n            prob_fgr_affine=0.95,\n            prob_bgr_affine=0.3,\n            prob_noise=0.05,\n            prob_color_jitter=0.3,\n            prob_grayscale=0.03,\n            prob_sharpness=0.05,\n            prob_blur=0.02,\n            prob_hflip=0.5,\n            prob_pause=0.03,\n        )\n"
  },
  {
    "path": "dataset/spd.py",
    "content": "import os\nfrom torch.utils.data import Dataset\nfrom PIL import Image\n\n\nclass SuperviselyPersonDataset(Dataset):\n    def __init__(self, imgdir, segdir, transform=None):\n        self.img_dir = imgdir\n        self.img_files = sorted(os.listdir(imgdir))\n        self.seg_dir = segdir\n        self.seg_files = sorted(os.listdir(segdir))\n        assert len(self.img_files) == len(self.seg_files)\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.img_files)\n    \n    def __getitem__(self, idx):\n        with Image.open(os.path.join(self.img_dir, self.img_files[idx])) as img, \\\n             Image.open(os.path.join(self.seg_dir, self.seg_files[idx])) as seg:\n            img = img.convert('RGB')\n            seg = seg.convert('L')\n        \n        if self.transform is not None:\n            img, seg = self.transform(img, seg)\n            \n        return img, seg\n"
  },
  {
    "path": "dataset/videomatte.py",
    "content": "import os\nimport random\nfrom torch.utils.data import Dataset\nfrom PIL import Image\n\nfrom .augmentation import MotionAugmentation\n\n\nclass VideoMatteDataset(Dataset):\n    def __init__(self,\n                 videomatte_dir,\n                 background_image_dir,\n                 background_video_dir,\n                 size,\n                 seq_length,\n                 seq_sampler,\n                 transform=None):\n        self.background_image_dir = background_image_dir\n        self.background_image_files = os.listdir(background_image_dir)\n        self.background_video_dir = background_video_dir\n        self.background_video_clips = sorted(os.listdir(background_video_dir))\n        self.background_video_frames = [sorted(os.listdir(os.path.join(background_video_dir, clip)))\n                                        for clip in self.background_video_clips]\n        \n        self.videomatte_dir = videomatte_dir\n        self.videomatte_clips = sorted(os.listdir(os.path.join(videomatte_dir, 'fgr')))\n        self.videomatte_frames = [sorted(os.listdir(os.path.join(videomatte_dir, 'fgr', clip))) \n                                  for clip in self.videomatte_clips]\n        self.videomatte_idx = [(clip_idx, frame_idx) \n                               for clip_idx in range(len(self.videomatte_clips)) \n                               for frame_idx in range(0, len(self.videomatte_frames[clip_idx]), seq_length)]\n        self.size = size\n        self.seq_length = seq_length\n        self.seq_sampler = seq_sampler\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.videomatte_idx)\n    \n    def __getitem__(self, idx):\n        if random.random() < 0.5:\n            bgrs = self._get_random_image_background()\n        else:\n            bgrs = self._get_random_video_background()\n        \n        fgrs, phas = self._get_videomatte(idx)\n        \n        if self.transform is not None:\n            return self.transform(fgrs, phas, bgrs)\n        \n        return fgrs, phas, bgrs\n    \n    def _get_random_image_background(self):\n        with Image.open(os.path.join(self.background_image_dir, random.choice(self.background_image_files))) as bgr:\n            bgr = self._downsample_if_needed(bgr.convert('RGB'))\n        bgrs = [bgr] * self.seq_length\n        return bgrs\n    \n    def _get_random_video_background(self):\n        clip_idx = random.choice(range(len(self.background_video_clips)))\n        frame_count = len(self.background_video_frames[clip_idx])\n        frame_idx = random.choice(range(max(1, frame_count - self.seq_length)))\n        clip = self.background_video_clips[clip_idx]\n        bgrs = []\n        for i in self.seq_sampler(self.seq_length):\n            frame_idx_t = frame_idx + i\n            frame = self.background_video_frames[clip_idx][frame_idx_t % frame_count]\n            with Image.open(os.path.join(self.background_video_dir, clip, frame)) as bgr:\n                bgr = self._downsample_if_needed(bgr.convert('RGB'))\n            bgrs.append(bgr)\n        return bgrs\n    \n    def _get_videomatte(self, idx):\n        clip_idx, frame_idx = self.videomatte_idx[idx]\n        clip = self.videomatte_clips[clip_idx]\n        frame_count = len(self.videomatte_frames[clip_idx])\n        fgrs, phas = [], []\n        for i in self.seq_sampler(self.seq_length):\n            frame = self.videomatte_frames[clip_idx][(frame_idx + i) % frame_count]\n            with Image.open(os.path.join(self.videomatte_dir, 'fgr', clip, frame)) as fgr, \\\n                 Image.open(os.path.join(self.videomatte_dir, 'pha', clip, frame)) as pha:\n                    fgr = self._downsample_if_needed(fgr.convert('RGB'))\n                    pha = self._downsample_if_needed(pha.convert('L'))\n            fgrs.append(fgr)\n            phas.append(pha)\n        return fgrs, phas\n    \n    def _downsample_if_needed(self, img):\n        w, h = img.size\n        if min(w, h) > self.size:\n            scale = self.size / min(w, h)\n            w = int(scale * w)\n            h = int(scale * h)\n            img = img.resize((w, h))\n        return img\n\nclass VideoMatteTrainAugmentation(MotionAugmentation):\n    def __init__(self, size):\n        super().__init__(\n            size=size,\n            prob_fgr_affine=0.3,\n            prob_bgr_affine=0.3,\n            prob_noise=0.1,\n            prob_color_jitter=0.3,\n            prob_grayscale=0.02,\n            prob_sharpness=0.1,\n            prob_blur=0.02,\n            prob_hflip=0.5,\n            prob_pause=0.03,\n        )\n\nclass VideoMatteValidAugmentation(MotionAugmentation):\n    def __init__(self, size):\n        super().__init__(\n            size=size,\n            prob_fgr_affine=0,\n            prob_bgr_affine=0,\n            prob_noise=0,\n            prob_color_jitter=0,\n            prob_grayscale=0,\n            prob_sharpness=0,\n            prob_blur=0,\n            prob_hflip=0,\n            prob_pause=0,\n        )\n"
  },
  {
    "path": "dataset/youtubevis.py",
    "content": "import torch\nimport os\nimport json\nimport numpy as np\nimport random\nfrom torch.utils.data import Dataset\nfrom PIL import Image\nfrom torchvision import transforms\nfrom torchvision.transforms import functional as F\n\n\nclass YouTubeVISDataset(Dataset):\n    def __init__(self, videodir, annfile, size, seq_length, seq_sampler, transform=None):\n        self.videodir = videodir\n        self.size = size\n        self.seq_length = seq_length\n        self.seq_sampler = seq_sampler\n        self.transform = transform\n        \n        with open(annfile) as f:\n            data = json.load(f)\n\n        self.masks = {}\n        for ann in data['annotations']:\n            if ann['category_id'] == 26: # person\n                video_id = ann['video_id']\n                if video_id not in self.masks:\n                    self.masks[video_id] = [[] for _ in range(len(ann['segmentations']))]\n                for frame, mask in zip(self.masks[video_id], ann['segmentations']):\n                    if mask is not None:\n                        frame.append(mask)\n        \n        self.videos = {}\n        for video in data['videos']:\n            video_id = video['id']\n            if video_id in self.masks:\n                self.videos[video_id] = video\n        \n        self.index = []\n        for video_id in self.videos.keys():\n            for frame in range(len(self.videos[video_id]['file_names'])):\n                self.index.append((video_id, frame))\n                \n    def __len__(self):\n        return len(self.index)\n    \n    def __getitem__(self, idx):\n        video_id, frame_id = self.index[idx]\n        video = self.videos[video_id]\n        frame_count = len(self.videos[video_id]['file_names'])\n        H, W = video['height'], video['width']\n        \n        imgs, segs = [], []\n        for t in self.seq_sampler(self.seq_length):\n            frame = (frame_id + t) % frame_count\n\n            filename = video['file_names'][frame]\n            masks = self.masks[video_id][frame]\n        \n            with Image.open(os.path.join(self.videodir, filename)) as img:\n                imgs.append(self._downsample_if_needed(img.convert('RGB'), Image.BILINEAR))\n        \n            seg = np.zeros((H, W), dtype=np.uint8)\n            for mask in masks:\n                seg |= self._decode_rle(mask)\n            segs.append(self._downsample_if_needed(Image.fromarray(seg), Image.NEAREST))\n            \n        if self.transform is not None:\n            imgs, segs = self.transform(imgs, segs)\n        \n        return imgs, segs\n    \n    def _decode_rle(self, rle):\n        H, W = rle['size']\n        msk = np.zeros(H * W, dtype=np.uint8)\n        encoding = rle['counts']\n        skip = 0\n        for i in range(0, len(encoding) - 1, 2):\n            skip += encoding[i]\n            draw = encoding[i + 1]\n            msk[skip : skip + draw] = 255\n            skip += draw\n        return msk.reshape(W, H).transpose()\n    \n    def _downsample_if_needed(self, img, resample):\n        w, h = img.size\n        if min(w, h) > self.size:\n            scale = self.size / min(w, h)\n            w = int(scale * w)\n            h = int(scale * h)\n            img = img.resize((w, h), resample)\n        return img\n\n\nclass YouTubeVISAugmentation:\n    def __init__(self, size):\n        self.size = size\n        self.jitter = transforms.ColorJitter(0.3, 0.3, 0.3, 0.15)\n    \n    def __call__(self, imgs, segs):\n        \n        # To tensor\n        imgs = torch.stack([F.to_tensor(img) for img in imgs])\n        segs = torch.stack([F.to_tensor(seg) for seg in segs])\n        \n        # Resize\n        params = transforms.RandomResizedCrop.get_params(imgs, scale=(0.8, 1), ratio=(0.9, 1.1))\n        imgs = F.resized_crop(imgs, *params, self.size, interpolation=F.InterpolationMode.BILINEAR)\n        segs = F.resized_crop(segs, *params, self.size, interpolation=F.InterpolationMode.BILINEAR)\n        \n        # Color jitter\n        imgs = self.jitter(imgs)\n        \n        # Grayscale\n        if random.random() < 0.05:\n            imgs = F.rgb_to_grayscale(imgs, num_output_channels=3)\n        \n        # Horizontal flip\n        if random.random() < 0.5:\n            imgs = F.hflip(imgs)\n            segs = F.hflip(segs)\n        \n        return imgs, segs\n"
  },
  {
    "path": "documentation/inference.md",
    "content": "# Inference\n\n<p align=\"center\">English | <a href=\"inference_zh_Hans.md\">中文</a></p>\n\n## Content\n\n* [Concepts](#concepts)\n    * [Downsample Ratio](#downsample-ratio)\n    * [Recurrent States](#recurrent-states)\n* [PyTorch](#pytorch)\n* [TorchHub](#torchhub)\n* [TorchScript](#torchscript)\n* [ONNX](#onnx)\n* [TensorFlow](#tensorflow)\n* [TensorFlow.js](#tensorflowjs)\n* [CoreML](#coreml)\n\n<br>\n\n\n## Concepts\n\n### Downsample Ratio\n\nThe table provides a general guideline. Please adjust based on your video content.\n\n| Resolution    | Portrait      | Full-Body      |\n| ------------- | ------------- | -------------- |\n| <= 512x512    | 1             | 1              |\n| 1280x720      | 0.375         | 0.6            |\n| 1920x1080     | 0.25          | 0.4            |\n| 3840x2160     | 0.125         | 0.2            |\n\nInternally, the model resizes down the input for stage 1. Then, it refines at high-resolution for stage 2.\n\nSet `downsample_ratio` so that the downsampled resolution is between 256 and 512. For example, for `1920x1080` input with `downsample_ratio=0.25`, the resized resolution `480x270` is between 256 and 512.\n\nAdjust `downsample_ratio` base on the video content. If the shot is portrait, a lower `downsample_ratio` is sufficient. If the shot contains the full human body, use high `downsample_ratio`. Note that higher `downsample_ratio` is not always better.\n\n\n<br>\n\n### Recurrent States\nThe model is a recurrent neural network. You must process frames sequentially and recycle its recurrent states. \n\n**Correct Way**\n\nThe recurrent outputs are recycled back as input when processing the next frame. The states are essentially the model's memory.\n\n```python\nrec = [None] * 4  # Initial recurrent states are None\n\nfor frame in YOUR_VIDEO:\n    fgr, pha, *rec = model(frame, *rec, downsample_ratio)\n```\n\n**Wrong Way**\n\nThe model does not utilize the recurrent states. Only use it to process independent images.\n\n```python\nfor frame in YOUR_VIDEO:\n    fgr, pha = model(frame, downsample_ratio)[:2]\n```\n\nMore technical details are in the [paper](https://peterl1n.github.io/RobustVideoMatting/).\n\n<br><br><br>\n\n\n## PyTorch\n\nModel loading:\n\n```python\nimport torch\nfrom model import MattingNetwork\n\nmodel = MattingNetwork(variant='mobilenetv3').eval().cuda() # Or variant=\"resnet50\"\nmodel.load_state_dict(torch.load('rvm_mobilenetv3.pth'))\n```\n\nExample inference loop:\n```python\nrec = [None] * 4 # Set initial recurrent states to None\n\nfor src in YOUR_VIDEO:  # src can be [B, C, H, W] or [B, T, C, H, W]\n    fgr, pha, *rec = model(src, *rec, downsample_ratio=0.25)\n```\n\n* `src`: Input frame. \n    * Can be of shape `[B, C, H, W]` or `[B, T, C, H, W]`. \n    * If `[B, T, C, H, W]`, a chunk of `T` frames can be given at once for better parallelism.\n    * RGB input is normalized to `0~1` range.\n\n* `fgr, pha`: Foreground and alpha predictions. \n    * Can be of shape `[B, C, H, W]` or `[B, T, C, H, W]` depends on `src`. \n    * `fgr` has `C=3` for RGB, `pha` has `C=1`.\n    * Outputs normalized to `0~1` range.\n* `rec`: Recurrent states. \n    * Type of `List[Tensor, Tensor, Tensor, Tensor]`. \n    * Initial `rec` can be `List[None, None, None, None]`.\n    * It has 4 recurrent states because the model has 4 ConvGRU layers.\n    * All tensors are rank 4 regardless of `src` rank.\n    * If a chunk of `T` frames is given, only the last frame's recurrent states will be returned.\n\nTo inference on video, here is a complete example:\n\n```python\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms import ToTensor\nfrom inference_utils import VideoReader, VideoWriter\n\nreader = VideoReader('input.mp4', transform=ToTensor())\nwriter = VideoWriter('output.mp4', frame_rate=30)\n\nbgr = torch.tensor([.47, 1, .6]).view(3, 1, 1).cuda()  # Green background.\nrec = [None] * 4                                       # Initial recurrent states.\n\nwith torch.no_grad():\n    for src in DataLoader(reader):\n        fgr, pha, *rec = model(src.cuda(), *rec, downsample_ratio=0.25)  # Cycle the recurrent states.\n        writer.write(fgr * pha + bgr * (1 - pha))\n```\n\nOr you can use the provided video converter:\n\n```python\nfrom inference import convert_video\n\nconvert_video(\n    model,                           # The loaded model, can be on any device (cpu or cuda).\n    input_source='input.mp4',        # A video file or an image sequence directory.\n    input_resize=(1920, 1080),       # [Optional] Resize the input (also the output).\n    downsample_ratio=0.25,           # [Optional] If None, make downsampled max size be 512px.\n    output_type='video',             # Choose \"video\" or \"png_sequence\"\n    output_composition='com.mp4',    # File path if video; directory path if png sequence.\n    output_alpha=\"pha.mp4\",          # [Optional] Output the raw alpha prediction.\n    output_foreground=\"fgr.mp4\",     # [Optional] Output the raw foreground prediction.\n    output_video_mbps=4,             # Output video mbps. Not needed for png sequence.\n    seq_chunk=12,                    # Process n frames at once for better parallelism.\n    num_workers=1,                   # Only for image sequence input. Reader threads.\n    progress=True                    # Print conversion progress.\n)\n```\n\nThe converter can also be invoked in command line:\n\n```sh\npython inference.py \\\n    --variant mobilenetv3 \\\n    --checkpoint \"CHECKPOINT\" \\\n    --device cuda \\\n    --input-source \"input.mp4\" \\\n    --downsample-ratio 0.25 \\\n    --output-type video \\\n    --output-composition \"composition.mp4\" \\\n    --output-alpha \"alpha.mp4\" \\\n    --output-foreground \"foreground.mp4\" \\\n    --output-video-mbps 4 \\\n    --seq-chunk 12\n```\n\n<br><br><br>\n\n## TorchHub\n\nModel loading:\n\n```python\nmodel = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"mobilenetv3\") # or \"resnet50\"\n```\n\nUse the conversion function. Refer to the documentation for `convert_video` function above.\n\n```python\nconvert_video = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"converter\")\n\nconvert_video(model, ...args...)\n```\n\n<br><br><br>\n\n## TorchScript\n\nModel loading:\n\n```python\nimport torch\nmodel = torch.jit.load('rvm_mobilenetv3.torchscript')\n```\n\nOptionally, freeze the model. This will trigger graph optimization, such as BatchNorm fusion etc. Frozen models are faster.\n\n```python\nmodel = torch.jit.freeze(model)\n```\n\nThen, you can use the `model` exactly the same as a PyTorch model, with the exception that you must manually provide `device` and `dtype` to the converter API for frozen model. For example:\n\n```python\nconvert_video(frozen_model, ...args..., device='cuda', dtype=torch.float32)\n```\n\n<br><br><br>\n\n## ONNX\n\nModel spec:\n* Inputs: [`src`, `r1i`, `r2i`, `r3i`, `r4i`, `downsample_ratio`]. \n    * `src` is the RGB input frame of shape `[B, C, H, W]` normalized to `0~1` range. \n    * `rXi` are the recurrent state inputs. Initial recurrent states are zero value tensors of shape `[1, 1, 1, 1]`.\n    * `downsample_ratio` is a tensor of shape `[1]`.\n    * Only `downsample_ratio` must have `dtype=FP32`. Other inputs must have `dtype` matching the loaded model's precision.\n* Outputs: [`fgr`, `pha`, `r1o`, `r2o`, `r3o`, `r4o`]\n    * `fgr, pha` are the foreground and alpha prediction. Normalized to `0~1` range.\n    * `rXo` are the recurrent state outputs.\n\nWe only show examples of using onnxruntime CUDA backend in Python.\n\nModel loading\n\n```python\nimport onnxruntime as ort\n\nsess = ort.InferenceSession('rvm_mobilenetv3_fp16.onnx')\n```\n\nNaive inference loop\n\n```python\nimport numpy as np\n\nrec = [ np.zeros([1, 1, 1, 1], dtype=np.float16) ] * 4  # Must match dtype of the model.\ndownsample_ratio = np.array([0.25], dtype=np.float32)  # dtype always FP32\n\nfor src in YOUR_VIDEO:  # src is of [B, C, H, W] with dtype of the model.\n    fgr, pha, *rec = sess.run([], {\n        'src': src, \n        'r1i': rec[0], \n        'r2i': rec[1], \n        'r3i': rec[2], \n        'r4i': rec[3], \n        'downsample_ratio': downsample_ratio\n    })\n```\n\nIf you use GPU version of ONNX Runtime, the above naive implementation has recurrent states transferred between CPU and GPU on every frame. They could have just stayed on the GPU for better performance. Below is an example using `iobinding` to eliminate useless transfers.\n\n```python\nimport onnxruntime as ort\nimport numpy as np\n\n# Load model.\nsess = ort.InferenceSession('rvm_mobilenetv3_fp16.onnx')\n\n# Create an io binding.\nio = sess.io_binding()\n\n# Create tensors on CUDA.\nrec = [ ort.OrtValue.ortvalue_from_numpy(np.zeros([1, 1, 1, 1], dtype=np.float16), 'cuda') ] * 4\ndownsample_ratio = ort.OrtValue.ortvalue_from_numpy(np.asarray([0.25], dtype=np.float32), 'cuda')\n\n# Set output binding.\nfor name in ['fgr', 'pha', 'r1o', 'r2o', 'r3o', 'r4o']:\n    io.bind_output(name, 'cuda')\n\n# Inference loop\nfor src in YOUR_VIDEO:\n    io.bind_cpu_input('src', src)\n    io.bind_ortvalue_input('r1i', rec[0])\n    io.bind_ortvalue_input('r2i', rec[1])\n    io.bind_ortvalue_input('r3i', rec[2])\n    io.bind_ortvalue_input('r4i', rec[3])\n    io.bind_ortvalue_input('downsample_ratio', downsample_ratio)\n\n    sess.run_with_iobinding(io)\n\n    fgr, pha, *rec = io.get_outputs()\n\n    # Only transfer `fgr` and `pha` to CPU.\n    fgr = fgr.numpy()\n    pha = pha.numpy()\n```\n\nNote: depending on the inference tool you choose, it may not support all the operations in our official ONNX model. You are responsible for modifying the model code and exporting your own ONNX model. You can refer to our exporter code in the [onnx branch](https://github.com/PeterL1n/RobustVideoMatting/tree/onnx).\n\n<br><br><br>\n\n### TensorFlow\n\nAn example usage:\n\n```python\nimport tensorflow as tf\n\nmodel = tf.keras.models.load_model('rvm_mobilenetv3_tf')\nmodel = tf.function(model)\n\nrec = [ tf.constant(0.) ] * 4         # Initial recurrent states.\ndownsample_ratio = tf.constant(0.25)  # Adjust based on your video.\n\nfor src in YOUR_VIDEO:  # src is of shape [B, H, W, C], not [B, C, H, W]!\n    out = model([src, *rec, downsample_ratio])\n    fgr, pha, *rec = out['fgr'], out['pha'], out['r1o'], out['r2o'], out['r3o'], out['r4o']\n```\n\nNote the the tensors are all channel last. Otherwise, the inputs and outputs are exactly the same as PyTorch.\n\nWe also provide the raw TensorFlow model code in the [tensorflow branch](https://github.com/PeterL1n/RobustVideoMatting/tree/tensorflow). You can transfer PyTorch checkpoint weights to TensorFlow models.\n\n<br><br><br>\n\n### TensorFlow.js\n\nWe provide a starter code in the [tfjs branch](https://github.com/PeterL1n/RobustVideoMatting/tree/tfjs). The example is very self-explanatory. It shows how to properly use the model.\n\n<br><br><br>\n\n### CoreML\n\nWe only show example usage of the CoreML models in Python API using `coremltools`. In production, the same logic can be applied in Swift. When processing the first frame, do not provide recurrent states. CoreML will internally construct zero tensors of the correct shapes as the initial recurrent states.\n\n```python\nimport coremltools as ct\n\nmodel = ct.models.model.MLModel('rvm_mobilenetv3_1920x1080_s0.25_int8.mlmodel')\n\nr1, r2, r3, r4 = None, None, None, None\n\nfor src in YOUR_VIDEO:  # src is PIL.Image.\n    \n    if r1 is None:\n        # Initial frame, do not provide recurrent states.\n        inputs = {'src': src}\n    else:\n        # Subsequent frames, provide recurrent states.\n        inputs = {'src': src, 'r1i': r1, 'r2i': r2, 'r3i': r3, 'r4i': r4}\n\n    outputs = model.predict(inputs)\n\n    fgr = outputs['fgr']  # PIL.Image.\n    pha = outputs['pha']  # PIL.Image.\n    \n    r1 = outputs['r1o']  # Numpy array.\n    r2 = outputs['r2o']  # Numpy array.\n    r3 = outputs['r3o']  # Numpy array.\n    r4 = outputs['r4o']  # Numpy array.\n\n```\n\nOur CoreML models only support fixed resolutions. If you need other resolutions, you can export them yourself. See [coreml branch](https://github.com/PeterL1n/RobustVideoMatting/tree/coreml) for model export. "
  },
  {
    "path": "documentation/inference_zh_Hans.md",
    "content": "# 推断文档\n\n<p align=\"center\"><a href=\"inference.md\">English</a> | 中文</p>\n\n## 目录\n\n* [概念](#概念)\n    * [下采样比](#下采样比)\n    * [循环记忆](#循环记忆)\n* [PyTorch](#pytorch)\n* [TorchHub](#torchhub)\n* [TorchScript](#torchscript)\n* [ONNX](#onnx)\n* [TensorFlow](#tensorflow)\n* [TensorFlow.js](#tensorflowjs)\n* [CoreML](#coreml)\n\n<br>\n\n\n## 概念\n\n### 下采样比\n\n该表仅供参考。可根据视频内容进行调节。\n\n| 分辨率         | 人像           | 全身            |\n| ------------- | ------------- | -------------- |\n| <= 512x512    | 1             | 1              |\n| 1280x720      | 0.375         | 0.6            |\n| 1920x1080     | 0.25          | 0.4            |\n| 3840x2160     | 0.125         | 0.2            |\n\n模型在内部将高分辨率输入缩小做初步的处理，然后再放大做细分处理。\n\n建议设置 `downsample_ratio` 使缩小后的分辨率维持在 256 到 512 像素之间. 例如，`1920x1080` 的输入用 `downsample_ratio=0.25`，缩小后的分辨率 `480x270` 在 256 到 512 像素之间。\n\n根据视频内容调整 `downsample_ratio`。若视频是上身人像，低 `downsample_ratio` 足矣。若视频是全身像，建议尝试更高的 `downsample_ratio`。但注意，过高的 `downsample_ratio` 反而会降低效果。\n\n\n<br>\n\n### 循环记忆\n此模型是循环神经网络（Recurrent Neural Network）。必须按顺序处理视频每帧，并提供网络循环记忆。\n\n**正确用法**\n\n循环记忆输出被传递到下一帧做输入。\n\n```python\nrec = [None] * 4  # 初始值设置为 None\n\nfor frame in YOUR_VIDEO:\n    fgr, pha, *rec = model(frame, *rec, downsample_ratio)\n```\n\n**错误用法**\n\n没有使用循环记忆。此方法仅可用于处理单独的图片。\n\n```python\nfor frame in YOUR_VIDEO:\n    fgr, pha = model(frame, downsample_ratio)[:2]\n```\n\n更多技术细节见[论文](https://peterl1n.github.io/RobustVideoMatting/)。\n\n<br><br><br>\n\n\n## PyTorch\n\n载入模型：\n\n```python\nimport torch\nfrom model import MattingNetwork\n\nmodel = MattingNetwork(variant='mobilenetv3').eval().cuda() # 或 variant=\"resnet50\"\nmodel.load_state_dict(torch.load('rvm_mobilenetv3.pth'))\n```\n\n推断循环：\n```python\nrec = [None] * 4 # 初始值设置为 None\n\nfor src in YOUR_VIDEO:  # src 可以是 [B, C, H, W] 或 [B, T, C, H, W]\n    fgr, pha, *rec = model(src, *rec, downsample_ratio=0.25)\n```\n\n* `src`: 输入帧（Source）。 \n    * 可以是 `[B, C, H, W]` 或 `[B, T, C, H, W]` 的张量。 \n    * 若是 `[B, T, C, H, W]`，可给模型一次 `T` 帧，做一小段一小段地处理，用于更好的并行计算。\n    * RGB 通道输入，范围为 `0~1`。\n\n* `fgr, pha`: 前景（Foreground）和透明度通道（Alpha）的预测。 \n    * 根据`src`，可为 `[B, C, H, W]` 或 `[B, T, C, H, W]` 的输出。\n    * `fgr` 是 RGB 三通道，`pha` 为一通道。\n    * 输出范围为 `0~1`。\n* `rec`: 循环记忆（Recurrent States）。 \n    * `List[Tensor, Tensor, Tensor, Tensor]` 类型。 \n    * 初始 `rec` 为 `List[None, None, None, None]`。\n    * 有四个记忆，因为网络使用四个 `ConvGRU` 层。\n    * 无论 `src` 的 Rank，所有记忆张量的 Rank 为 4。\n    * 若一次给予 `T` 帧，只返回处理完最后一帧后的记忆。\n\n完整的推断例子：\n\n```python\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms import ToTensor\nfrom inference_utils import VideoReader, VideoWriter\n\nreader = VideoReader('input.mp4', transform=ToTensor())\nwriter = VideoWriter('output.mp4', frame_rate=30)\n\nbgr = torch.tensor([.47, 1, .6]).view(3, 1, 1).cuda()  # 绿背景\nrec = [None] * 4                                       # 初始记忆\n\nwith torch.no_grad():\n    for src in DataLoader(reader):\n        fgr, pha, *rec = model(src.cuda(), *rec, downsample_ratio=0.25)  # 将上一帧的记忆给下一帧\n        writer.write(fgr * pha + bgr * (1 - pha))\n```\n\n或者使用提供的视频转换 API：\n\n```python\nfrom inference import convert_video\n\nconvert_video(\n    model,                           # 模型，可以加载到任何设备（cpu 或 cuda）\n    input_source='input.mp4',        # 视频文件，或图片序列文件夹\n    input_resize=(1920, 1080),       # [可选项] 缩放视频大小\n    downsample_ratio=0.25,           # [可选项] 下采样比，若 None，自动下采样至 512px\n    output_type='video',             # 可选 \"video\"（视频）或 \"png_sequence\"（PNG 序列）\n    output_composition='com.mp4',    # 若导出视频，提供文件路径。若导出 PNG 序列，提供文件夹路径\n    output_alpha=\"pha.mp4\",          # [可选项] 输出透明度预测\n    output_foreground=\"fgr.mp4\",     # [可选项] 输出前景预测\n    output_video_mbps=4,             # 若导出视频，提供视频码率\n    seq_chunk=12,                    # 设置多帧并行计算\n    num_workers=1,                   # 只适用于图片序列输入，读取线程\n    progress=True                    # 显示进度条\n)\n```\n\n也可通过命令行调用转换 API：\n\n```sh\npython inference.py \\\n    --variant mobilenetv3 \\\n    --checkpoint \"CHECKPOINT\" \\\n    --device cuda \\\n    --input-source \"input.mp4\" \\\n    --downsample-ratio 0.25 \\\n    --output-type video \\\n    --output-composition \"composition.mp4\" \\\n    --output-alpha \"alpha.mp4\" \\\n    --output-foreground \"foreground.mp4\" \\\n    --output-video-mbps 4 \\\n    --seq-chunk 12\n```\n\n<br><br><br>\n\n## TorchHub\n\n载入模型：\n\n```python\nmodel = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"mobilenetv3\") # or \"resnet50\"\n```\n\n使用转换 API，具体请参考之前对 `convert_video` 的文档。\n\n```python\nconvert_video = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"converter\")\n\nconvert_video(model, ...args...)\n```\n\n<br><br><br>\n\n## TorchScript\n\n载入模型：\n\n```python\nimport torch\nmodel = torch.jit.load('rvm_mobilenetv3.torchscript')\n```\n\n也可以可选的将模型固化（Freeze）。这会对模型进行优化，例如 BatchNorm Fusion 等。固化的模型更快。\n\n```python\nmodel = torch.jit.freeze(model)\n```\n\n然后，可以将 `model` 作为普通的 PyTorch 模型使用。但注意，若用固化模型调用转换 API，必须手动提供 `device` 和 `dtype`:\n\n```python\nconvert_video(frozen_model, ...args..., device='cuda', dtype=torch.float32)\n```\n\n<br><br><br>\n\n## ONNX\n\n模型规格:\n* 输入: [`src`, `r1i`, `r2i`, `r3i`, `r4i`, `downsample_ratio`]. \n    * `src`：输入帧，RGB 通道，形状为 `[B, C, H, W]`，范围为`0~1`。\n    * `rXi`：记忆输入，初始值是是形状为 `[1, 1, 1, 1]` 的零张量。\n    * `downsample_ratio` 下采样比，张量形状为 `[1]`。\n    * 只有 `downsample_ratio` 必须是 `FP32`，其他输入必须和加载的模型使用一样的 `dtype`。\n* 输出: [`fgr`, `pha`, `r1o`, `r2o`, `r3o`, `r4o`]\n    * `fgr, pha`：前景和透明度通道输出，范围为 `0~1`。\n    * `rXo`：记忆输出。\n\n我们只展示用 ONNX Runtime CUDA Backend 在 Python 上的使用范例。\n\n载入模型：\n\n```python\nimport onnxruntime as ort\n\nsess = ort.InferenceSession('rvm_mobilenetv3_fp16.onnx')\n```\n\n简单推断循环，但此方法不是最优化的：\n\n```python\nimport numpy as np\n\nrec = [ np.zeros([1, 1, 1, 1], dtype=np.float16) ] * 4  # 必须用模型一样的 dtype\ndownsample_ratio = np.array([0.25], dtype=np.float32)  # 必须是 FP32\n\nfor src in YOUR_VIDEO:  # src 张量是 [B, C, H, W] 形状，必须用模型一样的 dtype\n    fgr, pha, *rec = sess.run([], {\n        'src': src, \n        'r1i': rec[0], \n        'r2i': rec[1], \n        'r3i': rec[2], \n        'r4i': rec[3], \n        'downsample_ratio': downsample_ratio\n    })\n```\n\n若使用 GPU，上例会将记忆输出传回到 CPU，再在下一帧时传回到 GPU。这种传输是无意义的，因为记忆值可以留在 GPU 上。下例使用 `iobinding` 来杜绝无用的传输。\n\n```python\nimport onnxruntime as ort\nimport numpy as np\n\n# 载入模型\nsess = ort.InferenceSession('rvm_mobilenetv3_fp16.onnx')\n\n# 创建 io binding.\nio = sess.io_binding()\n\n# 在 CUDA 上创建张量\nrec = [ ort.OrtValue.ortvalue_from_numpy(np.zeros([1, 1, 1, 1], dtype=np.float16), 'cuda') ] * 4\ndownsample_ratio = ort.OrtValue.ortvalue_from_numpy(np.asarray([0.25], dtype=np.float32), 'cuda')\n\n# 设置输出项\nfor name in ['fgr', 'pha', 'r1o', 'r2o', 'r3o', 'r4o']:\n    io.bind_output(name, 'cuda')\n\n# 推断\nfor src in YOUR_VIDEO:\n    io.bind_cpu_input('src', src)\n    io.bind_ortvalue_input('r1i', rec[0])\n    io.bind_ortvalue_input('r2i', rec[1])\n    io.bind_ortvalue_input('r3i', rec[2])\n    io.bind_ortvalue_input('r4i', rec[3])\n    io.bind_ortvalue_input('downsample_ratio', downsample_ratio)\n\n    sess.run_with_iobinding(io)\n\n    fgr, pha, *rec = io.get_outputs()\n\n    # 只将 `fgr` 和 `pha` 回传到 CPU\n    fgr = fgr.numpy()\n    pha = pha.numpy()\n```\n\n注：若你使用其他推断框架，可能有些 ONNX ops 不被支持，需被替换。可以参考 [onnx](https://github.com/PeterL1n/RobustVideoMatting/tree/onnx) 分支的代码做自行导出。\n\n<br><br><br>\n\n### TensorFlow\n\n范例:\n\n```python\nimport tensorflow as tf\n\nmodel = tf.keras.models.load_model('rvm_mobilenetv3_tf')\nmodel = tf.function(model)\n\nrec = [ tf.constant(0.) ] * 4         # 初始记忆\ndownsample_ratio = tf.constant(0.25)  # 下采样率，根据视频调整\n\nfor src in YOUR_VIDEO:  # src 张量是 [B, H, W, C] 的形状，而不是 [B, C, H, W]!\n    out = model([src, *rec, downsample_ratio])\n    fgr, pha, *rec = out['fgr'], out['pha'], out['r1o'], out['r2o'], out['r3o'], out['r4o']\n```\n\n注意，在 TensorFlow 上，所有张量都是 Channal Last 的格式。\n\n我们提供 TensorFlow 的原始模型代码，请参考 [tensorflow](https://github.com/PeterL1n/RobustVideoMatting/tree/tensorflow) 分支。您可自行将 PyTorch 的权值转到 TensorFlow 模型上。\n\n\n<br><br><br>\n\n### TensorFlow.js\n\n我们在 [tfjs](https://github.com/PeterL1n/RobustVideoMatting/tree/tfjs) 分支提供范例代码。代码简单易懂，解释如何正确使用模型。\n\n<br><br><br>\n\n### CoreML\n\n我们只展示在 Python 下通过 `coremltools` 使用 CoreML 模型。在部署时，同样逻辑可用于 Swift。模型的循环记忆输入不需要在处理第一帧时提供。CoreML 内部会自动创建零张量作为初始记忆。\n\n```python\nimport coremltools as ct\n\nmodel = ct.models.model.MLModel('rvm_mobilenetv3_1920x1080_s0.25_int8.mlmodel')\n\nr1, r2, r3, r4 = None, None, None, None\n\nfor src in YOUR_VIDEO:  # src 是 PIL.Image.\n    \n    if r1 is None:\n        # 初始帧, 不用提供循环记忆\n        inputs = {'src': src}\n    else:\n        # 剩余帧，提供循环记忆\n        inputs = {'src': src, 'r1i': r1, 'r2i': r2, 'r3i': r3, 'r4i': r4}\n\n    outputs = model.predict(inputs)\n\n    fgr = outputs['fgr']  # PIL.Image\n    pha = outputs['pha']  # PIL.Image\n    \n    r1 = outputs['r1o']  # Numpy array\n    r2 = outputs['r2o']  # Numpy array\n    r3 = outputs['r3o']  # Numpy array\n    r4 = outputs['r4o']  # Numpy array\n\n```\n\n我们的 CoreML 模型只支持固定分辨率。如果你需要其他分辨率，可自行导出。导出代码见 [coreml](https://github.com/PeterL1n/RobustVideoMatting/tree/coreml) 分支。"
  },
  {
    "path": "documentation/misc/aim_test.txt",
    "content": "boy-1518482_1920.png\ngirl-1219339_1920.png\ngirl-1467820_1280.png\ngirl-beautiful-young-face-53000.png\nlong-1245787_1920.png\nmodel-600238_1920.png\npexels-photo-58463.png\nsea-sunny-person-beach.png\nwedding-dresses-1486260_1280.png\nwoman-952506_1920 (1).png\nwoman-morning-bathrobe-bathroom.png\n"
  },
  {
    "path": "documentation/misc/d646_test.txt",
    "content": "test_13.png\ntest_16.png\ntest_18.png\ntest_22.png\ntest_32.png\ntest_35.png\ntest_39.png\ntest_42.png\ntest_46.png\ntest_4.png\ntest_6.png\n"
  },
  {
    "path": "documentation/misc/dvm_background_test_clips.txt",
    "content": "0000\n0001\n0002\n0004\n0005\n0007\n0008\n0009\n0010\n0012\n0013\n0014\n0015\n0016\n0017\n0018\n0019\n0021\n0022\n0023\n0024\n0025\n0027\n0029\n0030\n0032\n0033\n0034\n0035\n0037\n0038\n0039\n0040\n0041\n0042\n0043\n0045\n0046\n0047\n0048\n0050\n0051\n0052\n0054\n0055\n0057\n0058\n0059\n0060\n0061\n0062\n0063\n0064\n0065\n0066\n0068\n0070\n0071\n0073\n0074\n0075\n0077\n0078\n0079\n0080\n0081\n0082\n0083\n0084\n0085\n0086\n0089\n0097\n0100\n0101\n0102\n0103\n0104\n0106\n0107\n0109\n0110\n0111\n0113\n0115\n0116\n0117\n0119\n0120\n0121\n0122\n0123\n0124\n0125\n0126\n0127\n0128\n0129\n0130\n0131\n0132\n0133\n0134\n0135\n0136\n0137\n0143\n0145\n0147\n0148\n0150\n0159\n0160\n0161\n0162\n0165\n0166\n0168\n0172\n0174\n0175\n0176\n0178\n0181\n0182\n0183\n0184\n0185\n0187\n0194\n0198\n0200\n0201\n0207\n0210\n0211\n0212\n0215\n0217\n0218\n0219\n0220\n0222\n0223\n0224\n0225\n0226\n0227\n0229\n0230\n0231\n0232\n0233\n0234\n0235\n0237\n0240\n0241\n0242\n0243\n0244\n0245\n"
  },
  {
    "path": "documentation/misc/dvm_background_train_clips.txt",
    "content": "0000\n0002\n0003\n0004\n0005\n0006\n0007\n0009\n0010\n0012\n0013\n0014\n0015\n0016\n0019\n0021\n0022\n0023\n0024\n0025\n0028\n0029\n0030\n0031\n0032\n0034\n0035\n0036\n0037\n0039\n0040\n0041\n0042\n0043\n0044\n0046\n0047\n0048\n0049\n0050\n0051\n0052\n0053\n0054\n0055\n0056\n0057\n0058\n0060\n0061\n0062\n0063\n0064\n0065\n0066\n0067\n0068\n0069\n0070\n0071\n0073\n0074\n0075\n0076\n0077\n0078\n0079\n0081\n0082\n0087\n0088\n0099\n0100\n0101\n0104\n0105\n0107\n0108\n0109\n0110\n0111\n0112\n0113\n0114\n0115\n0117\n0118\n0119\n0120\n0122\n0123\n0124\n0125\n0127\n0128\n0129\n0130\n0131\n0132\n0133\n0134\n0135\n0136\n0137\n0138\n0139\n0140\n0141\n0142\n0144\n0146\n0147\n0148\n0150\n0151\n0152\n0153\n0154\n0155\n0156\n0157\n0158\n0159\n0160\n0161\n0163\n0164\n0165\n0167\n0168\n0169\n0170\n0171\n0172\n0174\n0175\n0176\n0177\n0178\n0180\n0181\n0182\n0184\n0185\n0187\n0188\n0189\n0190\n0192\n0193\n0194\n0195\n0196\n0197\n0198\n0199\n0200\n0202\n0203\n0204\n0205\n0206\n0207\n0208\n0209\n0210\n0211\n0212\n0213\n0214\n0215\n0217\n0218\n0219\n0220\n0221\n0222\n0223\n0224\n0225\n0226\n0227\n0229\n0230\n0231\n0233\n0234\n0235\n0236\n0237\n0238\n0240\n0241\n0242\n0243\n0244\n0245\n0246\n0247\n0248\n0249\n0250\n0251\n0252\n0253\n0254\n0255\n0256\n0257\n0258\n0259\n0260\n0261\n0262\n0263\n0264\n0265\n0266\n0267\n0268\n0269\n0270\n0271\n0272\n0273\n0274\n0275\n0276\n0277\n0278\n0279\n0280\n0281\n0282\n0283\n0284\n0285\n0286\n0287\n0288\n0289\n0290\n0291\n0292\n0293\n0294\n0297\n0298\n0299\n0300\n0301\n0302\n0303\n0304\n0305\n0306\n0308\n0309\n0310\n0311\n0312\n0313\n0314\n0315\n0316\n0317\n0319\n0320\n0321\n0322\n0323\n0324\n0325\n0326\n0327\n0328\n0329\n0330\n0331\n0332\n0333\n0335\n0336\n0337\n0338\n0339\n0341\n0342\n0344\n0345\n0346\n0348\n0349\n0352\n0353\n0356\n0357\n0358\n0359\n0360\n0361\n0362\n0363\n0364\n0365\n0366\n0368\n0369\n0370\n0371\n0372\n0373\n0374\n0375\n0376\n0377\n0378\n0379\n0380\n0381\n0382\n0383\n0384\n0385\n0386\n0387\n0388\n0389\n0391\n0392\n0393\n0394\n0395\n0397\n0398\n0399\n0400\n0401\n0402\n0403\n0404\n0405\n0406\n0407\n0408\n0409\n0410\n0411\n0413\n0414\n0415\n0416\n0417\n0419\n0420\n0421\n0422\n0423\n0424\n0425\n0426\n0427\n0428\n0429\n0431\n0433\n0434\n0435\n0436\n0437\n0438\n0439\n0440\n0441\n0442\n0443\n0445\n0446\n0447\n0448\n0449\n0450\n0451\n0452\n0453\n0454\n0456\n0457\n0458\n0459\n0462\n0463\n0464\n0465\n0466\n0467\n0468\n0469\n0470\n0471\n0472\n0473\n0474\n0475\n0476\n0477\n0478\n0479\n0480\n0481\n0482\n0483\n0484\n0485\n0486\n0487\n0488\n0489\n0490\n0491\n0492\n0493\n0494\n0499\n0501\n0502\n0503\n0504\n0505\n0506\n0507\n0509\n0510\n0511\n0512\n0513\n0514\n0515\n0517\n0518\n0519\n0520\n0521\n0522\n0524\n0526\n0527\n0529\n0530\n0534\n0535\n0536\n0538\n0539\n0541\n0542\n0543\n0544\n0545\n0546\n0548\n0549\n0550\n0552\n0554\n0555\n0556\n0557\n0558\n0559\n0560\n0561\n0562\n0563\n0564\n0565\n0566\n0567\n0568\n0571\n0572\n0573\n0574\n0575\n0576\n0577\n0578\n0579\n0580\n0581\n0582\n0583\n0584\n0586\n0587\n0589\n0590\n0591\n0592\n0594\n0595\n0596\n0597\n0598\n0600\n0601\n0602\n0603\n0604\n0605\n0606\n0608\n0609\n0610\n0611\n0612\n0613\n0614\n0615\n0616\n0617\n0618\n0619\n0620\n0624\n0625\n0626\n0627\n0628\n0629\n0630\n0631\n0634\n0635\n0636\n0637\n0638\n0639\n0640\n0641\n0642\n0643\n0644\n0645\n0646\n0647\n0648\n0650\n0651\n0652\n0654\n0655\n0656\n0658\n0659\n0660\n0661\n0662\n0663\n0664\n0665\n0666\n0667\n0669\n0670\n0671\n0672\n0673\n0674\n0675\n0676\n0677\n0678\n0679\n0680\n0681\n0682\n0683\n0684\n0685\n0686\n0687\n0689\n0690\n0691\n0692\n0693\n0694\n0695\n0696\n0697\n0698\n0699\n0700\n0701\n0702\n0703\n0704\n0705\n0706\n0707\n0708\n0709\n0710\n0711\n0712\n0713\n0714\n0715\n0716\n0717\n0718\n0719\n0720\n0721\n0723\n0724\n0725\n0726\n0727\n0729\n0730\n0731\n0732\n0733\n0734\n0735\n0736\n0738\n0740\n0741\n0742\n0743\n0744\n0746\n0747\n0748\n0749\n0750\n0752\n0753\n0754\n0755\n0756\n0757\n0758\n0759\n0760\n0762\n0763\n0764\n0765\n0766\n0767\n0768\n0770\n0771\n0772\n0773\n0774\n0775\n0776\n0777\n0778\n0779\n0780\n0781\n0782\n0783\n0784\n0786\n0787\n0788\n0789\n0790\n0791\n0792\n0793\n0794\n0795\n0796\n0797\n0798\n0800\n0801\n0804\n0806\n0808\n0809\n0811\n0812\n0813\n0814\n0815\n0816\n0817\n0819\n0823\n0824\n0825\n0827\n0828\n0829\n0830\n0831\n0832\n0833\n0834\n0835\n0836\n0837\n0840\n0841\n0842\n0847\n0848\n0850\n0851\n0852\n0853\n0854\n0855\n0856\n0857\n0858\n0859\n0860\n0861\n0862\n0864\n0867\n0868\n0869\n0870\n0871\n0872\n0873\n0874\n0876\n0877\n0878\n0879\n0880\n0881\n0882\n0883\n0885\n0886\n0887\n0889\n0890\n0891\n0892\n0893\n0894\n0895\n0896\n0899\n0900\n0901\n0902\n0903\n0904\n0905\n0906\n0907\n0908\n0909\n0910\n0911\n0912\n0913\n0914\n0915\n0916\n0917\n0918\n0919\n0921\n0922\n0923\n0924\n0925\n0926\n0927\n0929\n0930\n0931\n0932\n0933\n0934\n0935\n0936\n0937\n0939\n0940\n0941\n0942\n0945\n0946\n0947\n0948\n0949\n0950\n0951\n0952\n0953\n0954\n0955\n0956\n0957\n0958\n0960\n0962\n0963\n0964\n0965\n0966\n0967\n0968\n0969\n0970\n0971\n0973\n0974\n0976\n0977\n0978\n0979\n0980\n0981\n0982\n0983\n0984\n0985\n0986\n0987\n0988\n0989\n0990\n0991\n0992\n0993\n0994\n0995\n0996\n0997\n0998\n0999\n1000\n1001\n1002\n1003\n1005\n1006\n1008\n1009\n1010\n1011\n1012\n1013\n1014\n1016\n1017\n1018\n1019\n1020\n1021\n1022\n1023\n1024\n1025\n1026\n1028\n1029\n1030\n1032\n1035\n1036\n1037\n1038\n1039\n1040\n1041\n1042\n1043\n1044\n1045\n1046\n1047\n1048\n1049\n1050\n1052\n1053\n1054\n1055\n1056\n1057\n1058\n1061\n1062\n1063\n1064\n1065\n1066\n1067\n1068\n1069\n1072\n1075\n1076\n1077\n1078\n1079\n1081\n1082\n1083\n1084\n1087\n1088\n1089\n1090\n1096\n1097\n1098\n1099\n1101\n1102\n1103\n1104\n1105\n1106\n1107\n1108\n1109\n1110\n1111\n1112\n1113\n1115\n1116\n1117\n1118\n1119\n1120\n1121\n1122\n1123\n1124\n1128\n1129\n1130\n1131\n1132\n1134\n1137\n1138\n1139\n1140\n1141\n1142\n1143\n1144\n1145\n1146\n1147\n1148\n1149\n1150\n1151\n1152\n1153\n1154\n1155\n1156\n1157\n1158\n1159\n1160\n1161\n1162\n1163\n1165\n1168\n1169\n1170\n1171\n1172\n1173\n1174\n1175\n1176\n1177\n1178\n1179\n1180\n1181\n1182\n1183\n1184\n1185\n1186\n1187\n1188\n1189\n1190\n1191\n1192\n1193\n1194\n1195\n1196\n1197\n1199\n1200\n1201\n1202\n1203\n1204\n1206\n1207\n1208\n1211\n1212\n1213\n1215\n1216\n1217\n1219\n1220\n1221\n1222\n1223\n1224\n1225\n1226\n1227\n1228\n1229\n1230\n1231\n1232\n1233\n1234\n1235\n1237\n1238\n1239\n1240\n1241\n1242\n1245\n1246\n1248\n1249\n1252\n1253\n1255\n1256\n1257\n1258\n1259\n1260\n1261\n1262\n1263\n1264\n1265\n1266\n1267\n1268\n1269\n1270\n1271\n1272\n1273\n1274\n1275\n1277\n1278\n1279\n1280\n1281\n1282\n1283\n1284\n1287\n1288\n1289\n1290\n1291\n1293\n1294\n1295\n1296\n1297\n1299\n1300\n1301\n1302\n1303\n1304\n1305\n1306\n1307\n1308\n1309\n1310\n1311\n1312\n1313\n1316\n1317\n1318\n1319\n1320\n1321\n1322\n1323\n1324\n1325\n1326\n1327\n1328\n1329\n1331\n1332\n1333\n1334\n1335\n1336\n1337\n1338\n1339\n1340\n1341\n1342\n1343\n1344\n1345\n1346\n1347\n1348\n1350\n1351\n1352\n1353\n1354\n1355\n1356\n1357\n1359\n1360\n1361\n1362\n1363\n1364\n1365\n1366\n1367\n1368\n1369\n1370\n1371\n1372\n1373\n1374\n1375\n1376\n1378\n1379\n1380\n1381\n1382\n1383\n1385\n1386\n1387\n1389\n1390\n1391\n1392\n1393\n1394\n1395\n1396\n1397\n1398\n1399\n1400\n1402\n1403\n1405\n1406\n1409\n1410\n1411\n1412\n1413\n1414\n1415\n1416\n1417\n1418\n1420\n1421\n1422\n1423\n1424\n1425\n1426\n1427\n1428\n1429\n1430\n1431\n1432\n1433\n1434\n1435\n1436\n1437\n1438\n1439\n1441\n1442\n1443\n1444\n1445\n1446\n1447\n1448\n1449\n1450\n1451\n1452\n1453\n1454\n1455\n1456\n1457\n1458\n1459\n1460\n1461\n1462\n1465\n1466\n1467\n1468\n1469\n1470\n1471\n1472\n1473\n1474\n1475\n1476\n1477\n1478\n1479\n1480\n1481\n1482\n1483\n1484\n1485\n1486\n1487\n1488\n1489\n1490\n1491\n1493\n1494\n1495\n1496\n1497\n1499\n1500\n1501\n1502\n1503\n1504\n1505\n1506\n1507\n1508\n1509\n1510\n1511\n1512\n1513\n1514\n1515\n1516\n1519\n1520\n1521\n1522\n1523\n1524\n1525\n1526\n1527\n1528\n1529\n1530\n1531\n1532\n1534\n1535\n1536\n1537\n1538\n1539\n1540\n1541\n1542\n1543\n1544\n1545\n1546\n1547\n1548\n1549\n1550\n1551\n1552\n1553\n1554\n1555\n1556\n1557\n1558\n1560\n1561\n1562\n1563\n1565\n1566\n1567\n1568\n1569\n1570\n1571\n1572\n1573\n1574\n1575\n1576\n1577\n1578\n1579\n1580\n1581\n1582\n1583\n1584\n1585\n1586\n1587\n1588\n1589\n1590\n1591\n1592\n1593\n1594\n1595\n1596\n1597\n1598\n1599\n1600\n1601\n1602\n1603\n1604\n1605\n1606\n1608\n1609\n1611\n1612\n1613\n1614\n1615\n1616\n1617\n1618\n1619\n1620\n1621\n1622\n1623\n1624\n1625\n1626\n1627\n1628\n1629\n1630\n1631\n1632\n1633\n1634\n1635\n1636\n1637\n1638\n1639\n1640\n1641\n1642\n1643\n1644\n1645\n1646\n1649\n1650\n1651\n1652\n1653\n1654\n1655\n1656\n1657\n1658\n1659\n1660\n1661\n1662\n1663\n1664\n1665\n1666\n1667\n1668\n1669\n1670\n1671\n1672\n1673\n1675\n1676\n1677\n1678\n1679\n1680\n1681\n1682\n1683\n1684\n1685\n1686\n1687\n1688\n1689\n1690\n1691\n1692\n1693\n1694\n1695\n1696\n1697\n1698\n1699\n1700\n1701\n1702\n1703\n1704\n1705\n1706\n1707\n1708\n1709\n1710\n1712\n1713\n1714\n1715\n1716\n1717\n1718\n1719\n1720\n1721\n1722\n1723\n1724\n1725\n1726\n1727\n1728\n1729\n1730\n1731\n1732\n1733\n1734\n1735\n1736\n1737\n1738\n1739\n1740\n1741\n1742\n1743\n1744\n1745\n1746\n1747\n1748\n1749\n1750\n1751\n1752\n1753\n1754\n1755\n1756\n1757\n1758\n1759\n1760\n1761\n1762\n1763\n1764\n1765\n1766\n1767\n1768\n1769\n1770\n1771\n1772\n1773\n1774\n1775\n1776\n1778\n1779\n1780\n1781\n1782\n1784\n1785\n1786\n1787\n1788\n1789\n1790\n1791\n1792\n1793\n1794\n1795\n1796\n1797\n1798\n1799\n1800\n1804\n1806\n1807\n1808\n1809\n1811\n1812\n1813\n1814\n1815\n1816\n1817\n1818\n1819\n1820\n1821\n1822\n1823\n1825\n1826\n1827\n1828\n1829\n1831\n1833\n1834\n1835\n1836\n1837\n1838\n1839\n1840\n1842\n1843\n1844\n1845\n1846\n1847\n1848\n1849\n1850\n1851\n1852\n1853\n1854\n1855\n1856\n1857\n1858\n1859\n1861\n1862\n1863\n1864\n1865\n1866\n1867\n1868\n1869\n1870\n1871\n1872\n1873\n1874\n1875\n1876\n1877\n1879\n1880\n1881\n1882\n1886\n1887\n1889\n1891\n1892\n1893\n1894\n1896\n1897\n1898\n1899\n1900\n1901\n1902\n1903\n1904\n1905\n1906\n1907\n1908\n1909\n1910\n1911\n1912\n1913\n1914\n1915\n1916\n1917\n1918\n1919\n1920\n1921\n1922\n1923\n1924\n1925\n1926\n1927\n1928\n1929\n1930\n1931\n1932\n1933\n1934\n1935\n1936\n1937\n1938\n1939\n1940\n1941\n1942\n1943\n1944\n1945\n1946\n1947\n1948\n1949\n1950\n1952\n1953\n1954\n1955\n1956\n1958\n1959\n1960\n1961\n1962\n1963\n1964\n1965\n1966\n1967\n1968\n1969\n1970\n1971\n1972\n1973\n1974\n1975\n1976\n1977\n1978\n1980\n1981\n1982\n1983\n1984\n1985\n1986\n1988\n1989\n1990\n1991\n1992\n1993\n1994\n1995\n1997\n1998\n1999\n2000\n2002\n2003\n2004\n2005\n2007\n2008\n2010\n2011\n2012\n2013\n2014\n2015\n2016\n2017\n2018\n2019\n2020\n2021\n2022\n2024\n2025\n2026\n2027\n2028\n2029\n2030\n2031\n2032\n2035\n2036\n2037\n2038\n2039\n2040\n2041\n2042\n2043\n2045\n2046\n2047\n2049\n2050\n2052\n2053\n2054\n2056\n2057\n2059\n2060\n2061\n2064\n2066\n2068\n2069\n2070\n2071\n2072\n2073\n2074\n2075\n2077\n2078\n2079\n2080\n2081\n2082\n2083\n2084\n2085\n2086\n2087\n2088\n2089\n2090\n2091\n2092\n2093\n2094\n2096\n2097\n2098\n2099\n2100\n2101\n2102\n2103\n2104\n2105\n2107\n2108\n2109\n2111\n2112\n2113\n2114\n2115\n2116\n2117\n2119\n2120\n2121\n2122\n2123\n2124\n2125\n2126\n2127\n2128\n2129\n2130\n2131\n2132\n2133\n2134\n2135\n2136\n2137\n2138\n2139\n2140\n2141\n2143\n2144\n2145\n2146\n2147\n2148\n2149\n2152\n2153\n2155\n2158\n2159\n2160\n2161\n2162\n2163\n2164\n2165\n2166\n2167\n2168\n2169\n2170\n2171\n2174\n2176\n2177\n2178\n2179\n2180\n2181\n2182\n2183\n2184\n2186\n2187\n2188\n2189\n2190\n2191\n2192\n2193\n2195\n2197\n2198\n2199\n2200\n2201\n2202\n2203\n2204\n2205\n2206\n2207\n2208\n2209\n2210\n2211\n2212\n2213\n2214\n2215\n2216\n2217\n2218\n2219\n2220\n2221\n2222\n2223\n2225\n2226\n2227\n2228\n2229\n2230\n2231\n2232\n2233\n2234\n2235\n2236\n2238\n2239\n2240\n2241\n2242\n2243\n2244\n2245\n2246\n2247\n2248\n2249\n2250\n2251\n2252\n2253\n2255\n2256\n2257\n2258\n2259\n2260\n2261\n2263\n2264\n2265\n2267\n2268\n2269\n2270\n2271\n2272\n2273\n2274\n2275\n2276\n2277\n2278\n2279\n2280\n2281\n2282\n2283\n2284\n2285\n2286\n2287\n2288\n2290\n2291\n2292\n2293\n2294\n2295\n2297\n2299\n2300\n2301\n2302\n2303\n2304\n2305\n2311\n2312\n2313\n2314\n2315\n2316\n2317\n2318\n2319\n2320\n2322\n2324\n2325\n2326\n2329\n2331\n2332\n2334\n2335\n2336\n2337\n2338\n2339\n2340\n2341\n2342\n2343\n2344\n2345\n2347\n2349\n2350\n2351\n2352\n2353\n2355\n2356\n2358\n2359\n2360\n2361\n2362\n2363\n2364\n2365\n2367\n2368\n2369\n2370\n2372\n2373\n2374\n2375\n2376\n2377\n2378\n2379\n2380\n2381\n2382\n2383\n2384\n2386\n2389\n2390\n2391\n2392\n2393\n2394\n2395\n2396\n2397\n2398\n2399\n2400\n2401\n2402\n2403\n2404\n2406\n2407\n2408\n2409\n2410\n2411\n2412\n2413\n2414\n2416\n2417\n2418\n2419\n2420\n2421\n2422\n2423\n2424\n2425\n2426\n2427\n2428\n2429\n2431\n2432\n2433\n2434\n2437\n2439\n2440\n2441\n2442\n2443\n2444\n2445\n2446\n2448\n2449\n2450\n2451\n2452\n2453\n2454\n2455\n2456\n2457\n2460\n2461\n2462\n2463\n2464\n2465\n2466\n2467\n2468\n2469\n2470\n2472\n2474\n2475\n2479\n2480\n2481\n2482\n2483\n2484\n2485\n2486\n2487\n2488\n2489\n2490\n2491\n2492\n2493\n2494\n2495\n2496\n2497\n2499\n2500\n2501\n2502\n2503\n2504\n2505\n2506\n2507\n2508\n2509\n2510\n2511\n2512\n2513\n2514\n2515\n2516\n2517\n2518\n2519\n2520\n2521\n2522\n2523\n2524\n2525\n2530\n2534\n2536\n2537\n2539\n2540\n2541\n2542\n2543\n2544\n2545\n2546\n2548\n2549\n2550\n2551\n2553\n2554\n2555\n2556\n2559\n2560\n2562\n2567\n2570\n2573\n2575\n2576\n2578\n2579\n2582\n2585\n2588\n2590\n2593\n2594\n2595\n2596\n2597\n2598\n2600\n2601\n2602\n2603\n2604\n2605\n2606\n2607\n2612\n2613\n2615\n2616\n2617\n2618\n2619\n2620\n2622\n2623\n2624\n2625\n2629\n2630\n2633\n2634\n2635\n2637\n2638\n2639\n2641\n2643\n2644\n2646\n2648\n2649\n2650\n2652\n2654\n2656\n2659\n2661\n2662\n2663\n2664\n2665\n2667\n2669\n2670\n2671\n2672\n2674\n2675\n2677\n2679\n2680\n2682\n2684\n2685\n2687\n2689\n2691\n2692\n2693\n2694\n2695\n2696\n2697\n2698\n2699\n2700\n2701\n2702\n2703\n2705\n2706\n2707\n2710\n2713\n2714\n2715\n2717\n2718\n2720\n2721\n2722\n2726\n2727\n2729\n2733\n2734\n2737\n2739\n2740\n2741\n2742\n2743\n2745\n2747\n2748\n2749\n2755\n2756\n2757\n2758\n2759\n2761\n2762\n2763\n2765\n2767\n2768\n2769\n2770\n2773\n2775\n2776\n2780\n2781\n2782\n2785\n2787\n2790\n2791\n2793\n2794\n2795\n2796\n2797\n2798\n2800\n2801\n2802\n2803\n2806\n2808\n2810\n2812\n2813\n2814\n2815\n2816\n2818\n2819\n2820\n2821\n2822\n2823\n2825\n2827\n2828\n2829\n2830\n2831\n2832\n2833\n2834\n2835\n2837\n2838\n2842\n2843\n2844\n2845\n2847\n2848\n2849\n2850\n2851\n2852\n2853\n2854\n2856\n2857\n2858\n2860\n2861\n2862\n2863\n2864\n2865\n2866\n2868\n2869\n2871\n2874\n2875\n2877\n2879\n2881\n2882\n2884\n2885\n2887\n2888\n2889\n2890\n2891\n2893\n2894\n2895\n2896\n2900\n2902\n2903\n2904\n2905\n2906\n2907\n2908\n2911\n2912\n2914\n2915\n2916\n2917\n2918\n2919\n2921\n2923\n2924\n2925\n2926\n2928\n2929\n2930\n2931\n2932\n2933\n2934\n2935\n2936\n2938\n2939\n2940\n2941\n2944\n2945\n2946\n2947\n2952\n2954\n2957\n2958\n2960\n2962\n2963\n2966\n2967\n2968\n2969\n2970\n2971\n2972\n2973\n2974\n2975\n2976\n2981\n2982\n2984\n2985\n2986\n2988\n2993\n2994\n2996\n2998\n2999\n3000\n3001\n3002\n3004\n3006\n3007\n3008\n3010\n3015\n3016\n3017\n3018\n3019\n3020\n3021\n3022\n3024\n3026\n3027\n3029\n3033\n3034\n3035\n3036\n3037\n3040\n3041\n3042\n3043\n3044\n3045\n3046\n3047\n3048\n3049\n3050\n3051\n3053\n3056\n3057\n3058\n3059\n3060\n3061\n3063\n3065\n3066\n3068\n3069\n3070\n3074\n3077\n3078\n3079\n3080\n3081\n3082\n3083\n3084\n3085\n3086\n3087\n3094\n3095\n3097\n3098\n3100\n3101\n3102\n3103\n3105\n3106\n3108\n3109\n3110\n3111\n3112\n3113\n3114\n3115\n3116\n3117\n3118\n3119\n3121\n3123\n3124\n3125\n3127\n3128\n3130\n3131\n3133\n3134\n3136\n3137\n3140\n3142\n3143\n3144\n3145\n3147\n3148\n3152\n3153\n3155\n3156\n3157\n3159\n3160\n3162\n3164\n3165\n3166\n3168\n3170\n3171\n3173\n3176\n3178\n3179\n3180\n3181\n3184\n3187\n3188\n3190\n3191\n3194\n3197\n3199\n3200\n3201\n3202\n3204\n3209\n3210\n3211\n3212\n3214\n3215\n3217\n3218\n3219\n3221\n3222\n3223\n3224\n3226\n3228\n3229\n3230\n3232\n3237\n3238\n3239\n3240\n3241\n3242\n3243\n3245\n3247\n3248\n3250\n3251\n3252\n3253\n3254\n3257\n3258\n3259\n3260\n3262\n3264\n3266\n3267\n3269\n3270\n3275\n3278\n3279\n3280\n3282\n3284\n3285\n3286\n3287\n3288\n3289\n3292\n3293\n3295\n3296\n3298\n3299\n3300\n3301\n3302\n3303\n3304\n3309\n3311\n3312\n3315\n3316\n3317\n3318\n3319\n3322\n3325\n3328\n3332\n3334\n3339\n3340\n3342\n3346\n3348\n3349\n3350\n3351\n3352\n3354\n3355\n3357\n3358\n3361\n3363\n3364\n3365\n3366\n3367\n3368\n3369\n3370\n3373\n3374\n3377\n3378\n3380\n3381\n3382\n3383\n3384\n3385\n3386\n3391\n3393\n3395\n3396\n3397\n3398\n3399\n3400\n3401\n3402\n3403\n3404\n3405\n3407\n3408\n3409\n3410\n3411\n3415\n3416\n3418\n3420\n3422\n3423\n3424\n3427\n3428\n3431\n3433\n3435\n3437\n3438\n3439\n3440\n3441\n3442\n3443\n3444\n3446\n3449\n3450\n3451\n3452\n3453\n3454\n3455\n3456\n3457\n3460\n3462\n3463\n3464\n3465\n3466\n3467\n3468\n3470\n3475\n3476\n3477\n3483\n3484\n3486\n3487\n3489\n3492\n3496\n3497\n3498\n3500\n3501\n3502\n3505\n3507\n3508\n3509\n3510\n3511\n3512\n3513\n3514\n3515\n3517\n3518\n3519\n3521\n3524\n3525\n3526\n3528\n3529\n3532\n3536\n3541\n3542\n3543\n3544\n3545\n3546\n3549\n3550\n3551\n3552\n3554\n3556\n3557\n3558\n3559\n3560\n3562\n3563\n3564\n3566\n3567\n3568\n3571\n3572\n3573\n3574\n3575\n3576\n3578\n3579\n3580\n3582\n3584\n3585\n3588\n3590\n3592\n3593\n3594\n3599\n3602\n3605\n3606\n3608\n3611\n3612\n3615\n3617\n3620\n3621\n3622\n3623\n3624\n3625\n3626\n3629\n3630\n3632\n3633\n3636\n3637\n3638\n3641\n3644\n3646\n3647\n3648\n3649\n3654\n3655\n3656\n3657\n3660\n3662\n3667\n3671\n3672\n3673\n3674\n3675\n3676\n3678\n3679\n3680\n3681\n3682\n3683\n3685\n3687\n3691\n3692\n3694\n3695\n3697\n3698\n3699\n3700\n3701\n3703\n3704\n3705\n3707\n3709\n3711\n3712\n3715\n3717\n3718\n3719\n3720\n3721\n3723\n3724\n3725\n3726\n3728\n3729\n3733\n3734\n3735\n3737\n3738\n3739\n3741\n3743\n3746\n3748\n3750\n3753\n3754\n3756\n3757\n3759\n3760\n3762\n3764\n3765\n3766\n3768\n3772\n3773\n3774\n3776\n3777\n3779\n3780\n3782\n3783\n3784\n3785\n3786\n3790\n3792\n3793\n3794\n3798\n3799\n3800\n3801\n3802\n3803\n3804\n3807\n3809\n3813\n3814\n3816\n3819\n3822\n3823\n3824\n3826\n3827\n3828\n3829\n3830\n3831\n3832\n3833\n3834\n3836\n3837\n3838\n3839\n3840\n3841\n3842\n3844\n3845\n3847\n3848\n3849\n3850\n3852\n3854\n3855\n3856\n3857\n3858\n3861\n3862\n3863\n3865\n3869\n3872\n3873\n3874\n3879\n3880\n3883\n3885\n3886\n3887\n3888\n3889\n3890\n3891\n3893\n3894\n3895\n3897\n3898\n3899\n3900\n3901\n3903\n3904\n3906\n3914\n3915\n3916\n3920\n3923\n3924\n3925\n3926\n3928\n3929\n3931\n3932\n3934\n3935\n3937\n3939\n3942\n3943\n3945\n3949\n3950\n3952\n3955\n3956\n3963\n3965\n3966\n3967\n3969\n3970\n3971\n3974\n3976\n3977\n3978\n3980\n3981\n3982\n3983\n3984\n3987\n3988\n3992\n3995\n3996\n3997\n3999\n"
  },
  {
    "path": "documentation/misc/imagematte_train.txt",
    "content": "10743257206_18e7f44f2e_b.jpg\n10845279884_d2d4c7b4d1_b.jpg\n1-1252426161dfXY.jpg\n1-1255621189mTnS.jpg\n1-1259162624NMFK.jpg\n1-1259245823Un3j.jpg\n11363165393_05d7a21d76_b.jpg\n131686738165901828.jpg\n13564741125_753939e9ce_o.jpg\n14731860273_5b40b19b51_o.jpg\n16087-a-young-woman-showing-a-bitten-green-apple-pv.jpg\n1609484818_b9bb12b.jpg\n17620-a-beautiful-woman-in-a-bikini-pv.jpg\n20672673163_20c8467827_b.jpg\n3262986095_2d5afe583c_b.jpg\n3588101233_f91aa5e3a3.jpg\n3858897226_cae5b75963_o.jpg\n4889657410_2d503ca287_o.jpg\n4981835627_c4e6c4ffa8_o.jpg\n5025666458_576b974455_o.jpg\n5149410930_3a943dc43f_b.jpg\n539641011387760661.jpg\n5892503248_4b882863c7_o.jpg\n604673748289192179.jpg\n606189768665464996.jpg\n624753897218113578.jpg\n657454154710122500.jpg\n664308724952072193.jpg\n7669262460_e4be408343_b.jpg\n8244818049_dfa59a3eb8_b.jpg\n8688417335_01f3bafbe5_o.jpg\n9434599749_e7ccfc7812_b.jpg\nAaron_Friedman_Headshot.jpg\narrgh___r___28_by_mjranum_stock.jpg\narrgh___r___29_by_mjranum_stock.jpg\narrgh___r___30_by_mjranum_stock.jpg\na-single-person-1084191_960_720.jpg\nballerina-855652_1920.jpg\nbeautiful-19075_960_720.jpg\nboy-454633_1920.jpg\nbride-2819673_1920.jpg\nbride-442894_1920.jpg\nface-1223346_960_720.jpg\nfashion-model-portrait.jpg\nfashion-model-pose.jpg\ngirl-1535859_1920.jpg\nGirl_in_front_of_a_green_background.jpg\ngoth_by_bugidifino-d4w7zms.jpg\nh_0.jpg\nh_100.jpg\nh_101.jpg\nh_102.jpg\nh_103.jpg\nh_104.jpg\nh_105.jpg\nh_106.jpg\nh_107.jpg\nh_108.jpg\nh_109.jpg\nh_10.jpg\nh_111.jpg\nh_112.jpg\nh_113.jpg\nh_114.jpg\nh_115.jpg\nh_116.jpg\nh_117.jpg\nh_118.jpg\nh_119.jpg\nh_11.jpg\nh_120.jpg\nh_121.jpg\nh_122.jpg\nh_123.jpg\nh_124.jpg\nh_125.jpg\nh_126.jpg\nh_127.jpg\nh_128.jpg\nh_129.jpg\nh_12.jpg\nh_130.jpg\nh_131.jpg\nh_132.jpg\nh_133.jpg\nh_134.jpg\nh_135.jpg\nh_136.jpg\nh_137.jpg\nh_138.jpg\nh_139.jpg\nh_13.jpg\nh_140.jpg\nh_141.jpg\nh_142.jpg\nh_143.jpg\nh_144.jpg\nh_145.jpg\nh_146.jpg\nh_147.jpg\nh_148.jpg\nh_149.jpg\nh_14.jpg\nh_151.jpg\nh_152.jpg\nh_153.jpg\nh_154.jpg\nh_155.jpg\nh_156.jpg\nh_157.jpg\nh_158.jpg\nh_159.jpg\nh_15.jpg\nh_160.jpg\nh_161.jpg\nh_162.jpg\nh_163.jpg\nh_164.jpg\nh_165.jpg\nh_166.jpg\nh_167.jpg\nh_168.jpg\nh_169.jpg\nh_170.jpg\nh_171.jpg\nh_172.jpg\nh_173.jpg\nh_174.jpg\nh_175.jpg\nh_176.jpg\nh_177.jpg\nh_178.jpg\nh_179.jpg\nh_17.jpg\nh_180.jpg\nh_181.jpg\nh_182.jpg\nh_183.jpg\nh_184.jpg\nh_185.jpg\nh_186.jpg\nh_187.jpg\nh_188.jpg\nh_189.jpg\nh_18.jpg\nh_190.jpg\nh_191.jpg\nh_192.jpg\nh_193.jpg\nh_194.jpg\nh_195.jpg\nh_196.jpg\nh_197.jpg\nh_198.jpg\nh_199.jpg\nh_19.jpg\nh_1.jpg\nh_200.jpg\nh_201.jpg\nh_202.jpg\nh_204.jpg\nh_205.jpg\nh_206.jpg\nh_207.jpg\nh_208.jpg\nh_209.jpg\nh_20.jpg\nh_210.jpg\nh_211.jpg\nh_212.jpg\nh_213.jpg\nh_214.jpg\nh_215.jpg\nh_216.jpg\nh_217.jpg\nh_218.jpg\nh_219.jpg\nh_21.jpg\nh_220.jpg\nh_221.jpg\nh_222.jpg\nh_223.jpg\nh_224.jpg\nh_225.jpg\nh_226.jpg\nh_227.jpg\nh_228.jpg\nh_229.jpg\nh_22.jpg\nh_230.jpg\nh_231.jpg\nh_232.jpg\nh_233.jpg\nh_234.jpg\nh_235.jpg\nh_236.jpg\nh_237.jpg\nh_238.jpg\nh_239.jpg\nh_23.jpg\nh_240.jpg\nh_241.jpg\nh_242.jpg\nh_243.jpg\nh_244.jpg\nh_245.jpg\nh_247.jpg\nh_248.jpg\nh_249.jpg\nh_24.jpg\nh_250.jpg\nh_251.jpg\nh_252.jpg\nh_253.jpg\nh_254.jpg\nh_255.jpg\nh_256.jpg\nh_257.jpg\nh_258.jpg\nh_259.jpg\nh_25.jpg\nh_260.jpg\nh_261.jpg\nh_262.jpg\nh_263.jpg\nh_264.jpg\nh_265.jpg\nh_266.jpg\nh_268.jpg\nh_269.jpg\nh_26.jpg\nh_270.jpg\nh_271.jpg\nh_272.jpg\nh_273.jpg\nh_274.jpg\nh_276.jpg\nh_277.jpg\nh_278.jpg\nh_279.jpg\nh_27.jpg\nh_280.jpg\nh_281.jpg\nh_282.jpg\nh_283.jpg\nh_284.jpg\nh_285.jpg\nh_286.jpg\nh_287.jpg\nh_288.jpg\nh_289.jpg\nh_28.jpg\nh_290.jpg\nh_291.jpg\nh_292.jpg\nh_293.jpg\nh_294.jpg\nh_295.jpg\nh_296.jpg\nh_297.jpg\nh_298.jpg\nh_299.jpg\nh_29.jpg\nh_300.jpg\nh_301.jpg\nh_302.jpg\nh_303.jpg\nh_304.jpg\nh_305.jpg\nh_307.jpg\nh_308.jpg\nh_309.jpg\nh_30.jpg\nh_310.jpg\nh_311.jpg\nh_312.jpg\nh_313.jpg\nh_314.jpg\nh_315.jpg\nh_316.jpg\nh_317.jpg\nh_318.jpg\nh_319.jpg\nh_31.jpg\nh_320.jpg\nh_321.jpg\nh_322.jpg\nh_323.jpg\nh_324.jpg\nh_325.jpg\nh_326.jpg\nh_327.jpg\nh_329.jpg\nh_32.jpg\nh_33.jpg\nh_34.jpg\nh_35.jpg\nh_36.jpg\nh_37.jpg\nh_38.jpg\nh_39.jpg\nh_3.jpg\nh_40.jpg\nh_41.jpg\nh_42.jpg\nh_43.jpg\nh_44.jpg\nh_45.jpg\nh_46.jpg\nh_47.jpg\nh_48.jpg\nh_49.jpg\nh_4.jpg\nh_50.jpg\nh_51.jpg\nh_52.jpg\nh_53.jpg\nh_54.jpg\nh_55.jpg\nh_56.jpg\nh_57.jpg\nh_58.jpg\nh_59.jpg\nh_5.jpg\nh_60.jpg\nh_61.jpg\nh_62.jpg\nh_63.jpg\nh_65.jpg\nh_67.jpg\nh_68.jpg\nh_69.jpg\nh_6.jpg\nh_70.jpg\nh_71.jpg\nh_72.jpg\nh_73.jpg\nh_74.jpg\nh_75.jpg\nh_76.jpg\nh_77.jpg\nh_78.jpg\nh_79.jpg\nh_7.jpg\nh_80.jpg\nh_81.jpg\nh_82.jpg\nh_83.jpg\nh_84.jpg\nh_85.jpg\nh_86.jpg\nh_87.jpg\nh_88.jpg\nh_89.jpg\nh_8.jpg\nh_90.jpg\nh_91.jpg\nh_92.jpg\nh_93.jpg\nh_94.jpg\nh_95.jpg\nh_96.jpg\nh_97.jpg\nh_98.jpg\nh_99.jpg\nh_9.jpg\nhair-flying-142210_1920.jpg\nheadshotid_by_bokogreat_stock-d355xf3.jpg\nlil_white_goth_grl___23_by_mjranum_stock.jpg\nlil_white_goth_grl___26_by_mjranum_stock.jpg\nman-388104_960_720.jpg\nman_headshot.jpg\nMFettes-headshot.jpg\nmodel-429733_960_720.jpg\nmodel-610352_960_720.jpg\nmodel-858753_960_720.jpg\nmodel-858755_960_720.jpg\nmodel-873675_960_720.jpg\nmodel-873678_960_720.jpg\nmodel-873690_960_720.jpg\nmodel-881425_960_720.jpg\nmodel-881431_960_720.jpg\nmodel-female-girl-beautiful-51969.jpg\nModel_in_green_dress_3.jpg\nModern_shingle_bob_haircut.jpg\nMotivate_(Fitness_model).jpg\nOfficial_portrait_of_Barack_Obama.jpg\nperson-woman-eyes-face.jpg\npink-hair-855660_960_720.jpg\nportrait-750774_1920.jpg\nProfessor_Steven_Chu_ForMemRS_headshot.jpg\nsailor_flying_4_by_senshistock-d4k2wmr.jpg\nskin-care-937667_960_720.jpg\nsorcery___8_by_mjranum_stock.jpg\nt_62.jpg\nt_65.jpg\ntest_32.jpg\ntest_8.jpg\ntrain_245.jpg\ntrain_246.jpg\ntrain_255.jpg\ntrain_304.jpg\ntrain_333.jpg\ntrain_361.jpg\ntrain_395.jpg\ntrain_480.jpg\ntrain_488.jpg\ntrain_539.jpg\nwedding-846926_1920.jpg\nWild_hair.jpg\nwith_wings___pose_reference_by_senshistock-d6by42n_2.jpg\nwith_wings___pose_reference_by_senshistock-d6by42n.jpg\nwoman-1138435_960_720.jpg\nwoman1.jpg\nwoman2.jpg\nwoman-659354_960_720.jpg\nwoman-804072_960_720.jpg\nwoman-868519_960_720.jpg\nWoman_in_white_shirt_on_August_2009_02.jpg\nwomen-878869_1920.jpg\n"
  },
  {
    "path": "documentation/misc/imagematte_valid.txt",
    "content": "13564741125_753939e9ce_o.jpg\n3858897226_cae5b75963_o.jpg\n538724499685900405.jpg\nballerina-855652_1920.jpg\nboy-454633_1920.jpg\nh_110.jpg\nh_150.jpg\nh_16.jpg\nh_246.jpg\nh_267.jpg\nh_275.jpg\nh_306.jpg\nh_328.jpg\nmodel-610352_960_720.jpg\nt_66.jpg\n"
  },
  {
    "path": "documentation/misc/spd_preprocess.py",
    "content": "# pip install supervisely\nimport supervisely_lib as sly\nimport numpy as np\nimport os\nfrom PIL import Image\nfrom tqdm import tqdm\n\n# Download dataset from <https://supervise.ly/explore/projects/supervisely-person-dataset-23304/datasets>\nproject_root = 'PATH_TO/Supervisely Person Dataset'  # <-- Configure input\nproject = sly.Project(project_root, sly.OpenMode.READ)\n\noutput_path = 'OUTPUT_DIR'  # <-- Configure output\nos.makedirs(os.path.join(output_path, 'train', 'src'))\nos.makedirs(os.path.join(output_path, 'train', 'msk'))\nos.makedirs(os.path.join(output_path, 'valid', 'src'))\nos.makedirs(os.path.join(output_path, 'valid', 'msk'))\n\nmax_size = 2048  # <-- Configure max size\n\nfor dataset in project.datasets:\n    for item in tqdm(dataset):\n        ann = sly.Annotation.load_json_file(dataset.get_ann_path(item), project.meta)\n        msk = np.zeros(ann.img_size, dtype=np.uint8)\n        for label in ann.labels:\n            label.geometry.draw(msk, color=[255])\n        msk = Image.fromarray(msk)\n        \n        img = Image.open(dataset.get_img_path(item)).convert('RGB')\n        if img.size[0] > max_size or img.size[1] > max_size:\n            scale = max_size / max(img.size)\n            img = img.resize((int(img.size[0] * scale), int(img.size[1] * scale)), Image.BILINEAR)\n            msk = msk.resize((int(msk.size[0] * scale), int(msk.size[1] * scale)), Image.NEAREST)\n        \n        img.save(os.path.join(output_path, 'train', 'src', item.replace('.png', '.jpg')))\n        msk.save(os.path.join(output_path, 'train', 'msk', item.replace('.png', '.jpg')))\n\n# Move first 100 to validation set\nnames = os.listdir(os.path.join(output_path, 'train', 'src'))\nfor name in tqdm(names[:100]):\n    os.rename(\n        os.path.join(output_path, 'train', 'src', name),\n        os.path.join(output_path, 'valid', 'src', name))\n    os.rename(\n        os.path.join(output_path, 'train', 'msk', name),\n        os.path.join(output_path, 'valid', 'msk', name))"
  },
  {
    "path": "documentation/training.md",
    "content": "# Training Documentation\n\nThis documentation only shows the way to re-produce our [paper](https://peterl1n.github.io/RobustVideoMatting/). If you would like to remove or add a dataset to the training, you are responsible for adapting the training code yourself.\n\n## Datasets\n\nThe following datasets are used during our training.\n\n**IMPORTANT: If you choose to download our preprocessed versions. Please avoid repeated downloads and cache the data locally. All traffics cost our expense. Please be responsible. We may only provide the preprocessed version of a limited time.**\n\n### Matting Datasets\n* [VideoMatte240K](https://grail.cs.washington.edu/projects/background-matting-v2/#/datasets)\n    * Download JPEG SD version (6G) for stage 1 and 2.\n    * Download JPEG HD version (60G) for stage 3 and 4.\n    * Manually move clips `0000`, `0100`, `0200`, `0300` from the training set to a validation set.\n* ImageMatte\n    * ImageMatte consists of [Distinctions-646](https://wukaoliu.github.io/HAttMatting/) and [Adobe Image Matting](https://sites.google.com/view/deepimagematting) datasets.\n    * Only needed for stage 4.\n    * You need to contact their authors to acquire.\n    * After downloading both datasets, merge their samples together to form ImageMatte dataset.\n    * Only keep samples of humans.\n    * Full list of images we used in ImageMatte for training:\n        * [imagematte_train.txt](/documentation/misc/imagematte_train.txt)\n        * [imagematte_valid.txt](/documentation/misc/imagematte_valid.txt)\n    * Full list of images we used for evaluation.\n        * [aim_test.txt](/documentation/misc/aim_test.txt)\n        * [d646_test.txt](/documentation/misc/d646_test.txt)\n### Background Datasets\n* Video Backgrounds\n    * We process from [DVM Background Set](https://github.com/nowsyn/DVM) by selecting clips without humans and extract only the first 100 frames as JPEG sequence.\n    * Full list of clips we used:\n        * [dvm_background_train_clips.txt](/documentation/misc/dvm_background_train_clips.txt)\n        * [dvm_background_test_clips.txt](/documentation/misc/dvm_background_test_clips.txt)\n    * You can download our preprocessed versions:\n        * [Train set (14.6G)](https://robustvideomatting.blob.core.windows.net/data/BackgroundVideosTrain.tar) (Manually move some clips to validation set)\n        * [Test set (936M)](https://robustvideomatting.blob.core.windows.net/data/BackgroundVideosTest.tar) (Not needed for training. Only used for making synthetic test samples for evaluation)\n* Image Backgrounds\n    * Train set:\n        * We crawled 8000 suitable images from Google and Flicker.\n        * We will not publish these images.\n    * [Test set](https://grail.cs.washington.edu/projects/background-matting-v2/#/datasets)\n        * We use the validation background set from [BGMv2](https://grail.cs.washington.edu/projects/background-matting-v2/) project.\n        * It contains about 200 images.\n        * It is not used in our training. Only used for making synthetic test samples for evaluation.\n        * But if you just want to quickly tryout training, you may use this as a temporary subsitute for the train set.\n\n### Segmentation Datasets\n\n* [COCO](https://cocodataset.org/#download)\n    * Download [train2017.zip (18G)](http://images.cocodataset.org/zips/train2017.zip)\n    * Download [panoptic_annotations_trainval2017.zip (821M)](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip)\n    * Note that our train script expects the panopitc version.\n* [YouTubeVIS 2021](https://youtube-vos.org/dataset/vis/)\n    * Download the train set. No preprocessing needed.\n* [Supervisely Person Dataset](https://supervise.ly/explore/projects/supervisely-person-dataset-23304/datasets)\n    * We used the supervisedly library to convert their encoding to bitmaps masks before using our script. We also resized down some of the large images to avoid disk loading bottleneck.\n    * You can refer to [spd_preprocess.py](/documentation/misc/spd_preprocess.py)\n    * Or, you can download our [preprocessed version (800M)](https://robustvideomatting.blob.core.windows.net/data/SuperviselyPersonDataset.tar)\n\n## Training\n\nFor reference, our training was done on data center machines with 48 CPU cores, 300G CPU memory, and 4 Nvidia V100 32G GPUs.\n\nDuring our official training, the code contains custom logics for our infrastructure. For release, the script has been cleaned up. There may be bugs existing in this version of the code but not in our official training. If you find problems, please file an issue.\n\nAfter you have downloaded the datasets. Please configure `train_config.py` to provide paths to your datasets.\n\nThe training consists of 4 stages. For detail, please refer to the [paper](https://peterl1n.github.io/RobustVideoMatting/).\n\n### Stage 1\n```sh\npython train.py \\\n    --model-variant mobilenetv3 \\\n    --dataset videomatte \\\n    --resolution-lr 512 \\\n    --seq-length-lr 15 \\\n    --learning-rate-backbone 0.0001 \\\n    --learning-rate-aspp 0.0002 \\\n    --learning-rate-decoder 0.0002 \\\n    --learning-rate-refiner 0 \\\n    --checkpoint-dir checkpoint/stage1 \\\n    --log-dir log/stage1 \\\n    --epoch-start 0 \\\n    --epoch-end 20\n```\n\n### Stage 2\n```sh\npython train.py \\\n    --model-variant mobilenetv3 \\\n    --dataset videomatte \\\n    --resolution-lr 512 \\\n    --seq-length-lr 50 \\\n    --learning-rate-backbone 0.00005 \\\n    --learning-rate-aspp 0.0001 \\\n    --learning-rate-decoder 0.0001 \\\n    --learning-rate-refiner 0 \\\n    --checkpoint checkpoint/stage1/epoch-19.pth \\\n    --checkpoint-dir checkpoint/stage2 \\\n    --log-dir log/stage2 \\\n    --epoch-start 20 \\\n    --epoch-end 22\n```\n\n### Stage 3\n```sh\npython train.py \\\n    --model-variant mobilenetv3 \\\n    --dataset videomatte \\\n    --train-hr \\\n    --resolution-lr 512 \\\n    --resolution-hr 2048 \\\n    --seq-length-lr 40 \\\n    --seq-length-hr 6 \\\n    --learning-rate-backbone 0.00001 \\\n    --learning-rate-aspp 0.00001 \\\n    --learning-rate-decoder 0.00001 \\\n    --learning-rate-refiner 0.0002 \\\n    --checkpoint checkpoint/stage2/epoch-21.pth \\\n    --checkpoint-dir checkpoint/stage3 \\\n    --log-dir log/stage3 \\\n    --epoch-start 22 \\\n    --epoch-end 23\n```\n\n### Stage 4\n```sh\npython train.py \\\n    --model-variant mobilenetv3 \\\n    --dataset imagematte \\\n    --train-hr \\\n    --resolution-lr 512 \\\n    --resolution-hr 2048 \\\n    --seq-length-lr 40 \\\n    --seq-length-hr 6 \\\n    --learning-rate-backbone 0.00001 \\\n    --learning-rate-aspp 0.00001 \\\n    --learning-rate-decoder 0.00005 \\\n    --learning-rate-refiner 0.0002 \\\n    --checkpoint checkpoint/stage3/epoch-22.pth \\\n    --checkpoint-dir checkpoint/stage4 \\\n    --log-dir log/stage4 \\\n    --epoch-start 23 \\\n    --epoch-end 28\n```\n\n<br><br><br>\n\n## Evaluation\n\nWe synthetically composite test samples to both image and video backgrounds. Image samples (from D646, AIM) are augmented with synthetic motion.\n\nWe only provide the composited VideoMatte240K test set. They are used in our paper evaluation. For D646 and AIM, you need to acquire the data from their authors and composite them yourself. The composition scripts we used are saved in `/evaluation` folder as reference backup. You need to modify them based on your setup.\n\n* [videomatte_512x512.tar (PNG 1.8G)](https://robustvideomatting.blob.core.windows.net/eval/videomatte_512x288.tar)\n* [videomatte_1920x1080.tar (JPG 2.2G)](https://robustvideomatting.blob.core.windows.net/eval/videomatte_1920x1080.tar)\n\nEvaluation scripts are provided in `/evaluation` folder."
  },
  {
    "path": "evaluation/evaluate_hr.py",
    "content": "\"\"\"\nHR (High-Resolution) evaluation. We found using numpy is very slow for high resolution, so we moved it to PyTorch using CUDA.\n\nNote, the script only does evaluation. You will need to first inference yourself and save the results to disk\nExpected directory format for both prediction and ground-truth is:\n\n    videomatte_1920x1080\n        ├── videomatte_motion\n          ├── pha\n            ├── 0000\n              ├── 0000.png\n          ├── fgr\n            ├── 0000\n              ├── 0000.png\n        ├── videomatte_static\n          ├── pha\n            ├── 0000\n              ├── 0000.png\n          ├── fgr\n            ├── 0000\n              ├── 0000.png\n\nPrediction must have the exact file structure and file name as the ground-truth,\nmeaning that if the ground-truth is png/jpg, prediction should be png/jpg.\n\nExample usage:\n\npython evaluate.py \\\n    --pred-dir pred/videomatte_1920x1080 \\\n    --true-dir true/videomatte_1920x1080\n    \nAn excel sheet with evaluation results will be written to \"pred/videomatte_1920x1080/videomatte_1920x1080.xlsx\"\n\"\"\"\n\n\nimport argparse\nimport os\nimport cv2\nimport kornia\nimport numpy as np\nimport xlsxwriter\nimport torch\nfrom concurrent.futures import ThreadPoolExecutor\nfrom tqdm import tqdm\n\n\nclass Evaluator:\n    def __init__(self):\n        self.parse_args()\n        self.init_metrics()\n        self.evaluate()\n        self.write_excel()\n        \n    def parse_args(self):\n        parser = argparse.ArgumentParser()\n        parser.add_argument('--pred-dir', type=str, required=True)\n        parser.add_argument('--true-dir', type=str, required=True)\n        parser.add_argument('--num-workers', type=int, default=48)\n        parser.add_argument('--metrics', type=str, nargs='+', default=[\n            'pha_mad', 'pha_mse', 'pha_grad', 'pha_dtssd', 'fgr_mse'])\n        self.args = parser.parse_args()\n        \n    def init_metrics(self):\n        self.mad = MetricMAD()\n        self.mse = MetricMSE()\n        self.grad = MetricGRAD()\n        self.dtssd = MetricDTSSD()\n        \n    def evaluate(self):\n        tasks = []\n        position = 0\n        \n        with ThreadPoolExecutor(max_workers=self.args.num_workers) as executor:\n            for dataset in sorted(os.listdir(self.args.pred_dir)):\n                if os.path.isdir(os.path.join(self.args.pred_dir, dataset)):\n                    for clip in sorted(os.listdir(os.path.join(self.args.pred_dir, dataset))):\n                        future = executor.submit(self.evaluate_worker, dataset, clip, position)\n                        tasks.append((dataset, clip, future))\n                        position += 1\n                    \n        self.results = [(dataset, clip, future.result()) for dataset, clip, future in tasks]\n        \n    def write_excel(self):\n        workbook = xlsxwriter.Workbook(os.path.join(self.args.pred_dir, f'{os.path.basename(self.args.pred_dir)}.xlsx'))\n        summarysheet = workbook.add_worksheet('summary')\n        metricsheets = [workbook.add_worksheet(metric) for metric in self.results[0][2].keys()]\n        \n        for i, metric in enumerate(self.results[0][2].keys()):\n            summarysheet.write(i, 0, metric)\n            summarysheet.write(i, 1, f'={metric}!B2')\n        \n        for row, (dataset, clip, metrics) in enumerate(self.results):\n            for metricsheet, metric in zip(metricsheets, metrics.values()):\n                # Write the header\n                if row == 0:\n                    metricsheet.write(1, 0, 'Average')\n                    metricsheet.write(1, 1, f'=AVERAGE(C2:ZZ2)')\n                    for col in range(len(metric)):\n                        metricsheet.write(0, col + 2, col)\n                        colname = xlsxwriter.utility.xl_col_to_name(col + 2)\n                        metricsheet.write(1, col + 2, f'=AVERAGE({colname}3:{colname}9999)')\n                        \n                metricsheet.write(row + 2, 0, dataset)\n                metricsheet.write(row + 2, 1, clip)\n                metricsheet.write_row(row + 2, 2, metric)\n        \n        workbook.close()\n\n    def evaluate_worker(self, dataset, clip, position):\n        framenames = sorted(os.listdir(os.path.join(self.args.pred_dir, dataset, clip, 'pha')))\n        metrics = {metric_name : [] for metric_name in self.args.metrics}\n        \n        pred_pha_tm1 = None\n        true_pha_tm1 = None\n        \n        for i, framename in enumerate(tqdm(framenames, desc=f'{dataset} {clip}', position=position, dynamic_ncols=True)):\n            true_pha = cv2.imread(os.path.join(self.args.true_dir, dataset, clip, 'pha', framename), cv2.IMREAD_GRAYSCALE)\n            pred_pha = cv2.imread(os.path.join(self.args.pred_dir, dataset, clip, 'pha', framename), cv2.IMREAD_GRAYSCALE)\n            \n            true_pha = torch.from_numpy(true_pha).cuda(non_blocking=True).float().div_(255)\n            pred_pha = torch.from_numpy(pred_pha).cuda(non_blocking=True).float().div_(255)\n            \n            if 'pha_mad' in self.args.metrics:\n                metrics['pha_mad'].append(self.mad(pred_pha, true_pha))\n            if 'pha_mse' in self.args.metrics:\n                metrics['pha_mse'].append(self.mse(pred_pha, true_pha))\n            if 'pha_grad' in self.args.metrics:\n                metrics['pha_grad'].append(self.grad(pred_pha, true_pha))\n            if 'pha_conn' in self.args.metrics:\n                metrics['pha_conn'].append(self.conn(pred_pha, true_pha))\n            if 'pha_dtssd' in self.args.metrics:\n                if i == 0:\n                    metrics['pha_dtssd'].append(0)\n                else:\n                    metrics['pha_dtssd'].append(self.dtssd(pred_pha, pred_pha_tm1, true_pha, true_pha_tm1))\n                    \n            pred_pha_tm1 = pred_pha\n            true_pha_tm1 = true_pha\n            \n            if 'fgr_mse' in self.args.metrics:\n                true_fgr = cv2.imread(os.path.join(self.args.true_dir, dataset, clip, 'fgr', framename), cv2.IMREAD_COLOR)\n                pred_fgr = cv2.imread(os.path.join(self.args.pred_dir, dataset, clip, 'fgr', framename), cv2.IMREAD_COLOR)\n                \n                true_fgr = torch.from_numpy(true_fgr).float().div_(255)\n                pred_fgr = torch.from_numpy(pred_fgr).float().div_(255)\n                \n                true_msk = true_pha > 0\n                metrics['fgr_mse'].append(self.mse(pred_fgr[true_msk], true_fgr[true_msk]))\n\n        return metrics\n\n\nclass MetricMAD:\n    def __call__(self, pred, true):\n        return (pred - true).abs_().mean() * 1e3\n\n\nclass MetricMSE:\n    def __call__(self, pred, true):\n        return ((pred - true) ** 2).mean() * 1e3\n\n\nclass MetricGRAD:\n    def __init__(self, sigma=1.4):\n        self.filter_x, self.filter_y = self.gauss_filter(sigma)\n        self.filter_x = torch.from_numpy(self.filter_x).unsqueeze(0).cuda()\n        self.filter_y = torch.from_numpy(self.filter_y).unsqueeze(0).cuda()\n    \n    def __call__(self, pred, true):\n        true_grad = self.gauss_gradient(true)\n        pred_grad = self.gauss_gradient(pred)\n        return ((true_grad - pred_grad) ** 2).sum() / 1000\n    \n    def gauss_gradient(self, img):\n        img_filtered_x = kornia.filters.filter2D(img[None, None, :, :], self.filter_x, border_type='replicate')[0, 0]\n        img_filtered_y = kornia.filters.filter2D(img[None, None, :, :], self.filter_y, border_type='replicate')[0, 0]\n        return (img_filtered_x**2 + img_filtered_y**2).sqrt()\n    \n    @staticmethod\n    def gauss_filter(sigma, epsilon=1e-2):\n        half_size = np.ceil(sigma * np.sqrt(-2 * np.log(np.sqrt(2 * np.pi) * sigma * epsilon)))\n        size = np.int(2 * half_size + 1)\n\n        # create filter in x axis\n        filter_x = np.zeros((size, size))\n        for i in range(size):\n            for j in range(size):\n                filter_x[i, j] = MetricGRAD.gaussian(i - half_size, sigma) * MetricGRAD.dgaussian(\n                    j - half_size, sigma)\n\n        # normalize filter\n        norm = np.sqrt((filter_x**2).sum())\n        filter_x = filter_x / norm\n        filter_y = np.transpose(filter_x)\n\n        return filter_x, filter_y\n        \n    @staticmethod\n    def gaussian(x, sigma):\n        return np.exp(-x**2 / (2 * sigma**2)) / (sigma * np.sqrt(2 * np.pi))\n    \n    @staticmethod\n    def dgaussian(x, sigma):\n        return -x * MetricGRAD.gaussian(x, sigma) / sigma**2\n\n\nclass MetricDTSSD:\n    def __call__(self, pred_t, pred_tm1, true_t, true_tm1):\n        dtSSD = ((pred_t - pred_tm1) - (true_t - true_tm1)) ** 2\n        dtSSD = dtSSD.sum() / true_t.numel()\n        dtSSD = dtSSD.sqrt()\n        return dtSSD * 1e2\n\n\nif __name__ == '__main__':\n    Evaluator()"
  },
  {
    "path": "evaluation/evaluate_lr.py",
    "content": "\"\"\"\nLR (Low-Resolution) evaluation.\n\nNote, the script only does evaluation. You will need to first inference yourself and save the results to disk\nExpected directory format for both prediction and ground-truth is:\n\n    videomatte_512x288\n        ├── videomatte_motion\n          ├── pha\n            ├── 0000\n              ├── 0000.png\n          ├── fgr\n            ├── 0000\n              ├── 0000.png\n        ├── videomatte_static\n          ├── pha\n            ├── 0000\n              ├── 0000.png\n          ├── fgr\n            ├── 0000\n              ├── 0000.png\n\nPrediction must have the exact file structure and file name as the ground-truth,\nmeaning that if the ground-truth is png/jpg, prediction should be png/jpg.\n\nExample usage:\n\npython evaluate.py \\\n    --pred-dir PATH_TO_PREDICTIONS/videomatte_512x288 \\\n    --true-dir PATH_TO_GROUNDTURTH/videomatte_512x288\n    \nAn excel sheet with evaluation results will be written to \"PATH_TO_PREDICTIONS/videomatte_512x288/videomatte_512x288.xlsx\"\n\"\"\"\n\n\nimport argparse\nimport os\nimport cv2\nimport numpy as np\nimport xlsxwriter\nfrom concurrent.futures import ThreadPoolExecutor\nfrom tqdm import tqdm\n\n\nclass Evaluator:\n    def __init__(self):\n        self.parse_args()\n        self.init_metrics()\n        self.evaluate()\n        self.write_excel()\n        \n    def parse_args(self):\n        parser = argparse.ArgumentParser()\n        parser.add_argument('--pred-dir', type=str, required=True)\n        parser.add_argument('--true-dir', type=str, required=True)\n        parser.add_argument('--num-workers', type=int, default=48)\n        parser.add_argument('--metrics', type=str, nargs='+', default=[\n            'pha_mad', 'pha_mse', 'pha_grad', 'pha_conn', 'pha_dtssd', 'fgr_mad', 'fgr_mse'])\n        self.args = parser.parse_args()\n        \n    def init_metrics(self):\n        self.mad = MetricMAD()\n        self.mse = MetricMSE()\n        self.grad = MetricGRAD()\n        self.conn = MetricCONN()\n        self.dtssd = MetricDTSSD()\n        \n    def evaluate(self):\n        tasks = []\n        position = 0\n        \n        with ThreadPoolExecutor(max_workers=self.args.num_workers) as executor:\n            for dataset in sorted(os.listdir(self.args.pred_dir)):\n                if os.path.isdir(os.path.join(self.args.pred_dir, dataset)):\n                    for clip in sorted(os.listdir(os.path.join(self.args.pred_dir, dataset))):\n                        future = executor.submit(self.evaluate_worker, dataset, clip, position)\n                        tasks.append((dataset, clip, future))\n                        position += 1\n                    \n        self.results = [(dataset, clip, future.result()) for dataset, clip, future in tasks]\n        \n    def write_excel(self):\n        workbook = xlsxwriter.Workbook(os.path.join(self.args.pred_dir, f'{os.path.basename(self.args.pred_dir)}.xlsx'))\n        summarysheet = workbook.add_worksheet('summary')\n        metricsheets = [workbook.add_worksheet(metric) for metric in self.results[0][2].keys()]\n        \n        for i, metric in enumerate(self.results[0][2].keys()):\n            summarysheet.write(i, 0, metric)\n            summarysheet.write(i, 1, f'={metric}!B2')\n        \n        for row, (dataset, clip, metrics) in enumerate(self.results):\n            for metricsheet, metric in zip(metricsheets, metrics.values()):\n                # Write the header\n                if row == 0:\n                    metricsheet.write(1, 0, 'Average')\n                    metricsheet.write(1, 1, f'=AVERAGE(C2:ZZ2)')\n                    for col in range(len(metric)):\n                        metricsheet.write(0, col + 2, col)\n                        colname = xlsxwriter.utility.xl_col_to_name(col + 2)\n                        metricsheet.write(1, col + 2, f'=AVERAGE({colname}3:{colname}9999)')\n                        \n                metricsheet.write(row + 2, 0, dataset)\n                metricsheet.write(row + 2, 1, clip)\n                metricsheet.write_row(row + 2, 2, metric)\n        \n        workbook.close()\n\n    def evaluate_worker(self, dataset, clip, position):\n        framenames = sorted(os.listdir(os.path.join(self.args.pred_dir, dataset, clip, 'pha')))\n        metrics = {metric_name : [] for metric_name in self.args.metrics}\n        \n        pred_pha_tm1 = None\n        true_pha_tm1 = None\n        \n        for i, framename in enumerate(tqdm(framenames, desc=f'{dataset} {clip}', position=position, dynamic_ncols=True)):\n            true_pha = cv2.imread(os.path.join(self.args.true_dir, dataset, clip, 'pha', framename), cv2.IMREAD_GRAYSCALE).astype(np.float32) / 255\n            pred_pha = cv2.imread(os.path.join(self.args.pred_dir, dataset, clip, 'pha', framename), cv2.IMREAD_GRAYSCALE).astype(np.float32) / 255\n            if 'pha_mad' in self.args.metrics:\n                metrics['pha_mad'].append(self.mad(pred_pha, true_pha))\n            if 'pha_mse' in self.args.metrics:\n                metrics['pha_mse'].append(self.mse(pred_pha, true_pha))\n            if 'pha_grad' in self.args.metrics:\n                metrics['pha_grad'].append(self.grad(pred_pha, true_pha))\n            if 'pha_conn' in self.args.metrics:\n                metrics['pha_conn'].append(self.conn(pred_pha, true_pha))\n            if 'pha_dtssd' in self.args.metrics:\n                if i == 0:\n                    metrics['pha_dtssd'].append(0)\n                else:\n                    metrics['pha_dtssd'].append(self.dtssd(pred_pha, pred_pha_tm1, true_pha, true_pha_tm1))\n                    \n            pred_pha_tm1 = pred_pha\n            true_pha_tm1 = true_pha\n            \n            if 'fgr_mse' in self.args.metrics or 'fgr_mad' in self.args.metrics:\n                true_fgr = cv2.imread(os.path.join(self.args.true_dir, dataset, clip, 'fgr', framename), cv2.IMREAD_COLOR).astype(np.float32) / 255\n                pred_fgr = cv2.imread(os.path.join(self.args.pred_dir, dataset, clip, 'fgr', framename), cv2.IMREAD_COLOR).astype(np.float32) / 255\n                true_msk = true_pha > 0\n                \n                if 'fgr_mse' in self.args.metrics:\n                    metrics['fgr_mse'].append(self.mse(pred_fgr[true_msk], true_fgr[true_msk]))\n                if 'fgr_mad' in self.args.metrics:\n                    metrics['fgr_mad'].append(self.mad(pred_fgr[true_msk], true_fgr[true_msk]))\n\n        return metrics\n\n    \nclass MetricMAD:\n    def __call__(self, pred, true):\n        return np.abs(pred - true).mean() * 1e3\n\n\nclass MetricMSE:\n    def __call__(self, pred, true):\n        return ((pred - true) ** 2).mean() * 1e3\n\n\nclass MetricGRAD:\n    def __init__(self, sigma=1.4):\n        self.filter_x, self.filter_y = self.gauss_filter(sigma)\n    \n    def __call__(self, pred, true):\n        pred_normed = np.zeros_like(pred)\n        true_normed = np.zeros_like(true)\n        cv2.normalize(pred, pred_normed, 1., 0., cv2.NORM_MINMAX)\n        cv2.normalize(true, true_normed, 1., 0., cv2.NORM_MINMAX)\n\n        true_grad = self.gauss_gradient(true_normed).astype(np.float32)\n        pred_grad = self.gauss_gradient(pred_normed).astype(np.float32)\n\n        grad_loss = ((true_grad - pred_grad) ** 2).sum()\n        return grad_loss / 1000\n    \n    def gauss_gradient(self, img):\n        img_filtered_x = cv2.filter2D(img, -1, self.filter_x, borderType=cv2.BORDER_REPLICATE)\n        img_filtered_y = cv2.filter2D(img, -1, self.filter_y, borderType=cv2.BORDER_REPLICATE)\n        return np.sqrt(img_filtered_x**2 + img_filtered_y**2)\n    \n    @staticmethod\n    def gauss_filter(sigma, epsilon=1e-2):\n        half_size = np.ceil(sigma * np.sqrt(-2 * np.log(np.sqrt(2 * np.pi) * sigma * epsilon)))\n        size = np.int(2 * half_size + 1)\n\n        # create filter in x axis\n        filter_x = np.zeros((size, size))\n        for i in range(size):\n            for j in range(size):\n                filter_x[i, j] = MetricGRAD.gaussian(i - half_size, sigma) * MetricGRAD.dgaussian(\n                    j - half_size, sigma)\n\n        # normalize filter\n        norm = np.sqrt((filter_x**2).sum())\n        filter_x = filter_x / norm\n        filter_y = np.transpose(filter_x)\n\n        return filter_x, filter_y\n        \n    @staticmethod\n    def gaussian(x, sigma):\n        return np.exp(-x**2 / (2 * sigma**2)) / (sigma * np.sqrt(2 * np.pi))\n    \n    @staticmethod\n    def dgaussian(x, sigma):\n        return -x * MetricGRAD.gaussian(x, sigma) / sigma**2\n\n\nclass MetricCONN:\n    def __call__(self, pred, true):\n        step=0.1\n        thresh_steps = np.arange(0, 1 + step, step)\n        round_down_map = -np.ones_like(true)\n        for i in range(1, len(thresh_steps)):\n            true_thresh = true >= thresh_steps[i]\n            pred_thresh = pred >= thresh_steps[i]\n            intersection = (true_thresh & pred_thresh).astype(np.uint8)\n\n            # connected components\n            _, output, stats, _ = cv2.connectedComponentsWithStats(\n                intersection, connectivity=4)\n            # start from 1 in dim 0 to exclude background\n            size = stats[1:, -1]\n\n            # largest connected component of the intersection\n            omega = np.zeros_like(true)\n            if len(size) != 0:\n                max_id = np.argmax(size)\n                # plus one to include background\n                omega[output == max_id + 1] = 1\n\n            mask = (round_down_map == -1) & (omega == 0)\n            round_down_map[mask] = thresh_steps[i - 1]\n        round_down_map[round_down_map == -1] = 1\n\n        true_diff = true - round_down_map\n        pred_diff = pred - round_down_map\n        # only calculate difference larger than or equal to 0.15\n        true_phi = 1 - true_diff * (true_diff >= 0.15)\n        pred_phi = 1 - pred_diff * (pred_diff >= 0.15)\n\n        connectivity_error = np.sum(np.abs(true_phi - pred_phi))\n        return connectivity_error / 1000\n\n\nclass MetricDTSSD:\n    def __call__(self, pred_t, pred_tm1, true_t, true_tm1):\n        dtSSD = ((pred_t - pred_tm1) - (true_t - true_tm1)) ** 2\n        dtSSD = np.sum(dtSSD) / true_t.size\n        dtSSD = np.sqrt(dtSSD)\n        return dtSSD * 1e2\n\n\n\nif __name__ == '__main__':\n    Evaluator()"
  },
  {
    "path": "evaluation/generate_imagematte_with_background_image.py",
    "content": "\"\"\"\npython generate_imagematte_with_background_image.py \\\n    --imagematte-dir ../matting-data/Distinctions/test \\\n    --background-dir ../matting-data/Backgrounds/valid \\\n    --resolution 512 \\\n    --out-dir ../matting-data/evaluation/distinction_static_sd/ \\\n    --random-seed 10\n    \nSeed:\n    10 - distinction-static\n    11 - distinction-motion\n    12 - adobe-static\n    13 - adobe-motion\n    \n\"\"\"\n\nimport argparse\nimport os\nimport pims\nimport numpy as np\nimport random\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom tqdm.contrib.concurrent import process_map\nfrom torchvision import transforms\nfrom torchvision.transforms import functional as F\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--imagematte-dir', type=str, required=True)\nparser.add_argument('--background-dir', type=str, required=True)\nparser.add_argument('--num-samples', type=int, default=20)\nparser.add_argument('--num-frames', type=int, default=100)\nparser.add_argument('--resolution', type=int, required=True)\nparser.add_argument('--out-dir', type=str, required=True)\nparser.add_argument('--random-seed', type=int)\nparser.add_argument('--extension', type=str, default='.png')\nargs = parser.parse_args()\n    \nrandom.seed(args.random_seed)\n\nimagematte_filenames = os.listdir(os.path.join(args.imagematte_dir, 'fgr'))\nbackground_filenames = os.listdir(args.background_dir)\nrandom.shuffle(imagematte_filenames)\nrandom.shuffle(background_filenames)\n\n\ndef lerp(a, b, percentage):\n    return a * (1 - percentage) + b * percentage\n\ndef motion_affine(*imgs):\n    config = dict(degrees=(-10, 10), translate=(0.1, 0.1),\n                  scale_ranges=(0.9, 1.1), shears=(-5, 5), img_size=imgs[0][0].size)\n    angleA, (transXA, transYA), scaleA, (shearXA, shearYA) = transforms.RandomAffine.get_params(**config)\n    angleB, (transXB, transYB), scaleB, (shearXB, shearYB) = transforms.RandomAffine.get_params(**config)\n\n    T = len(imgs[0])\n    variation_over_time = random.random()\n    for t in range(T):\n        percentage = (t / (T - 1)) * variation_over_time\n        angle = lerp(angleA, angleB, percentage)\n        transX = lerp(transXA, transXB, percentage)\n        transY = lerp(transYA, transYB, percentage)\n        scale = lerp(scaleA, scaleB, percentage)\n        shearX = lerp(shearXA, shearXB, percentage)\n        shearY = lerp(shearYA, shearYB, percentage)\n        for img in imgs:\n            img[t] = F.affine(img[t], angle, (transX, transY), scale, (shearX, shearY), F.InterpolationMode.BILINEAR)\n    return imgs\n    \n\n\ndef process(i):\n    imagematte_filename = imagematte_filenames[i % len(imagematte_filenames)]\n    background_filename = background_filenames[i % len(background_filenames)]\n    \n    out_path = os.path.join(args.out_dir, str(i).zfill(4))\n    os.makedirs(os.path.join(out_path, 'fgr'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'pha'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'com'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'bgr'), exist_ok=True)\n    \n    with Image.open(os.path.join(args.background_dir, background_filename)) as bgr:\n        bgr = bgr.convert('RGB')\n        \n        w, h = bgr.size\n        scale = args.resolution / min(h, w)\n        w, h = int(w * scale), int(h * scale)\n        bgr = bgr.resize((w, h))\n        bgr = F.center_crop(bgr, (args.resolution, args.resolution))\n\n    with Image.open(os.path.join(args.imagematte_dir, 'fgr', imagematte_filename)) as fgr, \\\n         Image.open(os.path.join(args.imagematte_dir, 'pha', imagematte_filename)) as pha:\n        fgr = fgr.convert('RGB')\n        pha = pha.convert('L')\n        \n    fgrs = [fgr] * args.num_frames\n    phas = [pha] * args.num_frames\n    fgrs, phas = motion_affine(fgrs, phas)\n    \n    for t in tqdm(range(args.num_frames), desc=str(i).zfill(4)):\n        fgr = fgrs[t]\n        pha = phas[t]\n        \n        w, h = fgr.size\n        scale = args.resolution / max(h, w)\n        w, h = int(w * scale), int(h * scale)\n        \n        fgr = fgr.resize((w, h))\n        pha = pha.resize((w, h))\n        \n        if h < args.resolution:\n            pt = (args.resolution - h) // 2\n            pb = args.resolution - h - pt\n        else:\n            pt = 0\n            pb = 0\n            \n        if w < args.resolution:\n            pl = (args.resolution - w) // 2\n            pr = args.resolution - w - pl\n        else:\n            pl = 0\n            pr = 0\n            \n        fgr = F.pad(fgr, [pl, pt, pr, pb])\n        pha = F.pad(pha, [pl, pt, pr, pb])\n        \n        if i // len(imagematte_filenames) % 2 == 1:\n            fgr = fgr.transpose(Image.FLIP_LEFT_RIGHT)\n            pha = pha.transpose(Image.FLIP_LEFT_RIGHT)\n            \n        fgr.save(os.path.join(out_path, 'fgr', str(t).zfill(4) + args.extension))\n        pha.save(os.path.join(out_path, 'pha', str(t).zfill(4) + args.extension))\n        \n        if t == 0:\n            bgr.save(os.path.join(out_path, 'bgr', str(t).zfill(4) + args.extension))\n        else:\n            os.symlink(str(0).zfill(4) + args.extension, os.path.join(out_path, 'bgr', str(t).zfill(4) + args.extension))\n        \n        pha = np.asarray(pha).astype(float)[:, :, None] / 255\n        com = Image.fromarray(np.uint8(np.asarray(fgr) * pha + np.asarray(bgr) * (1 - pha)))\n        com.save(os.path.join(out_path, 'com', str(t).zfill(4) + args.extension))\n\n\nif __name__ == '__main__':\n    r = process_map(process, range(args.num_samples), max_workers=32)"
  },
  {
    "path": "evaluation/generate_imagematte_with_background_video.py",
    "content": "\"\"\"\npython generate_imagematte_with_background_video.py \\\n    --imagematte-dir ../matting-data/Distinctions/test \\\n    --background-dir ../matting-data/BackgroundVideos_mp4/test \\\n    --resolution 512 \\\n    --out-dir ../matting-data/evaluation/distinction_motion_sd/ \\\n    --random-seed 11\n    \nSeed:\n    10 - distinction-static\n    11 - distinction-motion\n    12 - adobe-static\n    13 - adobe-motion\n    \n\"\"\"\n\nimport argparse\nimport os\nimport pims\nimport numpy as np\nimport random\nfrom multiprocessing import Pool\nfrom PIL import Image\n# from tqdm import tqdm\nfrom tqdm.contrib.concurrent import process_map\nfrom torchvision import transforms\nfrom torchvision.transforms import functional as F\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--imagematte-dir', type=str, required=True)\nparser.add_argument('--background-dir', type=str, required=True)\nparser.add_argument('--num-samples', type=int, default=20)\nparser.add_argument('--num-frames', type=int, default=100)\nparser.add_argument('--resolution', type=int, required=True)\nparser.add_argument('--out-dir', type=str, required=True)\nparser.add_argument('--random-seed', type=int)\nparser.add_argument('--extension', type=str, default='.png')\nargs = parser.parse_args()\n    \nrandom.seed(args.random_seed)\n\nimagematte_filenames = os.listdir(os.path.join(args.imagematte_dir, 'fgr'))\nrandom.shuffle(imagematte_filenames)\n\nbackground_filenames = [\n    \"0000.mp4\",\n    \"0007.mp4\",\n    \"0008.mp4\",\n    \"0010.mp4\",\n    \"0013.mp4\",\n    \"0015.mp4\",\n    \"0016.mp4\",\n    \"0018.mp4\",\n    \"0021.mp4\",\n    \"0029.mp4\",\n    \"0033.mp4\",\n    \"0035.mp4\",\n    \"0039.mp4\",\n    \"0050.mp4\",\n    \"0052.mp4\",\n    \"0055.mp4\",\n    \"0060.mp4\",\n    \"0063.mp4\",\n    \"0087.mp4\",\n    \"0086.mp4\",\n    \"0090.mp4\",\n    \"0101.mp4\",\n    \"0110.mp4\",\n    \"0117.mp4\",\n    \"0120.mp4\",\n    \"0122.mp4\",\n    \"0123.mp4\",\n    \"0125.mp4\",\n    \"0128.mp4\",\n    \"0131.mp4\",\n    \"0172.mp4\",\n    \"0176.mp4\",\n    \"0181.mp4\",\n    \"0187.mp4\",\n    \"0193.mp4\",\n    \"0198.mp4\",\n    \"0220.mp4\",\n    \"0221.mp4\",\n    \"0224.mp4\",\n    \"0229.mp4\",\n    \"0233.mp4\",\n    \"0238.mp4\",\n    \"0241.mp4\",\n    \"0245.mp4\",\n    \"0246.mp4\"\n]\n\nrandom.shuffle(background_filenames)\n\ndef lerp(a, b, percentage):\n    return a * (1 - percentage) + b * percentage\n\ndef motion_affine(*imgs):\n    config = dict(degrees=(-10, 10), translate=(0.1, 0.1),\n                  scale_ranges=(0.9, 1.1), shears=(-5, 5), img_size=imgs[0][0].size)\n    angleA, (transXA, transYA), scaleA, (shearXA, shearYA) = transforms.RandomAffine.get_params(**config)\n    angleB, (transXB, transYB), scaleB, (shearXB, shearYB) = transforms.RandomAffine.get_params(**config)\n\n    T = len(imgs[0])\n    variation_over_time = random.random()\n    for t in range(T):\n        percentage = (t / (T - 1)) * variation_over_time\n        angle = lerp(angleA, angleB, percentage)\n        transX = lerp(transXA, transXB, percentage)\n        transY = lerp(transYA, transYB, percentage)\n        scale = lerp(scaleA, scaleB, percentage)\n        shearX = lerp(shearXA, shearXB, percentage)\n        shearY = lerp(shearYA, shearYB, percentage)\n        for img in imgs:\n            img[t] = F.affine(img[t], angle, (transX, transY), scale, (shearX, shearY), F.InterpolationMode.BILINEAR)\n    return imgs\n\n\ndef process(i):\n    imagematte_filename = imagematte_filenames[i % len(imagematte_filenames)]\n    background_filename = background_filenames[i % len(background_filenames)]\n    \n    bgrs = pims.PyAVVideoReader(os.path.join(args.background_dir, background_filename))\n    \n    out_path = os.path.join(args.out_dir, str(i).zfill(4))\n    os.makedirs(os.path.join(out_path, 'fgr'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'pha'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'com'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'bgr'), exist_ok=True)\n\n    with Image.open(os.path.join(args.imagematte_dir, 'fgr', imagematte_filename)) as fgr, \\\n         Image.open(os.path.join(args.imagematte_dir, 'pha', imagematte_filename)) as pha:\n        fgr = fgr.convert('RGB')\n        pha = pha.convert('L')\n        \n    fgrs = [fgr] * args.num_frames\n    phas = [pha] * args.num_frames\n    fgrs, phas = motion_affine(fgrs, phas)\n    \n    for t in range(args.num_frames):\n        fgr = fgrs[t]\n        pha = phas[t]\n        \n        w, h = fgr.size\n        scale = args.resolution / max(h, w)\n        w, h = int(w * scale), int(h * scale)\n        \n        fgr = fgr.resize((w, h))\n        pha = pha.resize((w, h))\n        \n        if h < args.resolution:\n            pt = (args.resolution - h) // 2\n            pb = args.resolution - h - pt\n        else:\n            pt = 0\n            pb = 0\n            \n        if w < args.resolution:\n            pl = (args.resolution - w) // 2\n            pr = args.resolution - w - pl\n        else:\n            pl = 0\n            pr = 0\n            \n        fgr = F.pad(fgr, [pl, pt, pr, pb])\n        pha = F.pad(pha, [pl, pt, pr, pb])\n        \n        if i // len(imagematte_filenames) % 2 == 1:\n            fgr = fgr.transpose(Image.FLIP_LEFT_RIGHT)\n            pha = pha.transpose(Image.FLIP_LEFT_RIGHT)\n            \n        fgr.save(os.path.join(out_path, 'fgr', str(t).zfill(4) + args.extension))\n        pha.save(os.path.join(out_path, 'pha', str(t).zfill(4) + args.extension))\n        \n        bgr = Image.fromarray(bgrs[t]).convert('RGB')\n        w, h = bgr.size\n        scale = args.resolution / min(h, w)\n        w, h = int(w * scale), int(h * scale)\n        bgr = bgr.resize((w, h))\n        bgr = F.center_crop(bgr, (args.resolution, args.resolution))\n        bgr.save(os.path.join(out_path, 'bgr', str(t).zfill(4) + args.extension))\n        \n        pha = np.asarray(pha).astype(float)[:, :, None] / 255\n        com = Image.fromarray(np.uint8(np.asarray(fgr) * pha + np.asarray(bgr) * (1 - pha)))\n        com.save(os.path.join(out_path, 'com', str(t).zfill(4) + args.extension))\n        \nif __name__ == '__main__':\n    r = process_map(process, range(args.num_samples), max_workers=10)\n\n"
  },
  {
    "path": "evaluation/generate_videomatte_with_background_image.py",
    "content": "\"\"\"\npython generate_videomatte_with_background_image.py \\\n    --videomatte-dir ../matting-data/VideoMatte240K_JPEG_HD/test \\\n    --background-dir ../matting-data/Backgrounds/valid \\\n    --num-samples 25 \\\n    --resize 512 288 \\\n    --out-dir ../matting-data/evaluation/vidematte_static_sd/\n\"\"\"\n\nimport argparse\nimport os\nimport pims\nimport numpy as np\nimport random\nfrom PIL import Image\nfrom tqdm import tqdm\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--videomatte-dir', type=str, required=True)\nparser.add_argument('--background-dir', type=str, required=True)\nparser.add_argument('--num-samples', type=int, default=20)\nparser.add_argument('--num-frames', type=int, default=100)\nparser.add_argument('--resize', type=int, default=None, nargs=2)\nparser.add_argument('--out-dir', type=str, required=True)\nparser.add_argument('--extension', type=str, default='.png')\nargs = parser.parse_args()\n    \nrandom.seed(10)\n\nvideomatte_filenames = [(clipname, sorted(os.listdir(os.path.join(args.videomatte_dir, 'fgr', clipname)))) \n                        for clipname in sorted(os.listdir(os.path.join(args.videomatte_dir, 'fgr')))]\n\nbackground_filenames = os.listdir(args.background_dir)\nrandom.shuffle(background_filenames)\n\nfor i in range(args.num_samples):\n    \n    clipname, framenames = videomatte_filenames[i % len(videomatte_filenames)]\n    \n    out_path = os.path.join(args.out_dir, str(i).zfill(4))\n    os.makedirs(os.path.join(out_path, 'fgr'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'pha'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'com'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'bgr'), exist_ok=True)\n    \n    with Image.open(os.path.join(args.background_dir, background_filenames[i])) as bgr:\n        bgr = bgr.convert('RGB')\n\n    \n    base_t = random.choice(range(len(framenames) - args.num_frames))\n    \n    for t in tqdm(range(args.num_frames), desc=str(i).zfill(4)):\n        with Image.open(os.path.join(args.videomatte_dir, 'fgr', clipname, framenames[base_t + t])) as fgr, \\\n             Image.open(os.path.join(args.videomatte_dir, 'pha', clipname, framenames[base_t + t])) as pha:\n            fgr = fgr.convert('RGB')\n            pha = pha.convert('L')\n            \n            if args.resize is not None:\n                fgr = fgr.resize(args.resize, Image.BILINEAR)\n                pha = pha.resize(args.resize, Image.BILINEAR)\n                \n            \n            if i // len(videomatte_filenames) % 2 == 1:\n                fgr = fgr.transpose(Image.FLIP_LEFT_RIGHT)\n                pha = pha.transpose(Image.FLIP_LEFT_RIGHT)\n            \n            fgr.save(os.path.join(out_path, 'fgr', str(t).zfill(4) + args.extension))\n            pha.save(os.path.join(out_path, 'pha', str(t).zfill(4) + args.extension))\n        \n        if t == 0:\n            bgr = bgr.resize(fgr.size, Image.BILINEAR)\n            bgr.save(os.path.join(out_path, 'bgr', str(t).zfill(4) + args.extension))\n        else:\n            os.symlink(str(0).zfill(4) + args.extension, os.path.join(out_path, 'bgr', str(t).zfill(4) + args.extension))\n        \n        pha = np.asarray(pha).astype(float)[:, :, None] / 255\n        com = Image.fromarray(np.uint8(np.asarray(fgr) * pha + np.asarray(bgr) * (1 - pha)))\n        com.save(os.path.join(out_path, 'com', str(t).zfill(4) + args.extension))\n"
  },
  {
    "path": "evaluation/generate_videomatte_with_background_video.py",
    "content": "\"\"\"\npython generate_videomatte_with_background_video.py \\\n    --videomatte-dir ../matting-data/VideoMatte240K_JPEG_HD/test \\\n    --background-dir ../matting-data/BackgroundVideos_mp4/test \\\n    --resize 512 288 \\\n    --out-dir ../matting-data/evaluation/vidematte_motion_sd/\n\"\"\"\n\nimport argparse\nimport os\nimport pims\nimport numpy as np\nimport random\nfrom PIL import Image\nfrom tqdm import tqdm\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--videomatte-dir', type=str, required=True)\nparser.add_argument('--background-dir', type=str, required=True)\nparser.add_argument('--num-samples', type=int, default=20)\nparser.add_argument('--num-frames', type=int, default=100)\nparser.add_argument('--resize', type=int, default=None, nargs=2)\nparser.add_argument('--out-dir', type=str, required=True)\nargs = parser.parse_args()\n\n# Hand selected a list of videos\nbackground_filenames = [\n    \"0000.mp4\",\n    \"0007.mp4\",\n    \"0008.mp4\",\n    \"0010.mp4\",\n    \"0013.mp4\",\n    \"0015.mp4\",\n    \"0016.mp4\",\n    \"0018.mp4\",\n    \"0021.mp4\",\n    \"0029.mp4\",\n    \"0033.mp4\",\n    \"0035.mp4\",\n    \"0039.mp4\",\n    \"0050.mp4\",\n    \"0052.mp4\",\n    \"0055.mp4\",\n    \"0060.mp4\",\n    \"0063.mp4\",\n    \"0087.mp4\",\n    \"0086.mp4\",\n    \"0090.mp4\",\n    \"0101.mp4\",\n    \"0110.mp4\",\n    \"0117.mp4\",\n    \"0120.mp4\",\n    \"0122.mp4\",\n    \"0123.mp4\",\n    \"0125.mp4\",\n    \"0128.mp4\",\n    \"0131.mp4\",\n    \"0172.mp4\",\n    \"0176.mp4\",\n    \"0181.mp4\",\n    \"0187.mp4\",\n    \"0193.mp4\",\n    \"0198.mp4\",\n    \"0220.mp4\",\n    \"0221.mp4\",\n    \"0224.mp4\",\n    \"0229.mp4\",\n    \"0233.mp4\",\n    \"0238.mp4\",\n    \"0241.mp4\",\n    \"0245.mp4\",\n    \"0246.mp4\"\n]\n\nrandom.seed(10)\n    \nvideomatte_filenames = [(clipname, sorted(os.listdir(os.path.join(args.videomatte_dir, 'fgr', clipname)))) \n                        for clipname in sorted(os.listdir(os.path.join(args.videomatte_dir, 'fgr')))]\n\nrandom.shuffle(background_filenames)\n\nfor i in range(args.num_samples):\n    bgrs = pims.PyAVVideoReader(os.path.join(args.background_dir, background_filenames[i % len(background_filenames)]))\n    clipname, framenames = videomatte_filenames[i % len(videomatte_filenames)]\n    \n    out_path = os.path.join(args.out_dir, str(i).zfill(4))\n    os.makedirs(os.path.join(out_path, 'fgr'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'pha'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'com'), exist_ok=True)\n    os.makedirs(os.path.join(out_path, 'bgr'), exist_ok=True)\n    \n    base_t = random.choice(range(len(framenames) - args.num_frames))\n    \n    for t in tqdm(range(args.num_frames), desc=str(i).zfill(4)):\n        with Image.open(os.path.join(args.videomatte_dir, 'fgr', clipname, framenames[base_t + t])) as fgr, \\\n             Image.open(os.path.join(args.videomatte_dir, 'pha', clipname, framenames[base_t + t])) as pha:\n            fgr = fgr.convert('RGB')\n            pha = pha.convert('L')\n            \n            if args.resize is not None:\n                fgr = fgr.resize(args.resize, Image.BILINEAR)\n                pha = pha.resize(args.resize, Image.BILINEAR)\n                \n            \n            if i // len(videomatte_filenames) % 2 == 1:\n                fgr = fgr.transpose(Image.FLIP_LEFT_RIGHT)\n                pha = pha.transpose(Image.FLIP_LEFT_RIGHT)\n            \n            fgr.save(os.path.join(out_path, 'fgr', str(t).zfill(4) + '.png'))\n            pha.save(os.path.join(out_path, 'pha', str(t).zfill(4) + '.png'))\n        \n        bgr = Image.fromarray(bgrs[t])\n        bgr = bgr.resize(fgr.size, Image.BILINEAR)\n        bgr.save(os.path.join(out_path, 'bgr', str(t).zfill(4) + '.png'))\n        \n        pha = np.asarray(pha).astype(float)[:, :, None] / 255\n        com = Image.fromarray(np.uint8(np.asarray(fgr) * pha + np.asarray(bgr) * (1 - pha)))\n        com.save(os.path.join(out_path, 'com', str(t).zfill(4) + '.png'))\n"
  },
  {
    "path": "hubconf.py",
    "content": "\"\"\"\nLoading model\n    model = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"mobilenetv3\")\n    model = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"resnet50\")\n\nConverter API\n    convert_video = torch.hub.load(\"PeterL1n/RobustVideoMatting\", \"converter\")\n\"\"\"\n\n\ndependencies = ['torch', 'torchvision']\n\nimport torch\nfrom model import MattingNetwork\n\n\ndef mobilenetv3(pretrained: bool = True, progress: bool = True):\n    model = MattingNetwork('mobilenetv3')\n    if pretrained:\n        url = 'https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_mobilenetv3.pth'\n        model.load_state_dict(torch.hub.load_state_dict_from_url(url, map_location='cpu', progress=progress))\n    return model\n\n\ndef resnet50(pretrained: bool = True, progress: bool = True):\n    model = MattingNetwork('resnet50')\n    if pretrained:\n        url = 'https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/rvm_resnet50.pth'\n        model.load_state_dict(torch.hub.load_state_dict_from_url(url, map_location='cpu', progress=progress))\n    return model\n\n\ndef converter():\n    try:\n        from inference import convert_video\n        return convert_video\n    except ModuleNotFoundError as error:\n        print(error)\n        print('Please run \"pip install av tqdm pims\"')\n"
  },
  {
    "path": "inference.py",
    "content": "\"\"\"\npython inference.py \\\n    --variant mobilenetv3 \\\n    --checkpoint \"CHECKPOINT\" \\\n    --device cuda \\\n    --input-source \"input.mp4\" \\\n    --output-type video \\\n    --output-composition \"composition.mp4\" \\\n    --output-alpha \"alpha.mp4\" \\\n    --output-foreground \"foreground.mp4\" \\\n    --output-video-mbps 4 \\\n    --seq-chunk 1\n\"\"\"\n\nimport torch\nimport os\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom typing import Optional, Tuple\nfrom tqdm.auto import tqdm\n\nfrom inference_utils import VideoReader, VideoWriter, ImageSequenceReader, ImageSequenceWriter\n\ndef convert_video(model,\n                  input_source: str,\n                  input_resize: Optional[Tuple[int, int]] = None,\n                  downsample_ratio: Optional[float] = None,\n                  output_type: str = 'video',\n                  output_composition: Optional[str] = None,\n                  output_alpha: Optional[str] = None,\n                  output_foreground: Optional[str] = None,\n                  output_video_mbps: Optional[float] = None,\n                  seq_chunk: int = 1,\n                  num_workers: int = 0,\n                  progress: bool = True,\n                  device: Optional[str] = None,\n                  dtype: Optional[torch.dtype] = None):\n    \n    \"\"\"\n    Args:\n        input_source:A video file, or an image sequence directory. Images must be sorted in accending order, support png and jpg.\n        input_resize: If provided, the input are first resized to (w, h).\n        downsample_ratio: The model's downsample_ratio hyperparameter. If not provided, model automatically set one.\n        output_type: Options: [\"video\", \"png_sequence\"].\n        output_composition:\n            The composition output path. File path if output_type == 'video'. Directory path if output_type == 'png_sequence'.\n            If output_type == 'video', the composition has green screen background.\n            If output_type == 'png_sequence'. the composition is RGBA png images.\n        output_alpha: The alpha output from the model.\n        output_foreground: The foreground output from the model.\n        seq_chunk: Number of frames to process at once. Increase it for better parallelism.\n        num_workers: PyTorch's DataLoader workers. Only use >0 for image input.\n        progress: Show progress bar.\n        device: Only need to manually provide if model is a TorchScript freezed model.\n        dtype: Only need to manually provide if model is a TorchScript freezed model.\n    \"\"\"\n    \n    assert downsample_ratio is None or (downsample_ratio > 0 and downsample_ratio <= 1), 'Downsample ratio must be between 0 (exclusive) and 1 (inclusive).'\n    assert any([output_composition, output_alpha, output_foreground]), 'Must provide at least one output.'\n    assert output_type in ['video', 'png_sequence'], 'Only support \"video\" and \"png_sequence\" output modes.'\n    assert seq_chunk >= 1, 'Sequence chunk must be >= 1'\n    assert num_workers >= 0, 'Number of workers must be >= 0'\n    \n    # Initialize transform\n    if input_resize is not None:\n        transform = transforms.Compose([\n            transforms.Resize(input_resize[::-1]),\n            transforms.ToTensor()\n        ])\n    else:\n        transform = transforms.ToTensor()\n\n    # Initialize reader\n    if os.path.isfile(input_source):\n        source = VideoReader(input_source, transform)\n    else:\n        source = ImageSequenceReader(input_source, transform)\n    reader = DataLoader(source, batch_size=seq_chunk, pin_memory=True, num_workers=num_workers)\n    \n    # Initialize writers\n    if output_type == 'video':\n        frame_rate = source.frame_rate if isinstance(source, VideoReader) else 30\n        output_video_mbps = 1 if output_video_mbps is None else output_video_mbps\n        if output_composition is not None:\n            writer_com = VideoWriter(\n                path=output_composition,\n                frame_rate=frame_rate,\n                bit_rate=int(output_video_mbps * 1000000))\n        if output_alpha is not None:\n            writer_pha = VideoWriter(\n                path=output_alpha,\n                frame_rate=frame_rate,\n                bit_rate=int(output_video_mbps * 1000000))\n        if output_foreground is not None:\n            writer_fgr = VideoWriter(\n                path=output_foreground,\n                frame_rate=frame_rate,\n                bit_rate=int(output_video_mbps * 1000000))\n    else:\n        if output_composition is not None:\n            writer_com = ImageSequenceWriter(output_composition, 'png')\n        if output_alpha is not None:\n            writer_pha = ImageSequenceWriter(output_alpha, 'png')\n        if output_foreground is not None:\n            writer_fgr = ImageSequenceWriter(output_foreground, 'png')\n\n    # Inference\n    model = model.eval()\n    if device is None or dtype is None:\n        param = next(model.parameters())\n        dtype = param.dtype\n        device = param.device\n    \n    if (output_composition is not None) and (output_type == 'video'):\n        bgr = torch.tensor([120, 255, 155], device=device, dtype=dtype).div(255).view(1, 1, 3, 1, 1)\n    \n    try:\n        with torch.no_grad():\n            bar = tqdm(total=len(source), disable=not progress, dynamic_ncols=True)\n            rec = [None] * 4\n            for src in reader:\n\n                if downsample_ratio is None:\n                    downsample_ratio = auto_downsample_ratio(*src.shape[2:])\n\n                src = src.to(device, dtype, non_blocking=True).unsqueeze(0) # [B, T, C, H, W]\n                fgr, pha, *rec = model(src, *rec, downsample_ratio)\n\n                if output_foreground is not None:\n                    writer_fgr.write(fgr[0])\n                if output_alpha is not None:\n                    writer_pha.write(pha[0])\n                if output_composition is not None:\n                    if output_type == 'video':\n                        com = fgr * pha + bgr * (1 - pha)\n                    else:\n                        fgr = fgr * pha.gt(0)\n                        com = torch.cat([fgr, pha], dim=-3)\n                    writer_com.write(com[0])\n                \n                bar.update(src.size(1))\n\n    finally:\n        # Clean up\n        if output_composition is not None:\n            writer_com.close()\n        if output_alpha is not None:\n            writer_pha.close()\n        if output_foreground is not None:\n            writer_fgr.close()\n\n\ndef auto_downsample_ratio(h, w):\n    \"\"\"\n    Automatically find a downsample ratio so that the largest side of the resolution be 512px.\n    \"\"\"\n    return min(512 / max(h, w), 1)\n\n\nclass Converter:\n    def __init__(self, variant: str, checkpoint: str, device: str):\n        self.model = MattingNetwork(variant).eval().to(device)\n        self.model.load_state_dict(torch.load(checkpoint, map_location=device))\n        self.model = torch.jit.script(self.model)\n        self.model = torch.jit.freeze(self.model)\n        self.device = device\n    \n    def convert(self, *args, **kwargs):\n        convert_video(self.model, device=self.device, dtype=torch.float32, *args, **kwargs)\n    \nif __name__ == '__main__':\n    import argparse\n    from model import MattingNetwork\n    \n    parser = argparse.ArgumentParser()\n    parser.add_argument('--variant', type=str, required=True, choices=['mobilenetv3', 'resnet50'])\n    parser.add_argument('--checkpoint', type=str, required=True)\n    parser.add_argument('--device', type=str, required=True)\n    parser.add_argument('--input-source', type=str, required=True)\n    parser.add_argument('--input-resize', type=int, default=None, nargs=2)\n    parser.add_argument('--downsample-ratio', type=float)\n    parser.add_argument('--output-composition', type=str)\n    parser.add_argument('--output-alpha', type=str)\n    parser.add_argument('--output-foreground', type=str)\n    parser.add_argument('--output-type', type=str, required=True, choices=['video', 'png_sequence'])\n    parser.add_argument('--output-video-mbps', type=int, default=1)\n    parser.add_argument('--seq-chunk', type=int, default=1)\n    parser.add_argument('--num-workers', type=int, default=0)\n    parser.add_argument('--disable-progress', action='store_true')\n    args = parser.parse_args()\n    \n    converter = Converter(args.variant, args.checkpoint, args.device)\n    converter.convert(\n        input_source=args.input_source,\n        input_resize=args.input_resize,\n        downsample_ratio=args.downsample_ratio,\n        output_type=args.output_type,\n        output_composition=args.output_composition,\n        output_alpha=args.output_alpha,\n        output_foreground=args.output_foreground,\n        output_video_mbps=args.output_video_mbps,\n        seq_chunk=args.seq_chunk,\n        num_workers=args.num_workers,\n        progress=not args.disable_progress\n    )\n    \n    \n"
  },
  {
    "path": "inference_speed_test.py",
    "content": "\"\"\"\npython inference_speed_test.py \\\n    --model-variant mobilenetv3 \\\n    --resolution 1920 1080 \\\n    --downsample-ratio 0.25 \\\n    --precision float32\n\"\"\"\n\nimport argparse\nimport torch\nfrom tqdm import tqdm\n\nfrom model.model import MattingNetwork\n\ntorch.backends.cudnn.benchmark = True\n\nclass InferenceSpeedTest:\n    def __init__(self):\n        self.parse_args()\n        self.init_model()\n        self.loop()\n        \n    def parse_args(self):\n        parser = argparse.ArgumentParser()\n        parser.add_argument('--model-variant', type=str, required=True)\n        parser.add_argument('--resolution', type=int, required=True, nargs=2)\n        parser.add_argument('--downsample-ratio', type=float, required=True)\n        parser.add_argument('--precision', type=str, default='float32')\n        parser.add_argument('--disable-refiner', action='store_true')\n        self.args = parser.parse_args()\n        \n    def init_model(self):\n        self.device = 'cuda'\n        self.precision = {'float32': torch.float32, 'float16': torch.float16}[self.args.precision]\n        self.model = MattingNetwork(self.args.model_variant)\n        self.model = self.model.to(device=self.device, dtype=self.precision).eval()\n        self.model = torch.jit.script(self.model)\n        self.model = torch.jit.freeze(self.model)\n    \n    def loop(self):\n        w, h = self.args.resolution\n        src = torch.randn((1, 3, h, w), device=self.device, dtype=self.precision)\n        with torch.no_grad():\n            rec = None, None, None, None\n            for _ in tqdm(range(1000)):\n                fgr, pha, *rec = self.model(src, *rec, self.args.downsample_ratio)\n                torch.cuda.synchronize()\n\nif __name__ == '__main__':\n    InferenceSpeedTest()"
  },
  {
    "path": "inference_utils.py",
    "content": "import av\nimport os\nimport pims\nimport numpy as np\nfrom torch.utils.data import Dataset\nfrom torchvision.transforms.functional import to_pil_image\nfrom PIL import Image\n\n\nclass VideoReader(Dataset):\n    def __init__(self, path, transform=None):\n        self.video = pims.PyAVVideoReader(path)\n        self.rate = self.video.frame_rate\n        self.transform = transform\n        \n    @property\n    def frame_rate(self):\n        return self.rate\n        \n    def __len__(self):\n        return len(self.video)\n        \n    def __getitem__(self, idx):\n        frame = self.video[idx]\n        frame = Image.fromarray(np.asarray(frame))\n        if self.transform is not None:\n            frame = self.transform(frame)\n        return frame\n\n\nclass VideoWriter:\n    def __init__(self, path, frame_rate, bit_rate=1000000):\n        self.container = av.open(path, mode='w')\n        self.stream = self.container.add_stream('h264', rate=f'{frame_rate:.4f}')\n        self.stream.pix_fmt = 'yuv420p'\n        self.stream.bit_rate = bit_rate\n    \n    def write(self, frames):\n        # frames: [T, C, H, W]\n        self.stream.width = frames.size(3)\n        self.stream.height = frames.size(2)\n        if frames.size(1) == 1:\n            frames = frames.repeat(1, 3, 1, 1) # convert grayscale to RGB\n        frames = frames.mul(255).byte().cpu().permute(0, 2, 3, 1).numpy()\n        for t in range(frames.shape[0]):\n            frame = frames[t]\n            frame = av.VideoFrame.from_ndarray(frame, format='rgb24')\n            self.container.mux(self.stream.encode(frame))\n                \n    def close(self):\n        self.container.mux(self.stream.encode())\n        self.container.close()\n\n\nclass ImageSequenceReader(Dataset):\n    def __init__(self, path, transform=None):\n        self.path = path\n        self.files = sorted(os.listdir(path))\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.files)\n    \n    def __getitem__(self, idx):\n        with Image.open(os.path.join(self.path, self.files[idx])) as img:\n            img.load()\n        if self.transform is not None:\n            return self.transform(img)\n        return img\n\n\nclass ImageSequenceWriter:\n    def __init__(self, path, extension='jpg'):\n        self.path = path\n        self.extension = extension\n        self.counter = 0\n        os.makedirs(path, exist_ok=True)\n    \n    def write(self, frames):\n        # frames: [T, C, H, W]\n        for t in range(frames.shape[0]):\n            to_pil_image(frames[t]).save(os.path.join(\n                self.path, str(self.counter).zfill(4) + '.' + self.extension))\n            self.counter += 1\n            \n    def close(self):\n        pass\n        \n"
  },
  {
    "path": "model/__init__.py",
    "content": "from .model import MattingNetwork"
  },
  {
    "path": "model/decoder.py",
    "content": "import torch\nfrom torch import Tensor\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom typing import Tuple, Optional\n\nclass RecurrentDecoder(nn.Module):\n    def __init__(self, feature_channels, decoder_channels):\n        super().__init__()\n        self.avgpool = AvgPool()\n        self.decode4 = BottleneckBlock(feature_channels[3])\n        self.decode3 = UpsamplingBlock(feature_channels[3], feature_channels[2], 3, decoder_channels[0])\n        self.decode2 = UpsamplingBlock(decoder_channels[0], feature_channels[1], 3, decoder_channels[1])\n        self.decode1 = UpsamplingBlock(decoder_channels[1], feature_channels[0], 3, decoder_channels[2])\n        self.decode0 = OutputBlock(decoder_channels[2], 3, decoder_channels[3])\n\n    def forward(self,\n                s0: Tensor, f1: Tensor, f2: Tensor, f3: Tensor, f4: Tensor,\n                r1: Optional[Tensor], r2: Optional[Tensor],\n                r3: Optional[Tensor], r4: Optional[Tensor]):\n        s1, s2, s3 = self.avgpool(s0)\n        x4, r4 = self.decode4(f4, r4)\n        x3, r3 = self.decode3(x4, f3, s3, r3)\n        x2, r2 = self.decode2(x3, f2, s2, r2)\n        x1, r1 = self.decode1(x2, f1, s1, r1)\n        x0 = self.decode0(x1, s0)\n        return x0, r1, r2, r3, r4\n    \n\nclass AvgPool(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.avgpool = nn.AvgPool2d(2, 2, count_include_pad=False, ceil_mode=True)\n        \n    def forward_single_frame(self, s0):\n        s1 = self.avgpool(s0)\n        s2 = self.avgpool(s1)\n        s3 = self.avgpool(s2)\n        return s1, s2, s3\n    \n    def forward_time_series(self, s0):\n        B, T = s0.shape[:2]\n        s0 = s0.flatten(0, 1)\n        s1, s2, s3 = self.forward_single_frame(s0)\n        s1 = s1.unflatten(0, (B, T))\n        s2 = s2.unflatten(0, (B, T))\n        s3 = s3.unflatten(0, (B, T))\n        return s1, s2, s3\n    \n    def forward(self, s0):\n        if s0.ndim == 5:\n            return self.forward_time_series(s0)\n        else:\n            return self.forward_single_frame(s0)\n\n\nclass BottleneckBlock(nn.Module):\n    def __init__(self, channels):\n        super().__init__()\n        self.channels = channels\n        self.gru = ConvGRU(channels // 2)\n        \n    def forward(self, x, r: Optional[Tensor]):\n        a, b = x.split(self.channels // 2, dim=-3)\n        b, r = self.gru(b, r)\n        x = torch.cat([a, b], dim=-3)\n        return x, r\n\n    \nclass UpsamplingBlock(nn.Module):\n    def __init__(self, in_channels, skip_channels, src_channels, out_channels):\n        super().__init__()\n        self.out_channels = out_channels\n        self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)\n        self.conv = nn.Sequential(\n            nn.Conv2d(in_channels + skip_channels + src_channels, out_channels, 3, 1, 1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(True),\n        )\n        self.gru = ConvGRU(out_channels // 2)\n\n    def forward_single_frame(self, x, f, s, r: Optional[Tensor]):\n        x = self.upsample(x)\n        x = x[:, :, :s.size(2), :s.size(3)]\n        x = torch.cat([x, f, s], dim=1)\n        x = self.conv(x)\n        a, b = x.split(self.out_channels // 2, dim=1)\n        b, r = self.gru(b, r)\n        x = torch.cat([a, b], dim=1)\n        return x, r\n    \n    def forward_time_series(self, x, f, s, r: Optional[Tensor]):\n        B, T, _, H, W = s.shape\n        x = x.flatten(0, 1)\n        f = f.flatten(0, 1)\n        s = s.flatten(0, 1)\n        x = self.upsample(x)\n        x = x[:, :, :H, :W]\n        x = torch.cat([x, f, s], dim=1)\n        x = self.conv(x)\n        x = x.unflatten(0, (B, T))\n        a, b = x.split(self.out_channels // 2, dim=2)\n        b, r = self.gru(b, r)\n        x = torch.cat([a, b], dim=2)\n        return x, r\n    \n    def forward(self, x, f, s, r: Optional[Tensor]):\n        if x.ndim == 5:\n            return self.forward_time_series(x, f, s, r)\n        else:\n            return self.forward_single_frame(x, f, s, r)\n\n\nclass OutputBlock(nn.Module):\n    def __init__(self, in_channels, src_channels, out_channels):\n        super().__init__()\n        self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)\n        self.conv = nn.Sequential(\n            nn.Conv2d(in_channels + src_channels, out_channels, 3, 1, 1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(True),\n            nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(True),\n        )\n        \n    def forward_single_frame(self, x, s):\n        x = self.upsample(x)\n        x = x[:, :, :s.size(2), :s.size(3)]\n        x = torch.cat([x, s], dim=1)\n        x = self.conv(x)\n        return x\n    \n    def forward_time_series(self, x, s):\n        B, T, _, H, W = s.shape\n        x = x.flatten(0, 1)\n        s = s.flatten(0, 1)\n        x = self.upsample(x)\n        x = x[:, :, :H, :W]\n        x = torch.cat([x, s], dim=1)\n        x = self.conv(x)\n        x = x.unflatten(0, (B, T))\n        return x\n    \n    def forward(self, x, s):\n        if x.ndim == 5:\n            return self.forward_time_series(x, s)\n        else:\n            return self.forward_single_frame(x, s)\n\n\nclass ConvGRU(nn.Module):\n    def __init__(self,\n                 channels: int,\n                 kernel_size: int = 3,\n                 padding: int = 1):\n        super().__init__()\n        self.channels = channels\n        self.ih = nn.Sequential(\n            nn.Conv2d(channels * 2, channels * 2, kernel_size, padding=padding),\n            nn.Sigmoid()\n        )\n        self.hh = nn.Sequential(\n            nn.Conv2d(channels * 2, channels, kernel_size, padding=padding),\n            nn.Tanh()\n        )\n        \n    def forward_single_frame(self, x, h):\n        r, z = self.ih(torch.cat([x, h], dim=1)).split(self.channels, dim=1)\n        c = self.hh(torch.cat([x, r * h], dim=1))\n        h = (1 - z) * h + z * c\n        return h, h\n    \n    def forward_time_series(self, x, h):\n        o = []\n        for xt in x.unbind(dim=1):\n            ot, h = self.forward_single_frame(xt, h)\n            o.append(ot)\n        o = torch.stack(o, dim=1)\n        return o, h\n        \n    def forward(self, x, h: Optional[Tensor]):\n        if h is None:\n            h = torch.zeros((x.size(0), x.size(-3), x.size(-2), x.size(-1)),\n                            device=x.device, dtype=x.dtype)\n        \n        if x.ndim == 5:\n            return self.forward_time_series(x, h)\n        else:\n            return self.forward_single_frame(x, h)\n\n\nclass Projection(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super().__init__()\n        self.conv = nn.Conv2d(in_channels, out_channels, 1)\n    \n    def forward_single_frame(self, x):\n        return self.conv(x)\n    \n    def forward_time_series(self, x):\n        B, T = x.shape[:2]\n        return self.conv(x.flatten(0, 1)).unflatten(0, (B, T))\n        \n    def forward(self, x):\n        if x.ndim == 5:\n            return self.forward_time_series(x)\n        else:\n            return self.forward_single_frame(x)\n    "
  },
  {
    "path": "model/deep_guided_filter.py",
    "content": "import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\"\"\"\nAdopted from <https://github.com/wuhuikai/DeepGuidedFilter/>\n\"\"\"\n\nclass DeepGuidedFilterRefiner(nn.Module):\n    def __init__(self, hid_channels=16):\n        super().__init__()\n        self.box_filter = nn.Conv2d(4, 4, kernel_size=3, padding=1, bias=False, groups=4)\n        self.box_filter.weight.data[...] = 1 / 9\n        self.conv = nn.Sequential(\n            nn.Conv2d(4 * 2 + hid_channels, hid_channels, kernel_size=1, bias=False),\n            nn.BatchNorm2d(hid_channels),\n            nn.ReLU(True),\n            nn.Conv2d(hid_channels, hid_channels, kernel_size=1, bias=False),\n            nn.BatchNorm2d(hid_channels),\n            nn.ReLU(True),\n            nn.Conv2d(hid_channels, 4, kernel_size=1, bias=True)\n        )\n        \n    def forward_single_frame(self, fine_src, base_src, base_fgr, base_pha, base_hid):\n        fine_x = torch.cat([fine_src, fine_src.mean(1, keepdim=True)], dim=1)\n        base_x = torch.cat([base_src, base_src.mean(1, keepdim=True)], dim=1)\n        base_y = torch.cat([base_fgr, base_pha], dim=1)\n        \n        mean_x = self.box_filter(base_x)\n        mean_y = self.box_filter(base_y)\n        cov_xy = self.box_filter(base_x * base_y) - mean_x * mean_y\n        var_x  = self.box_filter(base_x * base_x) - mean_x * mean_x\n        \n        A = self.conv(torch.cat([cov_xy, var_x, base_hid], dim=1))\n        b = mean_y - A * mean_x\n        \n        H, W = fine_src.shape[2:]\n        A = F.interpolate(A, (H, W), mode='bilinear', align_corners=False)\n        b = F.interpolate(b, (H, W), mode='bilinear', align_corners=False)\n        \n        out = A * fine_x + b\n        fgr, pha = out.split([3, 1], dim=1)\n        return fgr, pha\n    \n    def forward_time_series(self, fine_src, base_src, base_fgr, base_pha, base_hid):\n        B, T = fine_src.shape[:2]\n        fgr, pha = self.forward_single_frame(\n            fine_src.flatten(0, 1),\n            base_src.flatten(0, 1),\n            base_fgr.flatten(0, 1),\n            base_pha.flatten(0, 1),\n            base_hid.flatten(0, 1))\n        fgr = fgr.unflatten(0, (B, T))\n        pha = pha.unflatten(0, (B, T))\n        return fgr, pha\n    \n    def forward(self, fine_src, base_src, base_fgr, base_pha, base_hid):\n        if fine_src.ndim == 5:\n            return self.forward_time_series(fine_src, base_src, base_fgr, base_pha, base_hid)\n        else:\n            return self.forward_single_frame(fine_src, base_src, base_fgr, base_pha, base_hid)\n"
  },
  {
    "path": "model/fast_guided_filter.py",
    "content": "import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\"\"\"\nAdopted from <https://github.com/wuhuikai/DeepGuidedFilter/>\n\"\"\"\n\nclass FastGuidedFilterRefiner(nn.Module):\n    def __init__(self, *args, **kwargs):\n        super().__init__()\n        self.guilded_filter = FastGuidedFilter(1)\n    \n    def forward_single_frame(self, fine_src, base_src, base_fgr, base_pha):\n        fine_src_gray = fine_src.mean(1, keepdim=True)\n        base_src_gray = base_src.mean(1, keepdim=True)\n        \n        fgr, pha = self.guilded_filter(\n            torch.cat([base_src, base_src_gray], dim=1),\n            torch.cat([base_fgr, base_pha], dim=1),\n            torch.cat([fine_src, fine_src_gray], dim=1)).split([3, 1], dim=1)\n        \n        return fgr, pha\n    \n    def forward_time_series(self, fine_src, base_src, base_fgr, base_pha):\n        B, T = fine_src.shape[:2]\n        fgr, pha = self.forward_single_frame(\n            fine_src.flatten(0, 1),\n            base_src.flatten(0, 1),\n            base_fgr.flatten(0, 1),\n            base_pha.flatten(0, 1))\n        fgr = fgr.unflatten(0, (B, T))\n        pha = pha.unflatten(0, (B, T))\n        return fgr, pha\n    \n    def forward(self, fine_src, base_src, base_fgr, base_pha, base_hid):\n        if fine_src.ndim == 5:\n            return self.forward_time_series(fine_src, base_src, base_fgr, base_pha)\n        else:\n            return self.forward_single_frame(fine_src, base_src, base_fgr, base_pha)\n\n\nclass FastGuidedFilter(nn.Module):\n    def __init__(self, r: int, eps: float = 1e-5):\n        super().__init__()\n        self.r = r\n        self.eps = eps\n        self.boxfilter = BoxFilter(r)\n\n    def forward(self, lr_x, lr_y, hr_x):\n        mean_x = self.boxfilter(lr_x)\n        mean_y = self.boxfilter(lr_y)\n        cov_xy = self.boxfilter(lr_x * lr_y) - mean_x * mean_y\n        var_x = self.boxfilter(lr_x * lr_x) - mean_x * mean_x\n        A = cov_xy / (var_x + self.eps)\n        b = mean_y - A * mean_x\n        A = F.interpolate(A, hr_x.shape[2:], mode='bilinear', align_corners=False)\n        b = F.interpolate(b, hr_x.shape[2:], mode='bilinear', align_corners=False)\n        return A * hr_x + b\n\n\nclass BoxFilter(nn.Module):\n    def __init__(self, r):\n        super(BoxFilter, self).__init__()\n        self.r = r\n\n    def forward(self, x):\n        # Note: The original implementation at <https://github.com/wuhuikai/DeepGuidedFilter/>\n        #       uses faster box blur. However, it may not be friendly for ONNX export.\n        #       We are switching to use simple convolution for box blur.\n        kernel_size = 2 * self.r + 1\n        kernel_x = torch.full((x.data.shape[1], 1, 1, kernel_size), 1 / kernel_size, device=x.device, dtype=x.dtype)\n        kernel_y = torch.full((x.data.shape[1], 1, kernel_size, 1), 1 / kernel_size, device=x.device, dtype=x.dtype)\n        x = F.conv2d(x, kernel_x, padding=(0, self.r), groups=x.data.shape[1])\n        x = F.conv2d(x, kernel_y, padding=(self.r, 0), groups=x.data.shape[1])\n        return x"
  },
  {
    "path": "model/lraspp.py",
    "content": "from torch import nn\n\nclass LRASPP(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super().__init__()\n        self.aspp1 = nn.Sequential(\n            nn.Conv2d(in_channels, out_channels, 1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(True)\n        )\n        self.aspp2 = nn.Sequential(\n            nn.AdaptiveAvgPool2d(1),\n            nn.Conv2d(in_channels, out_channels, 1, bias=False),\n            nn.Sigmoid()\n        )\n        \n    def forward_single_frame(self, x):\n        return self.aspp1(x) * self.aspp2(x)\n    \n    def forward_time_series(self, x):\n        B, T = x.shape[:2]\n        x = self.forward_single_frame(x.flatten(0, 1)).unflatten(0, (B, T))\n        return x\n    \n    def forward(self, x):\n        if x.ndim == 5:\n            return self.forward_time_series(x)\n        else:\n            return self.forward_single_frame(x)"
  },
  {
    "path": "model/mobilenetv3.py",
    "content": "import torch\nfrom torch import nn\nfrom torchvision.models.mobilenetv3 import MobileNetV3, InvertedResidualConfig\nfrom torchvision.transforms.functional import normalize\n\nclass MobileNetV3LargeEncoder(MobileNetV3):\n    def __init__(self, pretrained: bool = False):\n        super().__init__(\n            inverted_residual_setting=[\n                InvertedResidualConfig( 16, 3,  16,  16, False, \"RE\", 1, 1, 1),\n                InvertedResidualConfig( 16, 3,  64,  24, False, \"RE\", 2, 1, 1),  # C1\n                InvertedResidualConfig( 24, 3,  72,  24, False, \"RE\", 1, 1, 1),\n                InvertedResidualConfig( 24, 5,  72,  40,  True, \"RE\", 2, 1, 1),  # C2\n                InvertedResidualConfig( 40, 5, 120,  40,  True, \"RE\", 1, 1, 1),\n                InvertedResidualConfig( 40, 5, 120,  40,  True, \"RE\", 1, 1, 1),\n                InvertedResidualConfig( 40, 3, 240,  80, False, \"HS\", 2, 1, 1),  # C3\n                InvertedResidualConfig( 80, 3, 200,  80, False, \"HS\", 1, 1, 1),\n                InvertedResidualConfig( 80, 3, 184,  80, False, \"HS\", 1, 1, 1),\n                InvertedResidualConfig( 80, 3, 184,  80, False, \"HS\", 1, 1, 1),\n                InvertedResidualConfig( 80, 3, 480, 112,  True, \"HS\", 1, 1, 1),\n                InvertedResidualConfig(112, 3, 672, 112,  True, \"HS\", 1, 1, 1),\n                InvertedResidualConfig(112, 5, 672, 160,  True, \"HS\", 2, 2, 1),  # C4\n                InvertedResidualConfig(160, 5, 960, 160,  True, \"HS\", 1, 2, 1),\n                InvertedResidualConfig(160, 5, 960, 160,  True, \"HS\", 1, 2, 1),\n            ],\n            last_channel=1280\n        )\n        \n        if pretrained:\n            self.load_state_dict(torch.hub.load_state_dict_from_url(\n                'https://download.pytorch.org/models/mobilenet_v3_large-8738ca79.pth'))\n\n        del self.avgpool\n        del self.classifier\n        \n    def forward_single_frame(self, x):\n        x = normalize(x, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n        \n        x = self.features[0](x)\n        x = self.features[1](x)\n        f1 = x\n        x = self.features[2](x)\n        x = self.features[3](x)\n        f2 = x\n        x = self.features[4](x)\n        x = self.features[5](x)\n        x = self.features[6](x)\n        f3 = x\n        x = self.features[7](x)\n        x = self.features[8](x)\n        x = self.features[9](x)\n        x = self.features[10](x)\n        x = self.features[11](x)\n        x = self.features[12](x)\n        x = self.features[13](x)\n        x = self.features[14](x)\n        x = self.features[15](x)\n        x = self.features[16](x)\n        f4 = x\n        return [f1, f2, f3, f4]\n    \n    def forward_time_series(self, x):\n        B, T = x.shape[:2]\n        features = self.forward_single_frame(x.flatten(0, 1))\n        features = [f.unflatten(0, (B, T)) for f in features]\n        return features\n\n    def forward(self, x):\n        if x.ndim == 5:\n            return self.forward_time_series(x)\n        else:\n            return self.forward_single_frame(x)\n"
  },
  {
    "path": "model/model.py",
    "content": "import torch\nfrom torch import Tensor\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom typing import Optional, List\n\nfrom .mobilenetv3 import MobileNetV3LargeEncoder\nfrom .resnet import ResNet50Encoder\nfrom .lraspp import LRASPP\nfrom .decoder import RecurrentDecoder, Projection\nfrom .fast_guided_filter import FastGuidedFilterRefiner\nfrom .deep_guided_filter import DeepGuidedFilterRefiner\n\nclass MattingNetwork(nn.Module):\n    def __init__(self,\n                 variant: str = 'mobilenetv3',\n                 refiner: str = 'deep_guided_filter',\n                 pretrained_backbone: bool = False):\n        super().__init__()\n        assert variant in ['mobilenetv3', 'resnet50']\n        assert refiner in ['fast_guided_filter', 'deep_guided_filter']\n        \n        if variant == 'mobilenetv3':\n            self.backbone = MobileNetV3LargeEncoder(pretrained_backbone)\n            self.aspp = LRASPP(960, 128)\n            self.decoder = RecurrentDecoder([16, 24, 40, 128], [80, 40, 32, 16])\n        else:\n            self.backbone = ResNet50Encoder(pretrained_backbone)\n            self.aspp = LRASPP(2048, 256)\n            self.decoder = RecurrentDecoder([64, 256, 512, 256], [128, 64, 32, 16])\n            \n        self.project_mat = Projection(16, 4)\n        self.project_seg = Projection(16, 1)\n\n        if refiner == 'deep_guided_filter':\n            self.refiner = DeepGuidedFilterRefiner()\n        else:\n            self.refiner = FastGuidedFilterRefiner()\n        \n    def forward(self,\n                src: Tensor,\n                r1: Optional[Tensor] = None,\n                r2: Optional[Tensor] = None,\n                r3: Optional[Tensor] = None,\n                r4: Optional[Tensor] = None,\n                downsample_ratio: float = 1,\n                segmentation_pass: bool = False):\n        \n        if downsample_ratio != 1:\n            src_sm = self._interpolate(src, scale_factor=downsample_ratio)\n        else:\n            src_sm = src\n        \n        f1, f2, f3, f4 = self.backbone(src_sm)\n        f4 = self.aspp(f4)\n        hid, *rec = self.decoder(src_sm, f1, f2, f3, f4, r1, r2, r3, r4)\n        \n        if not segmentation_pass:\n            fgr_residual, pha = self.project_mat(hid).split([3, 1], dim=-3)\n            if downsample_ratio != 1:\n                fgr_residual, pha = self.refiner(src, src_sm, fgr_residual, pha, hid)\n            fgr = fgr_residual + src\n            fgr = fgr.clamp(0., 1.)\n            pha = pha.clamp(0., 1.)\n            return [fgr, pha, *rec]\n        else:\n            seg = self.project_seg(hid)\n            return [seg, *rec]\n\n    def _interpolate(self, x: Tensor, scale_factor: float):\n        if x.ndim == 5:\n            B, T = x.shape[:2]\n            x = F.interpolate(x.flatten(0, 1), scale_factor=scale_factor,\n                mode='bilinear', align_corners=False, recompute_scale_factor=False)\n            x = x.unflatten(0, (B, T))\n        else:\n            x = F.interpolate(x, scale_factor=scale_factor,\n                mode='bilinear', align_corners=False, recompute_scale_factor=False)\n        return x\n"
  },
  {
    "path": "model/resnet.py",
    "content": "import torch\nfrom torch import nn\nfrom torchvision.models.resnet import ResNet, Bottleneck\n\nclass ResNet50Encoder(ResNet):\n    def __init__(self, pretrained: bool = False):\n        super().__init__(\n            block=Bottleneck,\n            layers=[3, 4, 6, 3],\n            replace_stride_with_dilation=[False, False, True],\n            norm_layer=None)\n        \n        if pretrained:\n            self.load_state_dict(torch.hub.load_state_dict_from_url(\n                'https://download.pytorch.org/models/resnet50-0676ba61.pth'))\n        \n        del self.avgpool\n        del self.fc\n        \n    def forward_single_frame(self, x):\n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        f1 = x  # 1/2\n        x = self.maxpool(x)\n        x = self.layer1(x)\n        f2 = x  # 1/4\n        x = self.layer2(x)\n        f3 = x  # 1/8\n        x = self.layer3(x)\n        x = self.layer4(x)\n        f4 = x  # 1/16\n        return [f1, f2, f3, f4]\n    \n    def forward_time_series(self, x):\n        B, T = x.shape[:2]\n        features = self.forward_single_frame(x.flatten(0, 1))\n        features = [f.unflatten(0, (B, T)) for f in features]\n        return features\n    \n    def forward(self, x):\n        if x.ndim == 5:\n            return self.forward_time_series(x)\n        else:\n            return self.forward_single_frame(x)\n"
  },
  {
    "path": "requirements_inference.txt",
    "content": "av==8.0.3\ntorch==1.9.0\ntorchvision==0.10.0\ntqdm==4.61.1\npims==0.5"
  },
  {
    "path": "requirements_training.txt",
    "content": "easing_functions==1.0.4\ntensorboard==2.5.0\ntorch==1.9.0\ntorchvision==0.10.0\ntqdm==4.61.1"
  },
  {
    "path": "train.py",
    "content": "\"\"\"\n# First update `train_config.py` to set paths to your dataset locations.\n\n# You may want to change `--num-workers` according to your machine's memory.\n# The default num-workers=8 may cause dataloader to exit unexpectedly when\n# machine is out of memory.\n\n# Stage 1\npython train.py \\\n    --model-variant mobilenetv3 \\\n    --dataset videomatte \\\n    --resolution-lr 512 \\\n    --seq-length-lr 15 \\\n    --learning-rate-backbone 0.0001 \\\n    --learning-rate-aspp 0.0002 \\\n    --learning-rate-decoder 0.0002 \\\n    --learning-rate-refiner 0 \\\n    --checkpoint-dir checkpoint/stage1 \\\n    --log-dir log/stage1 \\\n    --epoch-start 0 \\\n    --epoch-end 20\n\n# Stage 2\npython train.py \\\n    --model-variant mobilenetv3 \\\n    --dataset videomatte \\\n    --resolution-lr 512 \\\n    --seq-length-lr 50 \\\n    --learning-rate-backbone 0.00005 \\\n    --learning-rate-aspp 0.0001 \\\n    --learning-rate-decoder 0.0001 \\\n    --learning-rate-refiner 0 \\\n    --checkpoint checkpoint/stage1/epoch-19.pth \\\n    --checkpoint-dir checkpoint/stage2 \\\n    --log-dir log/stage2 \\\n    --epoch-start 20 \\\n    --epoch-end 22\n    \n# Stage 3\npython train.py \\\n    --model-variant mobilenetv3 \\\n    --dataset videomatte \\\n    --train-hr \\\n    --resolution-lr 512 \\\n    --resolution-hr 2048 \\\n    --seq-length-lr 40 \\\n    --seq-length-hr 6 \\\n    --learning-rate-backbone 0.00001 \\\n    --learning-rate-aspp 0.00001 \\\n    --learning-rate-decoder 0.00001 \\\n    --learning-rate-refiner 0.0002 \\\n    --checkpoint checkpoint/stage2/epoch-21.pth \\\n    --checkpoint-dir checkpoint/stage3 \\\n    --log-dir log/stage3 \\\n    --epoch-start 22 \\\n    --epoch-end 23\n\n# Stage 4\npython train.py \\\n    --model-variant mobilenetv3 \\\n    --dataset imagematte \\\n    --train-hr \\\n    --resolution-lr 512 \\\n    --resolution-hr 2048 \\\n    --seq-length-lr 40 \\\n    --seq-length-hr 6 \\\n    --learning-rate-backbone 0.00001 \\\n    --learning-rate-aspp 0.00001 \\\n    --learning-rate-decoder 0.00005 \\\n    --learning-rate-refiner 0.0002 \\\n    --checkpoint checkpoint/stage3/epoch-22.pth \\\n    --checkpoint-dir checkpoint/stage4 \\\n    --log-dir log/stage4 \\\n    --epoch-start 23 \\\n    --epoch-end 28\n\"\"\"\n\n\nimport argparse\nimport torch\nimport random\nimport os\nfrom torch import nn\nfrom torch import distributed as dist\nfrom torch import multiprocessing as mp\nfrom torch.nn import functional as F\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.optim import Adam\nfrom torch.cuda.amp import autocast, GradScaler\nfrom torch.utils.data import DataLoader, ConcatDataset\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchvision.utils import make_grid\nfrom torchvision.transforms.functional import center_crop\nfrom tqdm import tqdm\n\nfrom dataset.videomatte import (\n    VideoMatteDataset,\n    VideoMatteTrainAugmentation,\n    VideoMatteValidAugmentation,\n)\nfrom dataset.imagematte import (\n    ImageMatteDataset,\n    ImageMatteAugmentation\n)\nfrom dataset.coco import (\n    CocoPanopticDataset,\n    CocoPanopticTrainAugmentation,\n)\nfrom dataset.spd import (\n    SuperviselyPersonDataset\n)\nfrom dataset.youtubevis import (\n    YouTubeVISDataset,\n    YouTubeVISAugmentation\n)\nfrom dataset.augmentation import (\n    TrainFrameSampler,\n    ValidFrameSampler\n)\nfrom model import MattingNetwork\nfrom train_config import DATA_PATHS\nfrom train_loss import matting_loss, segmentation_loss\n\n\nclass Trainer:\n    def __init__(self, rank, world_size):\n        self.parse_args()\n        self.init_distributed(rank, world_size)\n        self.init_datasets()\n        self.init_model()\n        self.init_writer()\n        self.train()\n        self.cleanup()\n        \n    def parse_args(self):\n        parser = argparse.ArgumentParser()\n        # Model\n        parser.add_argument('--model-variant', type=str, required=True, choices=['mobilenetv3', 'resnet50'])\n        # Matting dataset\n        parser.add_argument('--dataset', type=str, required=True, choices=['videomatte', 'imagematte'])\n        # Learning rate\n        parser.add_argument('--learning-rate-backbone', type=float, required=True)\n        parser.add_argument('--learning-rate-aspp', type=float, required=True)\n        parser.add_argument('--learning-rate-decoder', type=float, required=True)\n        parser.add_argument('--learning-rate-refiner', type=float, required=True)\n        # Training setting\n        parser.add_argument('--train-hr', action='store_true')\n        parser.add_argument('--resolution-lr', type=int, default=512)\n        parser.add_argument('--resolution-hr', type=int, default=2048)\n        parser.add_argument('--seq-length-lr', type=int, required=True)\n        parser.add_argument('--seq-length-hr', type=int, default=6)\n        parser.add_argument('--downsample-ratio', type=float, default=0.25)\n        parser.add_argument('--batch-size-per-gpu', type=int, default=1)\n        parser.add_argument('--num-workers', type=int, default=8)\n        parser.add_argument('--epoch-start', type=int, default=0)\n        parser.add_argument('--epoch-end', type=int, default=16)\n        # Tensorboard logging\n        parser.add_argument('--log-dir', type=str, required=True)\n        parser.add_argument('--log-train-loss-interval', type=int, default=20)\n        parser.add_argument('--log-train-images-interval', type=int, default=500)\n        # Checkpoint loading and saving\n        parser.add_argument('--checkpoint', type=str)\n        parser.add_argument('--checkpoint-dir', type=str, required=True)\n        parser.add_argument('--checkpoint-save-interval', type=int, default=500)\n        # Distributed\n        parser.add_argument('--distributed-addr', type=str, default='localhost')\n        parser.add_argument('--distributed-port', type=str, default='12355')\n        # Debugging\n        parser.add_argument('--disable-progress-bar', action='store_true')\n        parser.add_argument('--disable-validation', action='store_true')\n        parser.add_argument('--disable-mixed-precision', action='store_true')\n        self.args = parser.parse_args()\n        \n    def init_distributed(self, rank, world_size):\n        self.rank = rank\n        self.world_size = world_size\n        self.log('Initializing distributed')\n        os.environ['MASTER_ADDR'] = self.args.distributed_addr\n        os.environ['MASTER_PORT'] = self.args.distributed_port\n        dist.init_process_group(\"nccl\", rank=rank, world_size=world_size)\n    \n    def init_datasets(self):\n        self.log('Initializing matting datasets')\n        size_hr = (self.args.resolution_hr, self.args.resolution_hr)\n        size_lr = (self.args.resolution_lr, self.args.resolution_lr)\n        \n        # Matting datasets:\n        if self.args.dataset == 'videomatte':\n            self.dataset_lr_train = VideoMatteDataset(\n                videomatte_dir=DATA_PATHS['videomatte']['train'],\n                background_image_dir=DATA_PATHS['background_images']['train'],\n                background_video_dir=DATA_PATHS['background_videos']['train'],\n                size=self.args.resolution_lr,\n                seq_length=self.args.seq_length_lr,\n                seq_sampler=TrainFrameSampler(),\n                transform=VideoMatteTrainAugmentation(size_lr))\n            if self.args.train_hr:\n                self.dataset_hr_train = VideoMatteDataset(\n                    videomatte_dir=DATA_PATHS['videomatte']['train'],\n                    background_image_dir=DATA_PATHS['background_images']['train'],\n                    background_video_dir=DATA_PATHS['background_videos']['train'],\n                    size=self.args.resolution_hr,\n                    seq_length=self.args.seq_length_hr,\n                    seq_sampler=TrainFrameSampler(),\n                    transform=VideoMatteTrainAugmentation(size_hr))\n            self.dataset_valid = VideoMatteDataset(\n                videomatte_dir=DATA_PATHS['videomatte']['valid'],\n                background_image_dir=DATA_PATHS['background_images']['valid'],\n                background_video_dir=DATA_PATHS['background_videos']['valid'],\n                size=self.args.resolution_hr if self.args.train_hr else self.args.resolution_lr,\n                seq_length=self.args.seq_length_hr if self.args.train_hr else self.args.seq_length_lr,\n                seq_sampler=ValidFrameSampler(),\n                transform=VideoMatteValidAugmentation(size_hr if self.args.train_hr else size_lr))\n        else:\n            self.dataset_lr_train = ImageMatteDataset(\n                imagematte_dir=DATA_PATHS['imagematte']['train'],\n                background_image_dir=DATA_PATHS['background_images']['train'],\n                background_video_dir=DATA_PATHS['background_videos']['train'],\n                size=self.args.resolution_lr,\n                seq_length=self.args.seq_length_lr,\n                seq_sampler=TrainFrameSampler(),\n                transform=ImageMatteAugmentation(size_lr))\n            if self.args.train_hr:\n                self.dataset_hr_train = ImageMatteDataset(\n                    imagematte_dir=DATA_PATHS['imagematte']['train'],\n                    background_image_dir=DATA_PATHS['background_images']['train'],\n                    background_video_dir=DATA_PATHS['background_videos']['train'],\n                    size=self.args.resolution_hr,\n                    seq_length=self.args.seq_length_hr,\n                    seq_sampler=TrainFrameSampler(),\n                    transform=ImageMatteAugmentation(size_hr))\n            self.dataset_valid = ImageMatteDataset(\n                imagematte_dir=DATA_PATHS['imagematte']['valid'],\n                background_image_dir=DATA_PATHS['background_images']['valid'],\n                background_video_dir=DATA_PATHS['background_videos']['valid'],\n                size=self.args.resolution_hr if self.args.train_hr else self.args.resolution_lr,\n                seq_length=self.args.seq_length_hr if self.args.train_hr else self.args.seq_length_lr,\n                seq_sampler=ValidFrameSampler(),\n                transform=ImageMatteAugmentation(size_hr if self.args.train_hr else size_lr))\n            \n        # Matting dataloaders:\n        self.datasampler_lr_train = DistributedSampler(\n            dataset=self.dataset_lr_train,\n            rank=self.rank,\n            num_replicas=self.world_size,\n            shuffle=True)\n        self.dataloader_lr_train = DataLoader(\n            dataset=self.dataset_lr_train,\n            batch_size=self.args.batch_size_per_gpu,\n            num_workers=self.args.num_workers,\n            sampler=self.datasampler_lr_train,\n            pin_memory=True)\n        if self.args.train_hr:\n            self.datasampler_hr_train = DistributedSampler(\n                dataset=self.dataset_hr_train,\n                rank=self.rank,\n                num_replicas=self.world_size,\n                shuffle=True)\n            self.dataloader_hr_train = DataLoader(\n                dataset=self.dataset_hr_train,\n                batch_size=self.args.batch_size_per_gpu,\n                num_workers=self.args.num_workers,\n                sampler=self.datasampler_hr_train,\n                pin_memory=True)\n        self.dataloader_valid = DataLoader(\n            dataset=self.dataset_valid,\n            batch_size=self.args.batch_size_per_gpu,\n            num_workers=self.args.num_workers,\n            pin_memory=True)\n        \n        # Segementation datasets\n        self.log('Initializing image segmentation datasets')\n        self.dataset_seg_image = ConcatDataset([\n            CocoPanopticDataset(\n                imgdir=DATA_PATHS['coco_panoptic']['imgdir'],\n                anndir=DATA_PATHS['coco_panoptic']['anndir'],\n                annfile=DATA_PATHS['coco_panoptic']['annfile'],\n                transform=CocoPanopticTrainAugmentation(size_lr)),\n            SuperviselyPersonDataset(\n                imgdir=DATA_PATHS['spd']['imgdir'],\n                segdir=DATA_PATHS['spd']['segdir'],\n                transform=CocoPanopticTrainAugmentation(size_lr))\n        ])\n        self.datasampler_seg_image = DistributedSampler(\n            dataset=self.dataset_seg_image,\n            rank=self.rank,\n            num_replicas=self.world_size,\n            shuffle=True)\n        self.dataloader_seg_image = DataLoader(\n            dataset=self.dataset_seg_image,\n            batch_size=self.args.batch_size_per_gpu * self.args.seq_length_lr,\n            num_workers=self.args.num_workers,\n            sampler=self.datasampler_seg_image,\n            pin_memory=True)\n        \n        self.log('Initializing video segmentation datasets')\n        self.dataset_seg_video = YouTubeVISDataset(\n            videodir=DATA_PATHS['youtubevis']['videodir'],\n            annfile=DATA_PATHS['youtubevis']['annfile'],\n            size=self.args.resolution_lr,\n            seq_length=self.args.seq_length_lr,\n            seq_sampler=TrainFrameSampler(speed=[1]),\n            transform=YouTubeVISAugmentation(size_lr))\n        self.datasampler_seg_video = DistributedSampler(\n            dataset=self.dataset_seg_video,\n            rank=self.rank,\n            num_replicas=self.world_size,\n            shuffle=True)\n        self.dataloader_seg_video = DataLoader(\n            dataset=self.dataset_seg_video,\n            batch_size=self.args.batch_size_per_gpu,\n            num_workers=self.args.num_workers,\n            sampler=self.datasampler_seg_video,\n            pin_memory=True)\n        \n    def init_model(self):\n        self.log('Initializing model')\n        self.model = MattingNetwork(self.args.model_variant, pretrained_backbone=True).to(self.rank)\n        \n        if self.args.checkpoint:\n            self.log(f'Restoring from checkpoint: {self.args.checkpoint}')\n            self.log(self.model.load_state_dict(\n                torch.load(self.args.checkpoint, map_location=f'cuda:{self.rank}')))\n            \n        self.model = nn.SyncBatchNorm.convert_sync_batchnorm(self.model)\n        self.model_ddp = DDP(self.model, device_ids=[self.rank], broadcast_buffers=False, find_unused_parameters=True)\n        self.optimizer = Adam([\n            {'params': self.model.backbone.parameters(), 'lr': self.args.learning_rate_backbone},\n            {'params': self.model.aspp.parameters(), 'lr': self.args.learning_rate_aspp},\n            {'params': self.model.decoder.parameters(), 'lr': self.args.learning_rate_decoder},\n            {'params': self.model.project_mat.parameters(), 'lr': self.args.learning_rate_decoder},\n            {'params': self.model.project_seg.parameters(), 'lr': self.args.learning_rate_decoder},\n            {'params': self.model.refiner.parameters(), 'lr': self.args.learning_rate_refiner},\n        ])\n        self.scaler = GradScaler()\n        \n    def init_writer(self):\n        if self.rank == 0:\n            self.log('Initializing writer')\n            self.writer = SummaryWriter(self.args.log_dir)\n        \n    def train(self):\n        for epoch in range(self.args.epoch_start, self.args.epoch_end):\n            self.epoch = epoch\n            self.step = epoch * len(self.dataloader_lr_train)\n            \n            if not self.args.disable_validation:\n                self.validate()\n            \n            self.log(f'Training epoch: {epoch}')\n            for true_fgr, true_pha, true_bgr in tqdm(self.dataloader_lr_train, disable=self.args.disable_progress_bar, dynamic_ncols=True):\n                # Low resolution pass\n                self.train_mat(true_fgr, true_pha, true_bgr, downsample_ratio=1, tag='lr')\n\n                # High resolution pass\n                if self.args.train_hr:\n                    true_fgr, true_pha, true_bgr = self.load_next_mat_hr_sample()\n                    self.train_mat(true_fgr, true_pha, true_bgr, downsample_ratio=self.args.downsample_ratio, tag='hr')\n                \n                # Segmentation pass\n                if self.step % 2 == 0:\n                    true_img, true_seg = self.load_next_seg_video_sample()\n                    self.train_seg(true_img, true_seg, log_label='seg_video')\n                else:\n                    true_img, true_seg = self.load_next_seg_image_sample()\n                    self.train_seg(true_img.unsqueeze(1), true_seg.unsqueeze(1), log_label='seg_image')\n                    \n                if self.step % self.args.checkpoint_save_interval == 0:\n                    self.save()\n                    \n                self.step += 1\n                \n    def train_mat(self, true_fgr, true_pha, true_bgr, downsample_ratio, tag):\n        true_fgr = true_fgr.to(self.rank, non_blocking=True)\n        true_pha = true_pha.to(self.rank, non_blocking=True)\n        true_bgr = true_bgr.to(self.rank, non_blocking=True)\n        true_fgr, true_pha, true_bgr = self.random_crop(true_fgr, true_pha, true_bgr)\n        true_src = true_fgr * true_pha + true_bgr * (1 - true_pha)\n        \n        with autocast(enabled=not self.args.disable_mixed_precision):\n            pred_fgr, pred_pha = self.model_ddp(true_src, downsample_ratio=downsample_ratio)[:2]\n            loss = matting_loss(pred_fgr, pred_pha, true_fgr, true_pha)\n\n        self.scaler.scale(loss['total']).backward()\n        self.scaler.step(self.optimizer)\n        self.scaler.update()\n        self.optimizer.zero_grad()\n        \n        if self.rank == 0 and self.step % self.args.log_train_loss_interval == 0:\n            for loss_name, loss_value in loss.items():\n                self.writer.add_scalar(f'train_{tag}_{loss_name}', loss_value, self.step)\n            \n        if self.rank == 0 and self.step % self.args.log_train_images_interval == 0:\n            self.writer.add_image(f'train_{tag}_pred_fgr', make_grid(pred_fgr.flatten(0, 1), nrow=pred_fgr.size(1)), self.step)\n            self.writer.add_image(f'train_{tag}_pred_pha', make_grid(pred_pha.flatten(0, 1), nrow=pred_pha.size(1)), self.step)\n            self.writer.add_image(f'train_{tag}_true_fgr', make_grid(true_fgr.flatten(0, 1), nrow=true_fgr.size(1)), self.step)\n            self.writer.add_image(f'train_{tag}_true_pha', make_grid(true_pha.flatten(0, 1), nrow=true_pha.size(1)), self.step)\n            self.writer.add_image(f'train_{tag}_true_src', make_grid(true_src.flatten(0, 1), nrow=true_src.size(1)), self.step)\n            \n    def train_seg(self, true_img, true_seg, log_label):\n        true_img = true_img.to(self.rank, non_blocking=True)\n        true_seg = true_seg.to(self.rank, non_blocking=True)\n        \n        true_img, true_seg = self.random_crop(true_img, true_seg)\n        \n        with autocast(enabled=not self.args.disable_mixed_precision):\n            pred_seg = self.model_ddp(true_img, segmentation_pass=True)[0]\n            loss = segmentation_loss(pred_seg, true_seg)\n        \n        self.scaler.scale(loss).backward()\n        self.scaler.step(self.optimizer)\n        self.scaler.update()\n        self.optimizer.zero_grad()\n        \n        if self.rank == 0 and (self.step - self.step % 2) % self.args.log_train_loss_interval == 0:\n            self.writer.add_scalar(f'{log_label}_loss', loss, self.step)\n        \n        if self.rank == 0 and (self.step - self.step % 2) % self.args.log_train_images_interval == 0:\n            self.writer.add_image(f'{log_label}_pred_seg', make_grid(pred_seg.flatten(0, 1).float().sigmoid(), nrow=self.args.seq_length_lr), self.step)\n            self.writer.add_image(f'{log_label}_true_seg', make_grid(true_seg.flatten(0, 1), nrow=self.args.seq_length_lr), self.step)\n            self.writer.add_image(f'{log_label}_true_img', make_grid(true_img.flatten(0, 1), nrow=self.args.seq_length_lr), self.step)\n    \n    def load_next_mat_hr_sample(self):\n        try:\n            sample = next(self.dataiterator_mat_hr)\n        except:\n            self.datasampler_hr_train.set_epoch(self.datasampler_hr_train.epoch + 1)\n            self.dataiterator_mat_hr = iter(self.dataloader_hr_train)\n            sample = next(self.dataiterator_mat_hr)\n        return sample\n    \n    def load_next_seg_video_sample(self):\n        try:\n            sample = next(self.dataiterator_seg_video)\n        except:\n            self.datasampler_seg_video.set_epoch(self.datasampler_seg_video.epoch + 1)\n            self.dataiterator_seg_video = iter(self.dataloader_seg_video)\n            sample = next(self.dataiterator_seg_video)\n        return sample\n    \n    def load_next_seg_image_sample(self):\n        try:\n            sample = next(self.dataiterator_seg_image)\n        except:\n            self.datasampler_seg_image.set_epoch(self.datasampler_seg_image.epoch + 1)\n            self.dataiterator_seg_image = iter(self.dataloader_seg_image)\n            sample = next(self.dataiterator_seg_image)\n        return sample\n    \n    def validate(self):\n        if self.rank == 0:\n            self.log(f'Validating at the start of epoch: {self.epoch}')\n            self.model_ddp.eval()\n            total_loss, total_count = 0, 0\n            with torch.no_grad():\n                with autocast(enabled=not self.args.disable_mixed_precision):\n                    for true_fgr, true_pha, true_bgr in tqdm(self.dataloader_valid, disable=self.args.disable_progress_bar, dynamic_ncols=True):\n                        true_fgr = true_fgr.to(self.rank, non_blocking=True)\n                        true_pha = true_pha.to(self.rank, non_blocking=True)\n                        true_bgr = true_bgr.to(self.rank, non_blocking=True)\n                        true_src = true_fgr * true_pha + true_bgr * (1 - true_pha)\n                        batch_size = true_src.size(0)\n                        pred_fgr, pred_pha = self.model(true_src)[:2]\n                        total_loss += matting_loss(pred_fgr, pred_pha, true_fgr, true_pha)['total'].item() * batch_size\n                        total_count += batch_size\n            avg_loss = total_loss / total_count\n            self.log(f'Validation set average loss: {avg_loss}')\n            self.writer.add_scalar('valid_loss', avg_loss, self.step)\n            self.model_ddp.train()\n        dist.barrier()\n    \n    def random_crop(self, *imgs):\n        h, w = imgs[0].shape[-2:]\n        w = random.choice(range(w // 2, w))\n        h = random.choice(range(h // 2, h))\n        results = []\n        for img in imgs:\n            B, T = img.shape[:2]\n            img = img.flatten(0, 1)\n            img = F.interpolate(img, (max(h, w), max(h, w)), mode='bilinear', align_corners=False)\n            img = center_crop(img, (h, w))\n            img = img.reshape(B, T, *img.shape[1:])\n            results.append(img)\n        return results\n    \n    def save(self):\n        if self.rank == 0:\n            os.makedirs(self.args.checkpoint_dir, exist_ok=True)\n            torch.save(self.model.state_dict(), os.path.join(self.args.checkpoint_dir, f'epoch-{self.epoch}.pth'))\n            self.log('Model saved')\n        dist.barrier()\n        \n    def cleanup(self):\n        dist.destroy_process_group()\n        \n    def log(self, msg):\n        print(f'[GPU{self.rank}] {msg}')\n            \nif __name__ == '__main__':\n    world_size = torch.cuda.device_count()\n    mp.spawn(\n        Trainer,\n        nprocs=world_size,\n        args=(world_size,),\n        join=True)\n"
  },
  {
    "path": "train_config.py",
    "content": "\"\"\"\nExpected directory format:\n\nVideoMatte Train/Valid:\n    ├──fgr/\n      ├── 0001/\n        ├── 00000.jpg\n        ├── 00001.jpg\n    ├── pha/\n      ├── 0001/\n        ├── 00000.jpg\n        ├── 00001.jpg\n        \nImageMatte Train/Valid:\n    ├── fgr/\n      ├── sample1.jpg\n      ├── sample2.jpg\n    ├── pha/\n      ├── sample1.jpg\n      ├── sample2.jpg\n\nBackground Image Train/Valid\n    ├── sample1.png\n    ├── sample2.png\n\nBackground Video Train/Valid\n    ├── 0000/\n      ├── 0000.jpg/\n      ├── 0001.jpg/\n\n\"\"\"\n\n\nDATA_PATHS = {\n    \n    'videomatte': {\n        'train': '../matting-data/VideoMatte240K_JPEG_SD/train',\n        'valid': '../matting-data/VideoMatte240K_JPEG_SD/valid',\n    },\n    'imagematte': {\n        'train': '../matting-data/ImageMatte/train',\n        'valid': '../matting-data/ImageMatte/valid',\n    },\n    'background_images': {\n        'train': '../matting-data/Backgrounds/train',\n        'valid': '../matting-data/Backgrounds/valid',\n    },\n    'background_videos': {\n        'train': '../matting-data/BackgroundVideos/train',\n        'valid': '../matting-data/BackgroundVideos/valid',\n    },\n    \n    \n    'coco_panoptic': {\n        'imgdir': '../matting-data/coco/train2017/',\n        'anndir': '../matting-data/coco/panoptic_train2017/',\n        'annfile': '../matting-data/coco/annotations/panoptic_train2017.json',\n    },\n    'spd': {\n        'imgdir': '../matting-data/SuperviselyPersonDataset/img',\n        'segdir': '../matting-data/SuperviselyPersonDataset/seg',\n    },\n    'youtubevis': {\n        'videodir': '../matting-data/YouTubeVIS/train/JPEGImages',\n        'annfile': '../matting-data/YouTubeVIS/train/instances.json',\n    }\n    \n}\n"
  },
  {
    "path": "train_loss.py",
    "content": "import torch\nfrom torch.nn import functional as F\n\n# --------------------------------------------------------------------------------- Train Loss\n\n\ndef matting_loss(pred_fgr, pred_pha, true_fgr, true_pha):\n    \"\"\"\n    Args:\n        pred_fgr: Shape(B, T, 3, H, W)\n        pred_pha: Shape(B, T, 1, H, W)\n        true_fgr: Shape(B, T, 3, H, W)\n        true_pha: Shape(B, T, 1, H, W)\n    \"\"\"\n    loss = dict()\n    # Alpha losses\n    loss['pha_l1'] = F.l1_loss(pred_pha, true_pha)\n    loss['pha_laplacian'] = laplacian_loss(pred_pha.flatten(0, 1), true_pha.flatten(0, 1))\n    loss['pha_coherence'] = F.mse_loss(pred_pha[:, 1:] - pred_pha[:, :-1],\n                                       true_pha[:, 1:] - true_pha[:, :-1]) * 5\n    # Foreground losses\n    true_msk = true_pha.gt(0)\n    pred_fgr = pred_fgr * true_msk\n    true_fgr = true_fgr * true_msk\n    loss['fgr_l1'] = F.l1_loss(pred_fgr, true_fgr)\n    loss['fgr_coherence'] = F.mse_loss(pred_fgr[:, 1:] - pred_fgr[:, :-1],\n                                       true_fgr[:, 1:] - true_fgr[:, :-1]) * 5\n    # Total\n    loss['total'] = loss['pha_l1'] + loss['pha_coherence'] + loss['pha_laplacian'] \\\n                  + loss['fgr_l1'] + loss['fgr_coherence']\n    return loss\n\ndef segmentation_loss(pred_seg, true_seg):\n    \"\"\"\n    Args:\n        pred_seg: Shape(B, T, 1, H, W)\n        true_seg: Shape(B, T, 1, H, W)\n    \"\"\"\n    return F.binary_cross_entropy_with_logits(pred_seg, true_seg)\n\n\n# ----------------------------------------------------------------------------- Laplacian Loss\n\n\ndef laplacian_loss(pred, true, max_levels=5):\n    kernel = gauss_kernel(device=pred.device, dtype=pred.dtype)\n    pred_pyramid = laplacian_pyramid(pred, kernel, max_levels)\n    true_pyramid = laplacian_pyramid(true, kernel, max_levels)\n    loss = 0\n    for level in range(max_levels):\n        loss += (2 ** level) * F.l1_loss(pred_pyramid[level], true_pyramid[level])\n    return loss / max_levels\n\ndef laplacian_pyramid(img, kernel, max_levels):\n    current = img\n    pyramid = []\n    for _ in range(max_levels):\n        current = crop_to_even_size(current)\n        down = downsample(current, kernel)\n        up = upsample(down, kernel)\n        diff = current - up\n        pyramid.append(diff)\n        current = down\n    return pyramid\n\ndef gauss_kernel(device='cpu', dtype=torch.float32):\n    kernel = torch.tensor([[1,  4,  6,  4, 1],\n                           [4, 16, 24, 16, 4],\n                           [6, 24, 36, 24, 6],\n                           [4, 16, 24, 16, 4],\n                           [1,  4,  6,  4, 1]], device=device, dtype=dtype)\n    kernel /= 256\n    kernel = kernel[None, None, :, :]\n    return kernel\n\ndef gauss_convolution(img, kernel):\n    B, C, H, W = img.shape\n    img = img.reshape(B * C, 1, H, W)\n    img = F.pad(img, (2, 2, 2, 2), mode='reflect')\n    img = F.conv2d(img, kernel)\n    img = img.reshape(B, C, H, W)\n    return img\n\ndef downsample(img, kernel):\n    img = gauss_convolution(img, kernel)\n    img = img[:, :, ::2, ::2]\n    return img\n\ndef upsample(img, kernel):\n    B, C, H, W = img.shape\n    out = torch.zeros((B, C, H * 2, W * 2), device=img.device, dtype=img.dtype)\n    out[:, :, ::2, ::2] = img * 4\n    out = gauss_convolution(out, kernel)\n    return out\n\ndef crop_to_even_size(img):\n    H, W = img.shape[2:]\n    H = H - H % 2\n    W = W - W % 2\n    return img[:, :, :H, :W]\n\n"
  }
]