[
  {
    "path": ".gitignore",
    "content": "segmentation/\noutputs/\nmodels/\nresults/\nimages/\ndata/\nlogs/\nexamples\n.idea/\nnotebooks/.ipynb_checkpoints/*\n*.tar.gz\n*.zip\n*.pkl\n*.pyc\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM nvidia/cuda:9.1-cudnn7-devel-ubuntu16.04\nENV ANACONDA /opt/anaconda3\nENV CUDA_PATH /usr/local/cuda\nENV PATH ${ANACONDA}/bin:${CUDA_PATH}/bin:$PATH\nENV LD_LIBRARY_PATH ${ANACONDA}/lib:${CUDA_PATH}/bin64:$LD_LIBRARY_PATH\nENV C_INCLUDE_PATH ${CUDA_PATH}/include\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n         wget \\\n\t axel \\\n         imagemagick \\\n         libopencv-dev \\\n         python-opencv \\\n         build-essential \\\n         cmake \\\n         git \\\n         curl \\\n         ca-certificates \\\n         libjpeg-dev \\\n         libpng-dev \\\n         axel \\\n         zip \\\n         unzip\nRUN wget https://repo.continuum.io/archive/Anaconda3-5.0.1-Linux-x86_64.sh -P /tmp\nRUN bash /tmp/Anaconda3-5.0.1-Linux-x86_64.sh -b -p $ANACONDA\nRUN rm /tmp/Anaconda3-5.0.1-Linux-x86_64.sh -rf\nRUN conda install -y pytorch=0.4.1 torchvision cuda91 -c pytorch\nRUN conda install -y -c anaconda pip \nRUN conda install -y -c menpo opencv3\nRUN pip install scikit-umfpack\nRUN pip install cupy-cuda91\nRUN pip install pynvrtc\n"
  },
  {
    "path": "LICENSE.md",
    "content": "## creative commons\n\n# Attribution-NonCommercial-ShareAlike 4.0 International\n\nCreative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.\n\n### Using Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.\n\n* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).\n\n* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).\n\n## Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License (\"Public License\"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.\n\n### Section 1 – Definitions.\n\na. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.\n\nb. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.\n\nc. __BY-NC-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License.\n\nd. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.\n\ne. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.\n\nf. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.\n\ng. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.\n\nh. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.\n\ni. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.\n\nh. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.\n\ni. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.\n\nj. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.\n\nk. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.\n\nl. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.\n\n### Section 2 – Scope.\n\na. ___License grant.___\n\n 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:\n\n  A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and\n\n  B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.\n\n 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.\n    \n 3. __Term.__ The term of this Public License is specified in Section 6(a).\n\n 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.\n    \n 5. __Downstream recipients.__\n\n  A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.\n\n  B. __Additional offer from the Licensor – Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.\n\n  C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.\n\n 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).\n    \nb. ___Other rights.___\n\n 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.\n\n 2. Patent and trademark rights are not licensed under this Public License.\n\n 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.\n    \n### Section 3 – License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the following conditions.\n\na. ___Attribution.___\n\n 1. If You Share the Licensed Material (including in modified form), You must:\n\n  A. retain the following if it is supplied by the Licensor with the Licensed Material:\n\n   i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);\n\n   ii. a copyright notice;\n\n   iii. a notice that refers to this Public License;\n\n   iv. a notice that refers to the disclaimer of warranties;\n\n   v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;\n\n  B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and\n\n  C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.\n\n 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.\n\n 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.\n\nb. ___ShareAlike.___\n\nIn addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.\n\n 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.      \n\n 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.\n\n 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.\n\n### Section 4 – Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:\n\na. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;\n\nb. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and\n\nc. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.\n\n### Section 5 – Disclaimer of Warranties and Limitation of Liability.\n\na. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__\n\nb. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__\n\nc. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.\n\n### Section 6 – Term and Termination.\n\na. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.\n\nb. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:\n\n 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or\n\n 2. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or\n\n For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.\n\nc. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.\n\nd. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.\n\n### Section 7 – Other Terms and Conditions.\n\na. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.\n\nb. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.\n\n### Section 8 – Interpretation.\n\na. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.\n\nb. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.\n\nc. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.\n\nd. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.\n\n```\nCreative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. \n\nCreative Commons may be contacted at [creativecommons.org](http://creativecommons.org/).\n```\n"
  },
  {
    "path": "README.md",
    "content": "[![License CC BY-NC-SA 4.0](https://img.shields.io/badge/license-CC4.0-blue.svg)](https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/LICENSE.md)\n![Python 2.7](https://img.shields.io/badge/python-2.7-green.svg)\n![Python 3.5](https://img.shields.io/badge/python-3.5-green.svg)\n\n## FastPhotoStyle\n\n### License\nCopyright (C) 2018 NVIDIA Corporation.  All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\n<img src=\"https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/teaser.png\" width=\"800\" title=\"Teaser results\"> \n\n\n### What's new\n \n | Date     | News |\n |----------|--------------|\n |2018-07-25| Migrate to pytorch 0.4.0. For pytorch 0.3.0 user, check out [FastPhotoStyle for pytorch 0.3.0](https://github.com/NVIDIA/FastPhotoStyle/releases/tag/f33e07f). |\n |          | Add a [tutorial](TUTORIAL.md) showing 3 ways of using the FastPhotoStyle algorithm.|\n |2018-07-10| Our paper is accepted by the ECCV 2018 conference!!! | \n\n\n### About\n\nGiven a content photo and a style photo, the code can transfer the style of the style photo to the content photo. The details of the algorithm behind the code is documented in our arxiv paper. Please cite the paper if this code repository is used in your publications.\n\n[A Closed-form Solution to Photorealistic Image Stylization](https://arxiv.org/abs/1802.06474) <br> \n[Yijun Li (UC Merced)](https://sites.google.com/site/yijunlimaverick/), [Ming-Yu Liu (NVIDIA)](http://mingyuliu.net/), [Xueting Li (UC Merced)](https://sunshineatnoon.github.io/), [Ming-Hsuan Yang (NVIDIA, UC Merced)](http://faculty.ucmerced.edu/mhyang/), [Jan Kautz (NVIDIA)](http://jankautz.com/) <br>\nEuropean Conference on Computer Vision (ECCV), 2018 <br>\n\n\n### Tutorial\n\nPlease check out the [tutorial](TUTORIAL.md).\n\n\n"
  },
  {
    "path": "TUTORIAL.md",
    "content": "[![License CC BY-NC-SA 4.0](https://img.shields.io/badge/license-CC4.0-blue.svg)](https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/LICENSE.md)\n![Python 2.7](https://img.shields.io/badge/python-2.7-green.svg)\n![Python 3.5](https://img.shields.io/badge/python-3.5-green.svg)\n## FastPhotoStyle Tutorial \n\nIn this short tutorial, we will guide you through setting up the system environment for running the FastPhotoStyle software and then show several usage examples.\n\n### Background\n\nExisting style transfer algorithms can be divided into categories: artistic style transfer and photorealistic style transfer. \nFor artistic style transfer, the goal is to transfer the style of a reference painting to a photo so that the stylized photo looks like a painting and carries the style of the reference painting. \nFor photorealistic style transfer, the goal is to transfer the style of a reference photo to a photo so that the stylized photo preserves the content of the original photo but carries the style of the reference photo.\nThe FastPhotoStyle algorithm is in the category of photorealistic style transfer. \n\n### Algorithm\n\nFastPhotoStyle takes two images as input where one is the content image and the other is the style image. Its goal is to transfer the style of the style photo to the content photo for creating a stylized image as shown below.\n\n<img src=\"https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/demo_with_segmentation.gif\" width=\"800\" title=\"GIF\"> \n\n<img src=\"https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/teaser.png\" width=\"800\" title=\"Teaser results\"> \n\nFastPhotoStyle divides the photorealistic stylization process into two steps. \n  1. **PhotoWCT:** Generate a stylized image with visible distortions by applying a whitening and coloring transform to the deep features extracted from the content and style images. \n  2. **Photorealistic Smoothing:** Suppress the distortion in the stylized image by applying an image smoothing filter.\n  \nThe output is a photorealistic image as it were captured by a camera.\n\n### Requirements\n\n- Hardware: PC with NVIDIA Titan GPU.\n- Software: *Ubuntu 16.04*, *CUDA 9.1*, *Anaconda3*, *pytorch 0.4.0*\n- Environment variables.\n  - export ANACONDA=PATH-TO-YOUR-ANACONDA-LIBRARY\n  - export CUDA_PATH=/usr/local/cuda\n  - export PATH=${ANACONDA}/bin:${CUDA_PATH}/bin:$PATH\n  - export LD_LIBRARY_PATH=${ANACONDA}/lib:${CUDA_PATH}/bin64:$LD_LIBRARY_PATH\n  - export C_INCLUDE_PATH=${CUDA_PATH}/include\n- System package\n  - `sudo apt-get install -y axel imagemagick` (Only used for demo)  \n- Python package\n  - `conda install pytorch=0.4.0 torchvision cuda91 -y -c pytorch`\n  - `pip install scikit-umfpack`\n  - `pip install -U setuptools`\n  - `pip install cupy`\n  - `pip install pynvrtc`\n  - `conda install -c menpo opencv3` (OpenCV is only required if you want to use the approximate version of the photo smoothing step.)\n\n### Examples\n\nIn the following, we will provide 3 usage examples. \nIn the 1st example, we will run the FastPhotoStyle code without using \nsegmentation mask. \nIn the 2nd example, we will show how to use a labeling tool to create the segmentation masks and use them for stylization.\nIn the 3rd example, we will show how to use a pretrained segmetnation network to automatically generate the segmetnation masks and use them for stylization.\n\n#### Example 1: Transfer style of a style photo to a content photo without using segmentation masks.\n\nYou can simply type `./demo_example1.sh` to run the demo or follow the steps below.\n- Create image and output folders and make sure nothing is inside the folders: `mkdir images && mkdir results`\n- Go to the image folder: `cd images`\n- Download content image 1: `axel -n 1 http://freebigpictures.com/wp-content/uploads/shady-forest.jpg --output=content1.png`\n- Download style image 1: `axel -n 1 https://vignette.wikia.nocookie.net/strangerthings8338/images/e/e0/Wiki-background.jpeg/revision/latest?cb=20170522192233 --output=style1.png`\n- These images are huge. We need to resize them first. Run\n  - `convert -resize 25% content1.png content1.png`\n  - `convert -resize 50% style1.png style1.png`\n- Go back to the root folder: `cd ..`\n- Test the photorealistic image stylization code `python demo.py --output_image_path results/example1.png`\n- You should see output messages like\n- ```\n    Resize image: (803,538)->(803,538)\n    Resize image: (960,540)->(960,540)\n    Elapsed time in stylization: 0.398996\n    Elapsed time in propagation: 13.456573\n    Elapsed time in post processing: 0.202319\n  ```\n- You should see an output image like\n\n| Input Style Photo | Input Content Photo | Output Stylization Result |\n|-------------------|---------------------|---------------------------|\n|<img src=\"https://vignette.wikia.nocookie.net/strangerthings8338/images/e/e0/Wiki-background.jpeg\" height=\"200\" title=\"content 1\"> | <img src=\"http://freebigpictures.com/wp-content/uploads/shady-forest.jpg\" height=\"200\" title=\"content 1\"> |<img src=\"https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/demo_result_example1.png\" height=\"200\" title=\"demo_result_example1.png\"> |\n\n- As shown in the output messages, the computational bottleneck of FastPhotoStyle is the propagation step (the photorealistic smoothing step). We find that we can make this step much faster by using the guided image filtering algorithm as an approximate. To run the fast version of the demo, you can simply type `./demo_example1_fast.sh` or run.\n- `python demo.py --fast --output_image_path results/example1_fast.png`\n- You should see output messages like\n- ```\n    Resize image: (803,538)->(803,538)\n    Resize image: (960,540)->(960,540)\n    Elapsed time in stylization: 0.342203\n    Elapsed time in propagation: 0.039506\n    Elapsed time in post processing: 0.203081\n  ```\n- Check out the stylization result computed by the fast approximation step in `results/example1_fast.png`. It should look very similar to `results/example1.png` from the full algorithm.\n\n#### Example 2: Transfer style of a style photo to a content photo with manually generated semantic label maps.\n\nWhen segmentation masks of content and style photos are available, FastPhotoStyle can utilize content–style \ncorrespondences obtained by matching the semantic labels in the segmentation masks for generating better stylization effects. \nIn this example, we show how to manually create segmentation masks of content and style photos and use them for photorealistic style transfer.  \n\n##### Prepare label maps\n\n- Install the tool [labelme](https://github.com/wkentaro/labelme) and run the following command to start it: `labelme`\n- Please refer to [labelme](https://github.com/wkentaro/labelme) for details about how to use this great UI. Basically, do the following steps:\n  - Click `Open` and load the target image (content or style)\n  - Click `Create Polygons` and start drawing polygons in content or style image. Note that the corresponding regions (e.g., sky-to-sky) should have the same label. All unlabeled pixels will be automatically labeled as `0`. \n  - Optional: Click `Edit Polygons` and polish the mask.\n  - Save the labeling result.\n\n<img src=\"https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/demo_mask_poly.png\" width=\"800\" title=\"demo_mask_poly\"> \n\n- The labeling result is saved in a \".json\" file. By running the following command, you will get the `label.png` under `path/example_json`, which is the label map used in our code. `label.png` is a 1-channel image (usually looks totally black) consists of consecutive labels starting from 0.\n\n```\nlabelme_json_to_dataset example.json -o path/example_json\n```  \n\n##### Stylize with label maps\n\n```\npython demo.py \\\n   --content_image_path PATH-TO-YOUR-CONTENT-IMAGE \\ \n   --content_seg_path PATH-TO-YOUR-CONTENT-LABEL \\ \n   --style_image_path PATH-TO-YOUR-STYLE-IMAGE \\ \n   --style_seg_path PATH-TO-YOUR-STYLE-LABEL \\ \n   --output_image_path PATH-TO-YOUR-OUTPUT\n```\n\nBelow is a 3-label transferring example (images and labels are from the [DPST](https://github.com/luanfujun/deep-photo-styletransfer) work by Luan et al.):\n\n![](demo_result_example2.png)\n\n#### Example 3: Transfer the style of a style photo to a content photo with automatically generated semantic label maps.\n\nIn this example, we will show how to use segmentation masks of content and style photos generated by a pretrained segmentation network to achieve better stylization results. \nWe will use the segmentation network provided from [CSAILVision/semantic-segmentation-pytorch](https://github.com/CSAILVision/semantic-segmentation-pytorch) in this example. \nTo setup up the segmentation network, do the following steps:\n- Clone the CSAIL segmentation network from this fork of [CSAILVision/semantic-segmentation-pytorch](https://github.com/CSAILVision/semantic-segmentation-pytorch) using the following command \n  `git clone https://github.com/mingyuliutw/semantic-segmentation-pytorch segmentation`\n- Run the demo code in [CSAILVision/semantic-segmentation-pytorch](https://github.com/CSAILVision/semantic-segmentation-pytorch) to download the network and make sure the environment is set up properly. \n  - `cd segmentation` \n  - `./demo_test.sh`\n  - You should see output messages like \n    ```\n    2018-XX-XX XX:XX:XX--  http://sceneparsing.csail.mit.edu//data/ADEChallengeData2016/images/validation/ADE_val_00001519.jpg\n    Resolving sceneparsing.csail.mit.edu (sceneparsing.csail.mit.edu)... 128.30.100.255\n    Connecting to sceneparsing.csail.mit.edu (sceneparsing.csail.mit.edu)|128.30.100.255|:80... connected.\n    HTTP request sent, awaiting response... 200 OK\n    Length: 62271 (61K) [image/jpeg]\n    Saving to: ‘./ADE_val_00001519.jpg’\n    \n    ADE_val_00001519.jpg      100%[=====================================>]  60.81K   366KB/s    in 0.2s    \n    \n    2018-07-25 16:55:00 (366 KB/s) - ‘./ADE_val_00001519.jpg’ saved [62271/62271]\n    \n    Namespace(arch_decoder='ppm_bilinear_deepsup', arch_encoder='resnet50_dilated8', batch_size=1, fc_dim=2048, gpu_id=0, imgMaxSize=1000, imgSize=[300, 400, 500, 600], model_path='baseline-resnet50_dilated8-ppm_bilinear_deepsup', num_class=150, num_val=-1, padding_constant=8, result='./', segm_downsampling_rate=8, suffix='_epoch_20.pth', test_img='ADE_val_00001519.jpg')\n    Loading weights for net_encoder\n    Loading weights for net_decoder\n    Inference done!    \n    ```\n  - Go back to the root folder `cd ..`\n\n- Now, we are ready to use the segmentation network trained on the ADE20K for automatically generating the segmentation mask. \n- To run the fast version of the demo, you can simply type `./demo_example3.sh` or run.\n- Create image and output folders and make sure nothing is inside the folders. `mkdir images && mkdir results`\n- Go to the image folder: `cd images`\n- Download content image 3: `axel -n 1 https://pre00.deviantart.net/f1a6/th/pre/i/2010/019/0/e/country_road_hdr_by_mirre89.jpg --output=content3.png`\n- Download style image 3: `axel -n 1 https://nerdist.com/wp-content/uploads/2017/11/Stranger_Things_S2_news_Images_V03-1024x481.jpg --output=style3.png;`\n- These images are huge. We need to resize them first. Run\n  - `convert -resize 50% content3.png content3.png`\n  - `convert -resize 50% style3.png style3.png`\n- Go back to the root folder: `cd ..`\n- **Update the python library path by** `export PYTHONPATH=$PYTHONPATH:segmentation`\n- We will now run the demo code that first computing the segmentation masks of content and style images and then performing photorealistic style transfer. \n  `python demo_with_ade20k_ssn.py --output_visualization` or `python demo_with_ade20k_ssn.py --fast --output_visualization` \n- You should see output messages like\n  ```\n    Loading weights for net_encoder\n    Loading weights for net_decoder\n    Resize image: (546,366)->(546,366)\n    Resize image: (485,273)->(485,273)\n    Elapsed time in stylization: 0.890762\n    Elapsed time in propagation: 0.014808\n    Elapsed time in post processing: 0.197138\n  ```\n- You should see an output image like\n\n| Input Style Photo | Input Content Photo | Output Stylization Result |\n|-------------------|---------------------|---------------------------|\n|<img src=\"https://nerdist.com/wp-content/uploads/2017/11/Stranger_Things_S2_news_Images_V03-1024x481.jpg\" height=\"200\" title=\"content 3\"> | <img src=\"https://pre00.deviantart.net/f1a6/th/pre/i/2010/019/0/e/country_road_hdr_by_mirre89.jpg\" height=\"200\" title=\"content 3\"> |<img src=\"https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/demo_result_example3.png\" height=\"200\" title=\"demo_result_example3.png\"> |\n\n- We can check out the segmentation results in the `results` folder.\n\n| Segmentation of the Style Photo | Segmentation of the Content Photo |\n|---------------------------------|-----------------------------------|\n|<img src=\"https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/demo_result_style3_seg.pgm.visualization.jpg\" height=\"200\" title=\"demo_result_style3_seg.png\"> | <img src=\"https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/demo_result_content3_seg.pgm.visualization.jpg\" height=\"200\" title=\"demo_result_content3_seg.png\"> |\n\n\n### Use docker image\n\nWe provide a docker image for testing the code. \n\n  1. Install docker-ce. Follow the instruction in the [Docker page](https://docs.docker.com/install/linux/docker-ce/ubuntu/#install-docker-ce-1)\n  2. Install nvidia-docker. Follow the instruction in the [NVIDIA-DOCKER README page](https://github.com/NVIDIA/nvidia-docker).\n  3. Build the docker image `docker build -t your-docker-image:v1.0 .`\n  4. Run an interactive session `docker run -v YOUR_PATH:YOUR_PATH --runtime=nvidia -i -t your-docker-image:v1.0 /bin/bash`\n  5. `cd YOUR_PATH`\n  6. `./demo_example1.sh`\n\n## Acknowledgement\n\n- We express gratitudes to the great work [DPST](https://www.cs.cornell.edu/~fujun/files/style-cvpr17/style-cvpr17.pdf) by Luan et al. and their [Torch](https://github.com/luanfujun/deep-photo-styletransfer) and [Tensorflow](https://github.com/LouieYang/deep-photo-styletransfer-tf) implementations.\n"
  },
  {
    "path": "converter.py",
    "content": "import os\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.serialization import load_lua\n\nfrom models import VGGEncoder, VGGDecoder\nfrom photo_wct import PhotoWCT\n\n\ndef weight_assign(lua, pth, maps):\n    for k, v in maps.items():\n        getattr(pth, k).weight = nn.Parameter(lua.get(v).weight.float())\n        getattr(pth, k).bias = nn.Parameter(lua.get(v).bias.float())\n\n\ndef photo_wct_loader(p_wct):\n    p_wct.e1.load_state_dict(torch.load('pth_models/vgg_normalised_conv1.pth'))\n    p_wct.d1.load_state_dict(torch.load('pth_models/feature_invertor_conv1.pth'))\n    p_wct.e2.load_state_dict(torch.load('pth_models/vgg_normalised_conv2.pth'))\n    p_wct.d2.load_state_dict(torch.load('pth_models/feature_invertor_conv2.pth'))\n    p_wct.e3.load_state_dict(torch.load('pth_models/vgg_normalised_conv3.pth'))\n    p_wct.d3.load_state_dict(torch.load('pth_models/feature_invertor_conv3.pth'))\n    p_wct.e4.load_state_dict(torch.load('pth_models/vgg_normalised_conv4.pth'))\n    p_wct.d4.load_state_dict(torch.load('pth_models/feature_invertor_conv4.pth'))\n\n\nif __name__ == '__main__':\n    if not os.path.exists('pth_models'):\n        os.mkdir('pth_models')\n    \n    ## VGGEncoder1\n    vgg1 = load_lua('models/vgg_normalised_conv1_1_mask.t7')\n    e1 = VGGEncoder(1)\n    weight_assign(vgg1, e1, {\n        'conv0': 0,\n        'conv1_1': 2,\n    })\n    torch.save(e1.state_dict(), 'pth_models/vgg_normalised_conv1.pth')\n    \n    ## VGGDecoder1\n    inv1 = load_lua('models/feature_invertor_conv1_1_mask.t7')\n    d1 = VGGDecoder(1)\n    weight_assign(inv1, d1, {\n        'conv1_1': 1,\n    })\n    torch.save(d1.state_dict(), 'pth_models/feature_invertor_conv1.pth')\n    \n    ## VGGEncoder2\n    vgg2 = load_lua('models/vgg_normalised_conv2_1_mask.t7')\n    e2 = VGGEncoder(2)\n    weight_assign(vgg2, e2, {\n        'conv0': 0,\n        'conv1_1': 2,\n        'conv1_2': 5,\n        'conv2_1': 9,\n    })\n    torch.save(e2.state_dict(), 'pth_models/vgg_normalised_conv2.pth')\n    \n    ## VGGDecoder2\n    inv2 = load_lua('models/feature_invertor_conv2_1_mask.t7')\n    d2 = VGGDecoder(2)\n    weight_assign(inv2, d2, {\n        'conv2_1': 1,\n        'conv1_2': 5,\n        'conv1_1': 8,\n    })\n    torch.save(d2.state_dict(), 'pth_models/feature_invertor_conv2.pth')\n    \n    ## VGGEncoder3\n    vgg3 = load_lua('models/vgg_normalised_conv3_1_mask.t7')\n    e3 = VGGEncoder(3)\n    weight_assign(vgg3, e3, {\n        'conv0': 0,\n        'conv1_1': 2,\n        'conv1_2': 5,\n        'conv2_1': 9,\n        'conv2_2': 12,\n        'conv3_1': 16,\n    })\n    torch.save(e3.state_dict(), 'pth_models/vgg_normalised_conv3.pth')\n    \n    ## VGGDecoder3\n    inv3 = load_lua('models/feature_invertor_conv3_1_mask.t7')\n    d3 = VGGDecoder(3)\n    weight_assign(inv3, d3, {\n        'conv3_1': 1,\n        'conv2_2': 5,\n        'conv2_1': 8,\n        'conv1_2': 12,\n        'conv1_1': 15,\n    })\n    torch.save(d3.state_dict(), 'pth_models/feature_invertor_conv3.pth')\n    \n    ## VGGEncoder4\n    vgg4 = load_lua('models/vgg_normalised_conv4_1_mask.t7')\n    e4 = VGGEncoder(4)\n    weight_assign(vgg4, e4, {\n        'conv0': 0,\n        'conv1_1': 2,\n        'conv1_2': 5,\n        'conv2_1': 9,\n        'conv2_2': 12,\n        'conv3_1': 16,\n        'conv3_2': 19,\n        'conv3_3': 22,\n        'conv3_4': 25,\n        'conv4_1': 29,\n    })\n    torch.save(e4.state_dict(), 'pth_models/vgg_normalised_conv4.pth')\n    \n    ## VGGDecoder4\n    inv4 = load_lua('models/feature_invertor_conv4_1_mask.t7')\n    d4 = VGGDecoder(4)\n    weight_assign(inv4, d4, {\n        'conv4_1': 1,\n        'conv3_4': 5,\n        'conv3_3': 8,\n        'conv3_2': 11,\n        'conv3_1': 14,\n        'conv2_2': 18,\n        'conv2_1': 21,\n        'conv1_2': 25,\n        'conv1_1': 28,\n    })\n    torch.save(d4.state_dict(), 'pth_models/feature_invertor_conv4.pth')\n    \n    p_wct = PhotoWCT()\n    photo_wct_loader(p_wct)\n    torch.save(p_wct.state_dict(), 'PhotoWCTModels/photo_wct.pth')\n"
  },
  {
    "path": "demo.py",
    "content": "\"\"\"\nCopyright (C) 2018 NVIDIA Corporation.  All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\n\nfrom __future__ import print_function\nimport argparse\nimport torch\nimport process_stylization\nfrom photo_wct import PhotoWCT\nparser = argparse.ArgumentParser(description='Photorealistic Image Stylization')\nparser.add_argument('--model', default='./PhotoWCTModels/photo_wct.pth')\nparser.add_argument('--content_image_path', default='./images/content1.png')\nparser.add_argument('--content_seg_path', default=[])\nparser.add_argument('--style_image_path', default='./images/style1.png')\nparser.add_argument('--style_seg_path', default=[])\nparser.add_argument('--output_image_path', default='./results/example1.png')\nparser.add_argument('--save_intermediate', action='store_true', default=False)\nparser.add_argument('--fast', action='store_true', default=False)\nparser.add_argument('--no_post', action='store_true', default=False)\nparser.add_argument('--cuda', type=int, default=1, help='Enable CUDA.')\nargs = parser.parse_args()\n\n# Load model\np_wct = PhotoWCT()\np_wct.load_state_dict(torch.load(args.model))\n\nif args.fast:\n    from photo_gif import GIFSmoothing\n    p_pro = GIFSmoothing(r=35, eps=0.001)\nelse:\n    from photo_smooth import Propagator\n    p_pro = Propagator()\nif args.cuda:\n    p_wct.cuda(0)\n\nprocess_stylization.stylization(\n    stylization_module=p_wct,\n    smoothing_module=p_pro,\n    content_image_path=args.content_image_path,\n    style_image_path=args.style_image_path,\n    content_seg_path=args.content_seg_path,\n    style_seg_path=args.style_seg_path,\n    output_image_path=args.output_image_path,\n    cuda=args.cuda,\n    save_intermediate=args.save_intermediate,\n    no_post=args.no_post\n)\n"
  },
  {
    "path": "demo_example1.sh",
    "content": "mkdir images -p && mkdir results -p;\nrm images/content1.png -rf;\nrm images/style1.png -rf;\nrm results/demo_result_example1.png\ncd images;\naxel -n 1 http://freebigpictures.com/wp-content/uploads/shady-forest.jpg --output=content1.png;\naxel -n 1 https://vignette.wikia.nocookie.net/strangerthings8338/images/e/e0/Wiki-background.jpeg/revision/latest?cb=20170522192233 --output=style1.png;\nconvert -resize 25% content1.png content1.png;\nconvert -resize 50% style1.png style1.png;\ncd ..;\npython demo.py;\n"
  },
  {
    "path": "demo_example1_fast.sh",
    "content": "mkdir images -p && mkdir results -p;\nrm images/content1.png -rf;\nrm images/style1.png -rf;\nrm results/demo_result_example1.png\ncd images;\naxel -n 1 http://freebigpictures.com/wp-content/uploads/shady-forest.jpg --output=content1.png;\naxel -n 1 https://vignette.wikia.nocookie.net/strangerthings8338/images/e/e0/Wiki-background.jpeg/revision/latest?cb=20170522192233 --output=style1.png;\nconvert -resize 25% content1.png content1.png;\nconvert -resize 50% style1.png style1.png;\ncd ..;\npython demo.py --fast --output_image_path results/example2.png;\n"
  },
  {
    "path": "demo_example3.sh",
    "content": "mkdir images -p && mkdir results -p;\nrm images/content3.png -rf;\nrm images/style3.png -rf;\nrm results/content3_seg.pgm -rf;\nrm results/style3_seg.pgm -rf;\nrm results/stylization_with_auto_segmentation.png -rf;\nexport PYTHONPATH=$PYTHONPATH:segmentation\ncd images;\naxel -n 1 https://pre00.deviantart.net/f1a6/th/pre/i/2010/019/0/e/country_road_hdr_by_mirre89.jpg --output=content3.png;\naxel -n 1 https://nerdist.com/wp-content/uploads/2017/11/Stranger_Things_S2_news_Images_V03-1024x481.jpg --output=style3.png;\nconvert -resize 50% content3.png content3.png;\nconvert -resize 50% style3.png style3.png;\ncd ..;\npython demo_with_ade20k_ssn.py;\n"
  },
  {
    "path": "demo_with_ade20k_ssn.py",
    "content": "\"\"\"\nCopyright (C) 2018 NVIDIA Corporation.  All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\nfrom __future__ import print_function\nimport argparse\nimport os\nimport torch\nimport process_stylization_ade20k_ssn\nfrom torch import nn\nfrom photo_wct import PhotoWCT\nfrom segmentation.dataset import round2nearest_multiple\nfrom segmentation.models import ModelBuilder, SegmentationModule\nfrom lib.nn import user_scattered_collate, async_copy_to\nfrom lib.utils import as_numpy, mark_volatile\nfrom scipy.misc import imread, imresize\nimport cv2\nfrom torchvision import transforms\nimport numpy as np\n\nparser = argparse.ArgumentParser(description='Photorealistic Image Stylization')\nparser.add_argument('--model_path', help='folder to model path', default='baseline-resnet50_dilated8-ppm_bilinear_deepsup')\nparser.add_argument('--suffix', default='_epoch_20.pth', help=\"which snapshot to load\")\nparser.add_argument('--arch_encoder', default='resnet50_dilated8', help=\"architecture of net_encoder\")\nparser.add_argument('--arch_decoder', default='ppm_bilinear_deepsup', help=\"architecture of net_decoder\")\nparser.add_argument('--fc_dim', default=2048, type=int, help='number of features between encoder and decoder')\nparser.add_argument('--num_val', default=-1, type=int, help='number of images to evalutate')\nparser.add_argument('--num_class', default=150, type=int, help='number of classes')\nparser.add_argument('--batch_size', default=1, type=int, help='batchsize. current only supports 1')\nparser.add_argument('--imgSize', default=[300, 400, 500, 600], nargs='+', type=int, help='list of input image sizes.' 'for multiscale testing, e.g. 300 400 500')\nparser.add_argument('--imgMaxSize', default=1000, type=int, help='maximum input image size of long edge')\nparser.add_argument('--padding_constant', default=8, type=int, help='maxmimum downsampling rate of the network')\nparser.add_argument('--segm_downsampling_rate', default=8, type=int, help='downsampling rate of the segmentation label')\nparser.add_argument('--gpu_id', default=0, type=int, help='gpu_id for evaluation')\n\nparser.add_argument('--model', default='./PhotoWCTModels/photo_wct.pth', help='Path to the PhotoWCT model. These are provided by the PhotoWCT submodule, please use `git submodule update --init --recursive` to pull.')\nparser.add_argument('--content_image_path', default=\"./images/content3.png\")\nparser.add_argument('--content_seg_path', default='./results/content3_seg.pgm')\nparser.add_argument('--style_image_path', default='./images/style3.png')\nparser.add_argument('--style_seg_path', default='./results/style3_seg.pgm')\nparser.add_argument('--output_image_path', default='./results/example3.png')\nparser.add_argument('--save_intermediate', action='store_true', default=False)\nparser.add_argument('--fast', action='store_true', default=False)\nparser.add_argument('--no_post', action='store_true', default=False)\nparser.add_argument('--output_visualization', action='store_true', default=False)\nparser.add_argument('--cuda', type=int, default=1, help='Enable CUDA.')\nparser.add_argument('--label_mapping', type=str, default='ade20k_semantic_rel.npy')\nargs = parser.parse_args()\n\nsegReMapping = process_stylization_ade20k_ssn.SegReMapping(args.label_mapping)\n\n# Absolute paths of segmentation model weights\nSEG_NET_PATH = 'segmentation'\nargs.weights_encoder = os.path.join(SEG_NET_PATH,args.model_path, 'encoder' + args.suffix)\nargs.weights_decoder = os.path.join(SEG_NET_PATH,args.model_path, 'decoder' + args.suffix)\nargs.arch_encoder = 'resnet50_dilated8'\nargs.arch_decoder = 'ppm_bilinear_deepsup'\nargs.fc_dim = 2048\n\n# Load semantic segmentation network module\nbuilder = ModelBuilder()\nnet_encoder = builder.build_encoder(arch=args.arch_encoder, fc_dim=args.fc_dim, weights=args.weights_encoder)\nnet_decoder = builder.build_decoder(arch=args.arch_decoder, fc_dim=args.fc_dim, num_class=args.num_class, weights=args.weights_decoder, use_softmax=True)\ncrit = nn.NLLLoss(ignore_index=-1)\nsegmentation_module = SegmentationModule(net_encoder, net_decoder, crit)\nsegmentation_module.cuda()\nsegmentation_module.eval()\ntransform = transforms.Compose([transforms.Normalize(mean=[102.9801, 115.9465, 122.7717], std=[1., 1., 1.])])\n\n# Load FastPhotoStyle model\np_wct = PhotoWCT()\np_wct.load_state_dict(torch.load(args.model))\nif args.fast:\n    from photo_gif import GIFSmoothing\n    p_pro = GIFSmoothing(r=35, eps=0.001)\nelse:\n    from photo_smooth import Propagator\n    p_pro = Propagator()\nif args.cuda:\n    p_wct.cuda(0)\n\n\ndef segment_this_img(f):\n    img = imread(f, mode='RGB')\n    img = img[:, :, ::-1]  # BGR to RGB!!!\n    ori_height, ori_width, _ = img.shape\n    img_resized_list = []\n    for this_short_size in args.imgSize:\n        scale = this_short_size / float(min(ori_height, ori_width))\n        target_height, target_width = int(ori_height * scale), int(ori_width * scale)\n        target_height = round2nearest_multiple(target_height, args.padding_constant)\n        target_width = round2nearest_multiple(target_width, args.padding_constant)\n        img_resized = cv2.resize(img.copy(), (target_width, target_height))\n        img_resized = img_resized.astype(np.float32)\n        img_resized = img_resized.transpose((2, 0, 1))\n        img_resized = transform(torch.from_numpy(img_resized))\n        img_resized = torch.unsqueeze(img_resized, 0)\n        img_resized_list.append(img_resized)\n    input = dict()\n    input['img_ori'] = img.copy()\n    input['img_data'] = [x.contiguous() for x in img_resized_list]\n    segSize = (img.shape[0],img.shape[1])\n    with torch.no_grad():\n        pred = torch.zeros(1, args.num_class, segSize[0], segSize[1])\n        for timg in img_resized_list:\n            feed_dict = dict()\n            feed_dict['img_data'] = timg.cuda()\n            feed_dict = async_copy_to(feed_dict, args.gpu_id)\n            # forward pass\n            pred_tmp = segmentation_module(feed_dict, segSize=segSize)\n            pred = pred + pred_tmp.cpu() / len(args.imgSize)\n        _, preds = torch.max(pred, dim=1)\n        preds = as_numpy(preds.squeeze(0))\n    return preds\n\n\ncont_seg = segment_this_img(args.content_image_path)\ncv2.imwrite(args.content_seg_path, cont_seg)\nstyle_seg = segment_this_img(args.style_image_path)\ncv2.imwrite(args.style_seg_path, style_seg)\nprocess_stylization_ade20k_ssn.stylization(\n    stylization_module=p_wct,\n    smoothing_module=p_pro,\n    content_image_path=args.content_image_path,\n    style_image_path=args.style_image_path,\n    content_seg_path=args.content_seg_path,\n    style_seg_path=args.style_seg_path,\n    output_image_path=args.output_image_path,\n    cuda=True,\n    save_intermediate=args.save_intermediate,\n    no_post=args.no_post,\n    label_remapping=segReMapping,\n    output_visualization=args.output_visualization\n)\n"
  },
  {
    "path": "download_models.py",
    "content": "# Download code taken from Code taken from https://stackoverflow.com/questions/25010369/wget-curl-large-file-from-google-drive/39225039#39225039\nimport requests\n\ndef download_file_from_google_drive(id, destination):\n    URL = \"https://docs.google.com/uc?export=download\"\n\n    session = requests.Session()\n\n    response = session.get(URL, params = { 'id' : id }, stream = True)\n    token = get_confirm_token(response)\n\n    if token:\n        params = { 'id' : id, 'confirm' : token }\n        response = session.get(URL, params = params, stream = True)\n\n    save_response_content(response, destination)    \n\ndef get_confirm_token(response):\n    for key, value in response.cookies.items():\n        if key.startswith('download_warning'):\n            return value\n\n    return None\n\ndef save_response_content(response, destination):\n    CHUNK_SIZE = 32768\n\n    with open(destination, \"wb\") as f:\n        for chunk in response.iter_content(CHUNK_SIZE):\n            if chunk: # filter out keep-alive new chunks\n                f.write(chunk)\n\nfile_id = '1ENgQm9TgabE1R99zhNf5q6meBvX6WFuq'\ndestination = './models.zip'\ndownload_file_from_google_drive(file_id, destination)"
  },
  {
    "path": "download_models.sh",
    "content": "#!/bin/bash\npython download_models.py\nunzip models.zip\n"
  },
  {
    "path": "models.py",
    "content": "\"\"\"\nCopyright (C) 2018 NVIDIA Corporation.  All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\nimport torch.nn as nn\n\n\nclass VGGEncoder(nn.Module):\n    def __init__(self, level):\n        super(VGGEncoder, self).__init__()\n        self.level = level\n        \n        # 224 x 224\n        self.conv0 = nn.Conv2d(3, 3, 1, 1, 0)\n        \n        self.pad1_1 = nn.ReflectionPad2d((1, 1, 1, 1))\n        # 226 x 226\n        self.conv1_1 = nn.Conv2d(3, 64, 3, 1, 0)\n        self.relu1_1 = nn.ReLU(inplace=True)\n        # 224 x 224\n        \n        if level < 2: return\n        \n        self.pad1_2 = nn.ReflectionPad2d((1, 1, 1, 1))\n        self.conv1_2 = nn.Conv2d(64, 64, 3, 1, 0)\n        self.relu1_2 = nn.ReLU(inplace=True)\n        # 224 x 224\n        self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)\n        # 112 x 112\n        \n        self.pad2_1 = nn.ReflectionPad2d((1, 1, 1, 1))\n        self.conv2_1 = nn.Conv2d(64, 128, 3, 1, 0)\n        self.relu2_1 = nn.ReLU(inplace=True)\n        # 112 x 112\n        \n        if level < 3: return\n        \n        self.pad2_2 = nn.ReflectionPad2d((1, 1, 1, 1))\n        self.conv2_2 = nn.Conv2d(128, 128, 3, 1, 0)\n        self.relu2_2 = nn.ReLU(inplace=True)\n        # 112 x 112\n        \n        self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)\n        # 56 x 56\n        \n        self.pad3_1 = nn.ReflectionPad2d((1, 1, 1, 1))\n        self.conv3_1 = nn.Conv2d(128, 256, 3, 1, 0)\n        self.relu3_1 = nn.ReLU(inplace=True)\n        # 56 x 56\n        \n        if level < 4: return\n        \n        self.pad3_2 = nn.ReflectionPad2d((1, 1, 1, 1))\n        self.conv3_2 = nn.Conv2d(256, 256, 3, 1, 0)\n        self.relu3_2 = nn.ReLU(inplace=True)\n        # 56 x 56\n        \n        self.pad3_3 = nn.ReflectionPad2d((1, 1, 1, 1))\n        self.conv3_3 = nn.Conv2d(256, 256, 3, 1, 0)\n        self.relu3_3 = nn.ReLU(inplace=True)\n        # 56 x 56\n        \n        self.pad3_4 = nn.ReflectionPad2d((1, 1, 1, 1))\n        self.conv3_4 = nn.Conv2d(256, 256, 3, 1, 0)\n        self.relu3_4 = nn.ReLU(inplace=True)\n        # 56 x 56\n        \n        self.maxpool3 = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)\n        # 28 x 28\n        \n        self.pad4_1 = nn.ReflectionPad2d((1, 1, 1, 1))\n        self.conv4_1 = nn.Conv2d(256, 512, 3, 1, 0)\n        self.relu4_1 = nn.ReLU(inplace=True)\n        # 28 x 28\n    \n    def forward(self, x):\n        out = self.conv0(x)\n        \n        out = self.pad1_1(out)\n        out = self.conv1_1(out)\n        out = self.relu1_1(out)\n        \n        if self.level < 2:\n            return out\n        \n        out = self.pad1_2(out)\n        out = self.conv1_2(out)\n        pool1 = self.relu1_2(out)\n        \n        out, pool1_idx = self.maxpool1(pool1)\n        \n        out = self.pad2_1(out)\n        out = self.conv2_1(out)\n        out = self.relu2_1(out)\n        \n        if self.level < 3:\n            return out, pool1_idx, pool1.size()\n        \n        out = self.pad2_2(out)\n        out = self.conv2_2(out)\n        pool2 = self.relu2_2(out)\n        \n        out, pool2_idx = self.maxpool2(pool2)\n        \n        out = self.pad3_1(out)\n        out = self.conv3_1(out)\n        out = self.relu3_1(out)\n        \n        if self.level < 4:\n            return out, pool1_idx, pool1.size(), pool2_idx, pool2.size()\n        \n        out = self.pad3_2(out)\n        out = self.conv3_2(out)\n        out = self.relu3_2(out)\n        \n        out = self.pad3_3(out)\n        out = self.conv3_3(out)\n        out = self.relu3_3(out)\n        \n        out = self.pad3_4(out)\n        out = self.conv3_4(out)\n        pool3 = self.relu3_4(out)\n        out, pool3_idx = self.maxpool3(pool3)\n        \n        out = self.pad4_1(out)\n        out = self.conv4_1(out)\n        out = self.relu4_1(out)\n        \n        return out, pool1_idx, pool1.size(), pool2_idx, pool2.size(), pool3_idx, pool3.size()\n    \n    def forward_multiple(self, x):\n        out = self.conv0(x)\n        \n        out = self.pad1_1(out)\n        out = self.conv1_1(out)\n        out = self.relu1_1(out)\n        \n        if self.level < 2: return out\n        \n        out1 = out\n        \n        out = self.pad1_2(out)\n        out = self.conv1_2(out)\n        pool1 = self.relu1_2(out)\n        \n        out, pool1_idx = self.maxpool1(pool1)\n        \n        out = self.pad2_1(out)\n        out = self.conv2_1(out)\n        out = self.relu2_1(out)\n        \n        if self.level < 3: return out, out1\n        \n        out2 = out\n        \n        out = self.pad2_2(out)\n        out = self.conv2_2(out)\n        pool2 = self.relu2_2(out)\n        \n        out, pool2_idx = self.maxpool2(pool2)\n        \n        out = self.pad3_1(out)\n        out = self.conv3_1(out)\n        out = self.relu3_1(out)\n        \n        if self.level < 4: return out, out2, out1\n        \n        out3 = out\n        \n        out = self.pad3_2(out)\n        out = self.conv3_2(out)\n        out = self.relu3_2(out)\n        \n        out = self.pad3_3(out)\n        out = self.conv3_3(out)\n        out = self.relu3_3(out)\n        \n        out = self.pad3_4(out)\n        out = self.conv3_4(out)\n        pool3 = self.relu3_4(out)\n        out, pool3_idx = self.maxpool3(pool3)\n        \n        out = self.pad4_1(out)\n        out = self.conv4_1(out)\n        out = self.relu4_1(out)\n        \n        return out, out3, out2, out1\n\n\nclass VGGDecoder(nn.Module):\n    def __init__(self, level):\n        super(VGGDecoder, self).__init__()\n        self.level = level\n        \n        if level > 3:\n            self.pad4_1 = nn.ReflectionPad2d((1, 1, 1, 1))\n            self.conv4_1 = nn.Conv2d(512, 256, 3, 1, 0)\n            self.relu4_1 = nn.ReLU(inplace=True)\n            # 28 x 28\n            \n            self.unpool3 = nn.MaxUnpool2d(kernel_size=2, stride=2)\n            # 56 x 56\n            \n            self.pad3_4 = nn.ReflectionPad2d((1, 1, 1, 1))\n            self.conv3_4 = nn.Conv2d(256, 256, 3, 1, 0)\n            self.relu3_4 = nn.ReLU(inplace=True)\n            # 56 x 56\n            \n            self.pad3_3 = nn.ReflectionPad2d((1, 1, 1, 1))\n            self.conv3_3 = nn.Conv2d(256, 256, 3, 1, 0)\n            self.relu3_3 = nn.ReLU(inplace=True)\n            # 56 x 56\n            \n            self.pad3_2 = nn.ReflectionPad2d((1, 1, 1, 1))\n            self.conv3_2 = nn.Conv2d(256, 256, 3, 1, 0)\n            self.relu3_2 = nn.ReLU(inplace=True)\n            # 56 x 56\n        \n        if level > 2:\n            self.pad3_1 = nn.ReflectionPad2d((1, 1, 1, 1))\n            self.conv3_1 = nn.Conv2d(256, 128, 3, 1, 0)\n            self.relu3_1 = nn.ReLU(inplace=True)\n            # 56 x 56\n            \n            self.unpool2 = nn.MaxUnpool2d(kernel_size=2, stride=2)\n            # 112 x 112\n            \n            self.pad2_2 = nn.ReflectionPad2d((1, 1, 1, 1))\n            self.conv2_2 = nn.Conv2d(128, 128, 3, 1, 0)\n            self.relu2_2 = nn.ReLU(inplace=True)\n            # 112 x 112\n        \n        if level > 1:\n            self.pad2_1 = nn.ReflectionPad2d((1, 1, 1, 1))\n            self.conv2_1 = nn.Conv2d(128, 64, 3, 1, 0)\n            self.relu2_1 = nn.ReLU(inplace=True)\n            # 112 x 112\n            \n            self.unpool1 = nn.MaxUnpool2d(kernel_size=2, stride=2)\n            # 224 x 224\n            \n            self.pad1_2 = nn.ReflectionPad2d((1, 1, 1, 1))\n            self.conv1_2 = nn.Conv2d(64, 64, 3, 1, 0)\n            self.relu1_2 = nn.ReLU(inplace=True)\n            # 224 x 224\n        \n        if level > 0:\n            self.pad1_1 = nn.ReflectionPad2d((1, 1, 1, 1))\n            self.conv1_1 = nn.Conv2d(64, 3, 3, 1, 0)\n    \n    def forward(self, x, pool1_idx=None, pool1_size=None, pool2_idx=None, pool2_size=None, pool3_idx=None,\n                pool3_size=None):\n        out = x\n        \n        if self.level > 3:\n            out = self.pad4_1(out)\n            out = self.conv4_1(out)\n            out = self.relu4_1(out)\n            out = self.unpool3(out, pool3_idx, output_size=pool3_size)\n            \n            out = self.pad3_4(out)\n            out = self.conv3_4(out)\n            out = self.relu3_4(out)\n            \n            out = self.pad3_3(out)\n            out = self.conv3_3(out)\n            out = self.relu3_3(out)\n            \n            out = self.pad3_2(out)\n            out = self.conv3_2(out)\n            out = self.relu3_2(out)\n        \n        if self.level > 2:\n            out = self.pad3_1(out)\n            out = self.conv3_1(out)\n            out = self.relu3_1(out)\n            out = self.unpool2(out, pool2_idx, output_size=pool2_size)\n            \n            out = self.pad2_2(out)\n            out = self.conv2_2(out)\n            out = self.relu2_2(out)\n        \n        if self.level > 1:\n            out = self.pad2_1(out)\n            out = self.conv2_1(out)\n            out = self.relu2_1(out)\n            out = self.unpool1(out, pool1_idx, output_size=pool1_size)\n            \n            out = self.pad1_2(out)\n            out = self.conv1_2(out)\n            out = self.relu1_2(out)\n        \n        if self.level > 0:\n            out = self.pad1_1(out)\n            out = self.conv1_1(out)\n        \n        return out\n"
  },
  {
    "path": "photo_gif.py",
    "content": "\"\"\"\nCopyright (C) 2018 NVIDIA Corporation.    All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\nfrom __future__ import division\nfrom PIL import Image\nfrom torch import nn\nimport numpy as np\nimport cv2\nfrom cv2.ximgproc import guidedFilter\n\n\nclass GIFSmoothing(nn.Module):\n    def forward(self, *input):\n        pass\n        \n    def __init__(self, r, eps):\n        super(GIFSmoothing, self).__init__()\n        self.r = r\n        self.eps = eps\n\n    def process(self, initImg, contentImg):\n        return self.process_opencv(initImg, contentImg)\n\n    def process_opencv(self, initImg, contentImg):\n        '''\n        :param initImg: intermediate output. Either image path or PIL Image\n        :param contentImg: content image output. Either path or PIL Image\n        :return: stylized output image. PIL Image\n        '''\n        if type(initImg) == str:\n            init_img = cv2.imread(initImg)\n            init_img = init_img[2:-2,2:-2,:]\n        else:\n            init_img = np.array(initImg)[:, :, ::-1].copy()\n\n        if type(contentImg) == str:\n            cont_img = cv2.imread(contentImg)\n        else:\n            cont_img = np.array(contentImg)[:, :, ::-1].copy()\n\n        output_img = guidedFilter(guide=cont_img, src=init_img, radius=self.r, eps=self.eps)\n        output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2RGB)\n        output_img = Image.fromarray(output_img)\n        return output_img\n\n"
  },
  {
    "path": "photo_smooth.py",
    "content": "\"\"\"\nCopyright (C) 2018 NVIDIA Corporation.    All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\nfrom __future__ import division\nimport torch.nn as nn\nimport scipy.misc\nimport numpy as np\nimport scipy.sparse\nimport scipy.sparse.linalg\nfrom numpy.lib.stride_tricks import as_strided\nfrom PIL import Image\n\n\nclass Propagator(nn.Module):\n    def __init__(self, beta=0.9999):\n        super(Propagator, self).__init__()\n        self.beta = beta\n\n    def process(self, initImg, contentImg):\n\n        if type(contentImg) == str:\n            content = scipy.misc.imread(contentImg, mode='RGB')\n        else:\n            content = contentImg.copy()\n        # content = scipy.misc.imread(contentImg, mode='RGB')\n\n        if type(initImg) == str:\n            B = scipy.misc.imread(initImg, mode='RGB').astype(np.float64) / 255\n        else:\n            B = scipy.asarray(initImg).astype(np.float64) / 255\n            # B = self.\n        # B = scipy.misc.imread(initImg, mode='RGB').astype(np.float64)/255\n        h1,w1,k = B.shape\n        h = h1 - 4\n        w = w1 - 4\n        B = B[int((h1-h)/2):int((h1-h)/2+h),int((w1-w)/2):int((w1-w)/2+w),:]\n        content = scipy.misc.imresize(content,(h,w))\n        B = self.__replication_padding(B,2)\n        content = self.__replication_padding(content,2)\n        content = content.astype(np.float64)/255\n        B = np.reshape(B,(h1*w1,k))\n        W = self.__compute_laplacian(content)\n        W = W.tocsc()\n        dd = W.sum(0)\n        dd = np.sqrt(np.power(dd,-1))\n        dd = dd.A.squeeze()\n        D = scipy.sparse.csc_matrix((dd, (np.arange(0,w1*h1), np.arange(0,w1*h1)))) # 0.026\n        S = D.dot(W).dot(D)\n        A = scipy.sparse.identity(w1*h1) - self.beta*S\n        A = A.tocsc()\n        solver = scipy.sparse.linalg.factorized(A)\n        V = np.zeros((h1*w1,k))\n        V[:,0] = solver(B[:,0])\n        V[:,1] = solver(B[:,1])\n        V[:,2] = solver(B[:,2])\n        V = V*(1-self.beta)\n        V = V.reshape(h1,w1,k)\n        V = V[2:2+h,2:2+w,:]\n        \n        img = Image.fromarray(np.uint8(np.clip(V * 255., 0, 255.)))\n        return img\n\n    # Returns sparse matting laplacian\n    # The implementation of the function is heavily borrowed from\n    # https://github.com/MarcoForte/closed-form-matting/blob/master/closed_form_matting.py\n    # We thank Marco Forte for sharing his code.\n    def __compute_laplacian(self, img, eps=10**(-7), win_rad=1):\n            win_size = (win_rad*2+1)**2\n            h, w, d = img.shape\n            c_h, c_w = h - 2*win_rad, w - 2*win_rad\n            win_diam = win_rad*2+1\n            indsM = np.arange(h*w).reshape((h, w))\n            ravelImg = img.reshape(h*w, d)\n            win_inds = self.__rolling_block(indsM, block=(win_diam, win_diam))\n            win_inds = win_inds.reshape(c_h, c_w, win_size)\n            winI = ravelImg[win_inds]\n            win_mu = np.mean(winI, axis=2, keepdims=True)\n            win_var = np.einsum('...ji,...jk ->...ik', winI, winI)/win_size - np.einsum('...ji,...jk ->...ik', win_mu, win_mu)\n            inv = np.linalg.inv(win_var + (eps/win_size)*np.eye(3))\n            X = np.einsum('...ij,...jk->...ik', winI - win_mu, inv)\n            vals = (1/win_size)*(1 + np.einsum('...ij,...kj->...ik', X, winI - win_mu))\n            nz_indsCol = np.tile(win_inds, win_size).ravel()\n            nz_indsRow = np.repeat(win_inds, win_size).ravel()\n            nz_indsVal = vals.ravel()\n            L = scipy.sparse.coo_matrix((nz_indsVal, (nz_indsRow, nz_indsCol)), shape=(h*w, h*w))\n            return L\n\n    def __replication_padding(self, arr,pad):\n            h,w,c = arr.shape\n            ans = np.zeros((h+pad*2,w+pad*2,c))\n            for i in range(c):\n                    ans[:,:,i] = np.pad(arr[:,:,i],pad_width=(pad,pad),mode='edge')\n            return ans\n\n    def __rolling_block(self, A, block=(3, 3)):\n        shape = (A.shape[0] - block[0] + 1, A.shape[1] - block[1] + 1) + block\n        strides = (A.strides[0], A.strides[1]) + A.strides\n        return as_strided(A, shape=shape, strides=strides)"
  },
  {
    "path": "photo_wct.py",
    "content": "\"\"\"\nCopyright (C) 2018 NVIDIA Corporation.  All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\n\nimport numpy as np\nfrom PIL import Image\nimport torch\nimport torch.nn as nn\nfrom models import VGGEncoder, VGGDecoder\n\n\nclass PhotoWCT(nn.Module):\n    def __init__(self):\n        super(PhotoWCT, self).__init__()\n        self.e1 = VGGEncoder(1)\n        self.d1 = VGGDecoder(1)\n        self.e2 = VGGEncoder(2)\n        self.d2 = VGGDecoder(2)\n        self.e3 = VGGEncoder(3)\n        self.d3 = VGGDecoder(3)\n        self.e4 = VGGEncoder(4)\n        self.d4 = VGGDecoder(4)\n    \n    def transform(self, cont_img, styl_img, cont_seg, styl_seg):\n        self.__compute_label_info(cont_seg, styl_seg)\n\n        sF4, sF3, sF2, sF1 = self.e4.forward_multiple(styl_img)\n\n        cF4, cpool_idx, cpool1, cpool_idx2, cpool2, cpool_idx3, cpool3 = self.e4(cont_img)\n        sF4 = sF4.data.squeeze(0)\n        cF4 = cF4.data.squeeze(0)\n        # print(cont_seg)\n        csF4 = self.__feature_wct(cF4, sF4, cont_seg, styl_seg)\n        Im4 = self.d4(csF4, cpool_idx, cpool1, cpool_idx2, cpool2, cpool_idx3, cpool3)\n\n        cF3, cpool_idx, cpool1, cpool_idx2, cpool2 = self.e3(Im4)\n        sF3 = sF3.data.squeeze(0)\n        cF3 = cF3.data.squeeze(0)\n        csF3 = self.__feature_wct(cF3, sF3, cont_seg, styl_seg)\n        Im3 = self.d3(csF3, cpool_idx, cpool1, cpool_idx2, cpool2)\n\n        cF2, cpool_idx, cpool = self.e2(Im3)\n        sF2 = sF2.data.squeeze(0)\n        cF2 = cF2.data.squeeze(0)\n        csF2 = self.__feature_wct(cF2, sF2, cont_seg, styl_seg)\n        Im2 = self.d2(csF2, cpool_idx, cpool)\n\n        cF1 = self.e1(Im2)\n        sF1 = sF1.data.squeeze(0)\n        cF1 = cF1.data.squeeze(0)\n        csF1 = self.__feature_wct(cF1, sF1, cont_seg, styl_seg)\n        Im1 = self.d1(csF1)\n        return Im1\n\n    def __compute_label_info(self, cont_seg, styl_seg):\n        if cont_seg.size == False or styl_seg.size == False:\n            return\n        max_label = np.max(cont_seg) + 1\n        self.label_set = np.unique(cont_seg)\n        self.label_indicator = np.zeros(max_label)\n        for l in self.label_set:\n            # if l==0:\n            #   continue\n            is_valid = lambda a, b: a > 10 and b > 10 and a / b < 100 and b / a < 100\n            o_cont_mask = np.where(cont_seg.reshape(cont_seg.shape[0] * cont_seg.shape[1]) == l)\n            o_styl_mask = np.where(styl_seg.reshape(styl_seg.shape[0] * styl_seg.shape[1]) == l)\n            self.label_indicator[l] = is_valid(o_cont_mask[0].size, o_styl_mask[0].size)\n\n    def __feature_wct(self, cont_feat, styl_feat, cont_seg, styl_seg):\n        cont_c, cont_h, cont_w = cont_feat.size(0), cont_feat.size(1), cont_feat.size(2)\n        styl_c, styl_h, styl_w = styl_feat.size(0), styl_feat.size(1), styl_feat.size(2)\n        cont_feat_view = cont_feat.view(cont_c, -1).clone()\n        styl_feat_view = styl_feat.view(styl_c, -1).clone()\n\n        if cont_seg.size == False or styl_seg.size == False:\n            target_feature = self.__wct_core(cont_feat_view, styl_feat_view)\n        else:\n            target_feature = cont_feat.view(cont_c, -1).clone()\n            if len(cont_seg.shape) == 2:\n                t_cont_seg = np.asarray(Image.fromarray(cont_seg).resize((cont_w, cont_h), Image.NEAREST))\n            else:\n                t_cont_seg = np.asarray(Image.fromarray(cont_seg, mode='RGB').resize((cont_w, cont_h), Image.NEAREST))\n            if len(styl_seg.shape) == 2:\n                t_styl_seg = np.asarray(Image.fromarray(styl_seg).resize((styl_w, styl_h), Image.NEAREST))\n            else:\n                t_styl_seg = np.asarray(Image.fromarray(styl_seg, mode='RGB').resize((styl_w, styl_h), Image.NEAREST))\n\n            for l in self.label_set:\n                if self.label_indicator[l] == 0:\n                    continue\n                cont_mask = np.where(t_cont_seg.reshape(t_cont_seg.shape[0] * t_cont_seg.shape[1]) == l)\n                styl_mask = np.where(t_styl_seg.reshape(t_styl_seg.shape[0] * t_styl_seg.shape[1]) == l)\n                if cont_mask[0].size <= 0 or styl_mask[0].size <= 0:\n                    continue\n\n                cont_indi = torch.LongTensor(cont_mask[0])\n                styl_indi = torch.LongTensor(styl_mask[0])\n                if self.is_cuda:\n                    cont_indi = cont_indi.cuda(0)\n                    styl_indi = styl_indi.cuda(0)\n\n                cFFG = torch.index_select(cont_feat_view, 1, cont_indi)\n                sFFG = torch.index_select(styl_feat_view, 1, styl_indi)\n                # print(len(cont_indi))\n                # print(len(styl_indi))\n                tmp_target_feature = self.__wct_core(cFFG, sFFG)\n                # print(tmp_target_feature.size())\n                if torch.__version__ >= \"0.4.0\":\n                    # This seems to be a bug in PyTorch 0.4.0 to me.\n                    new_target_feature = torch.transpose(target_feature, 1, 0)\n                    new_target_feature.index_copy_(0, cont_indi, \\\n                            torch.transpose(tmp_target_feature,1,0))\n                    target_feature = torch.transpose(new_target_feature, 1, 0)\n                else:\n                    target_feature.index_copy_(1, cont_indi, tmp_target_feature)\n\n        target_feature = target_feature.view_as(cont_feat)\n        ccsF = target_feature.float().unsqueeze(0)\n        return ccsF\n    \n    def __wct_core(self, cont_feat, styl_feat):\n        cFSize = cont_feat.size()\n        c_mean = torch.mean(cont_feat, 1)  # c x (h x w)\n        c_mean = c_mean.unsqueeze(1).expand_as(cont_feat)\n        cont_feat = cont_feat - c_mean\n        \n        iden = torch.eye(cFSize[0])  # .double()\n        if self.is_cuda:\n            iden = iden.cuda()\n        \n        contentConv = torch.mm(cont_feat, cont_feat.t()).div(cFSize[1] - 1) + iden\n        # del iden\n        c_u, c_e, c_v = torch.svd(contentConv, some=False)\n        # c_e2, c_v = torch.eig(contentConv, True)\n        # c_e = c_e2[:,0]\n        \n        k_c = cFSize[0]\n        for i in range(cFSize[0] - 1, -1, -1):\n            if c_e[i] >= 0.00001:\n                k_c = i + 1\n                break\n        \n        sFSize = styl_feat.size()\n        s_mean = torch.mean(styl_feat, 1)\n        styl_feat = styl_feat - s_mean.unsqueeze(1).expand_as(styl_feat)\n        styleConv = torch.mm(styl_feat, styl_feat.t()).div(sFSize[1] - 1)\n        s_u, s_e, s_v = torch.svd(styleConv, some=False)\n        \n        k_s = sFSize[0]\n        for i in range(sFSize[0] - 1, -1, -1):\n            if s_e[i] >= 0.00001:\n                k_s = i + 1\n                break\n        \n        c_d = (c_e[0:k_c]).pow(-0.5)\n        step1 = torch.mm(c_v[:, 0:k_c], torch.diag(c_d))\n        step2 = torch.mm(step1, (c_v[:, 0:k_c].t()))\n        whiten_cF = torch.mm(step2, cont_feat)\n\n        s_d = (s_e[0:k_s]).pow(0.5)\n        targetFeature = torch.mm(torch.mm(torch.mm(s_v[:, 0:k_s], torch.diag(s_d)), (s_v[:, 0:k_s].t())), whiten_cF)\n        targetFeature = targetFeature + s_mean.unsqueeze(1).expand_as(targetFeature)\n        return targetFeature\n    \n    @property\n    def is_cuda(self):\n        return next(self.parameters()).is_cuda\n\n    def forward(self, *input):\n        pass"
  },
  {
    "path": "process_stylization.py",
    "content": "\"\"\"\nCopyright (C) 2018 NVIDIA Corporation.  All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\nfrom __future__ import print_function\nimport time\nimport numpy as np\nfrom PIL import Image\nfrom torch.autograd import Variable\nimport torchvision.transforms as transforms\nimport torchvision.utils as utils\nimport torch.nn as nn\nimport torch\nfrom smooth_filter import smooth_filter\n\n\nclass ReMapping:\n    def __init__(self):\n        self.remapping = []\n\n    def process(self, seg):\n        new_seg = seg.copy()\n        for k, v in self.remapping.items():\n            new_seg[seg == k] = v\n        return new_seg\n\n\nclass Timer:\n    def __init__(self, msg):\n        self.msg = msg\n        self.start_time = None\n\n    def __enter__(self):\n        self.start_time = time.time()\n\n    def __exit__(self, exc_type, exc_value, exc_tb):\n        print(self.msg % (time.time() - self.start_time))\n\n\ndef memory_limit_image_resize(cont_img):\n    # prevent too small or too big images\n    MINSIZE=256\n    MAXSIZE=960\n    orig_width = cont_img.width\n    orig_height = cont_img.height\n    if max(cont_img.width,cont_img.height) < MINSIZE:\n        if cont_img.width > cont_img.height:\n            cont_img.thumbnail((int(cont_img.width*1.0/cont_img.height*MINSIZE), MINSIZE), Image.BICUBIC)\n        else:\n            cont_img.thumbnail((MINSIZE, int(cont_img.height*1.0/cont_img.width*MINSIZE)), Image.BICUBIC)\n    if min(cont_img.width,cont_img.height) > MAXSIZE:\n        if cont_img.width > cont_img.height:\n            cont_img.thumbnail((MAXSIZE, int(cont_img.height*1.0/cont_img.width*MAXSIZE)), Image.BICUBIC)\n        else:\n            cont_img.thumbnail(((int(cont_img.width*1.0/cont_img.height*MAXSIZE), MAXSIZE)), Image.BICUBIC)\n    print(\"Resize image: (%d,%d)->(%d,%d)\" % (orig_width, orig_height, cont_img.width, cont_img.height))\n    return cont_img.width, cont_img.height\n\n\ndef stylization(stylization_module, smoothing_module, content_image_path, style_image_path, content_seg_path, style_seg_path, output_image_path,\n                cuda, save_intermediate, no_post, cont_seg_remapping=None, styl_seg_remapping=None):\n    # Load image\n    with torch.no_grad():\n        cont_img = Image.open(content_image_path).convert('RGB')\n        styl_img = Image.open(style_image_path).convert('RGB')\n\n        new_cw, new_ch = memory_limit_image_resize(cont_img)\n        new_sw, new_sh = memory_limit_image_resize(styl_img)\n        cont_pilimg = cont_img.copy()\n        cw = cont_pilimg.width\n        ch = cont_pilimg.height\n        try:\n            cont_seg = Image.open(content_seg_path)\n            styl_seg = Image.open(style_seg_path)\n            cont_seg.resize((new_cw,new_ch),Image.NEAREST)\n            styl_seg.resize((new_sw,new_sh),Image.NEAREST)\n\n        except:\n            cont_seg = []\n            styl_seg = []\n\n        cont_img = transforms.ToTensor()(cont_img).unsqueeze(0)\n        styl_img = transforms.ToTensor()(styl_img).unsqueeze(0)\n\n        if cuda:\n            cont_img = cont_img.cuda(0)\n            styl_img = styl_img.cuda(0)\n            stylization_module.cuda(0)\n\n        # cont_img = Variable(cont_img, volatile=True)\n        # styl_img = Variable(styl_img, volatile=True)\n\n        cont_seg = np.asarray(cont_seg)\n        styl_seg = np.asarray(styl_seg)\n        if cont_seg_remapping is not None:\n            cont_seg = cont_seg_remapping.process(cont_seg)\n        if styl_seg_remapping is not None:\n            styl_seg = styl_seg_remapping.process(styl_seg)\n\n        if save_intermediate:\n            with Timer(\"Elapsed time in stylization: %f\"):\n                stylized_img = stylization_module.transform(cont_img, styl_img, cont_seg, styl_seg)\n            if ch != new_ch or cw != new_cw:\n                print(\"De-resize image: (%d,%d)->(%d,%d)\" %(new_cw,new_ch,cw,ch))\n                stylized_img = nn.functional.upsample(stylized_img, size=(ch,cw), mode='bilinear')\n            utils.save_image(stylized_img.data.cpu().float(), output_image_path, nrow=1, padding=0)\n\n            with Timer(\"Elapsed time in propagation: %f\"):\n                out_img = smoothing_module.process(output_image_path, content_image_path)\n            out_img.save(output_image_path)\n\n            if not cuda:\n                print(\"NotImplemented: The CPU version of smooth filter has not been implemented currently.\")\n                return\n\n            if no_post is False:\n                with Timer(\"Elapsed time in post processing: %f\"):\n                    out_img = smooth_filter(output_image_path, content_image_path, f_radius=15, f_edge=1e-1)\n            out_img.save(output_image_path)\n        else:\n            with Timer(\"Elapsed time in stylization: %f\"):\n                stylized_img = stylization_module.transform(cont_img, styl_img, cont_seg, styl_seg)\n            if ch != new_ch or cw != new_cw:\n                print(\"De-resize image: (%d,%d)->(%d,%d)\" %(new_cw,new_ch,cw,ch))\n                stylized_img = nn.functional.upsample(stylized_img, size=(ch,cw), mode='bilinear')\n            grid = utils.make_grid(stylized_img.data, nrow=1, padding=0)\n            ndarr = grid.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()\n            out_img = Image.fromarray(ndarr)\n\n            with Timer(\"Elapsed time in propagation: %f\"):\n                out_img = smoothing_module.process(out_img, cont_pilimg)\n\n            if no_post is False:\n                with Timer(\"Elapsed time in post processing: %f\"):\n                    out_img = smooth_filter(out_img, cont_pilimg, f_radius=15, f_edge=1e-1)\n            out_img.save(output_image_path)\n\n"
  },
  {
    "path": "process_stylization_ade20k_ssn.py",
    "content": "\"\"\"\nCopyright (C) 2018 NVIDIA Corporation.  All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\n\nfrom __future__ import print_function\nimport torch\nimport numpy as np\nfrom PIL import Image\nfrom torch.autograd import Variable\nimport torchvision.transforms as transforms\nimport torchvision.utils as utils\nimport torch.nn as nn\nfrom smooth_filter import smooth_filter\nfrom process_stylization import Timer, memory_limit_image_resize\nfrom scipy.io import loadmat\ncolors = loadmat('segmentation/data/color150.mat')['colors']\n\n\ndef overlay(img, pred_color, blend_factor=0.4):\n    import cv2\n    edges = cv2.Canny(pred_color, 20, 40)\n    edges = cv2.dilate(edges, np.ones((5,5),np.uint8), iterations=1)\n    out = (1-blend_factor)*img + blend_factor * pred_color\n    edge_pixels = (edges==255)\n    new_color = [0,0,255]\n    for i in range(0,3):\n        timg = out[:,:,i]\n        timg[edge_pixels]=new_color[i]\n        out[:,:,i] = timg\n    return out\n\n\ndef visualize_result(label_map):\n    label_map = label_map.astype('int')\n    label_map_rgb = np.zeros((label_map.shape[0], label_map.shape[1], 3), dtype=np.uint8)\n    for label in np.unique(label_map):\n        label_map_rgb += (label_map == label)[:, :, np.newaxis] * \\\n            np.tile(colors[label],(label_map.shape[0], label_map.shape[1], 1))\n    return label_map_rgb\n\n\nclass SegReMapping:\n    def __init__(self, mapping_name, min_ratio=0.02):\n        self.label_mapping = np.load(mapping_name)\n        self.min_ratio = min_ratio\n\n    def cross_remapping(self, cont_seg, styl_seg):\n        cont_label_info = []\n        new_cont_label_info = []\n        for label in np.unique(cont_seg):\n            cont_label_info.append(label)\n            new_cont_label_info.append(label)\n\n        style_label_info = []\n        new_style_label_info = []\n        for label in np.unique(styl_seg):\n            style_label_info.append(label)\n            new_style_label_info.append(label)\n\n        cont_set_diff = set(cont_label_info) - set(style_label_info)\n        # Find the labels that are not covered by the style\n        # Assign them to the best matched region in the style region\n        for s in cont_set_diff:\n            cont_label_index = cont_label_info.index(s)\n            for j in range(self.label_mapping.shape[0]):\n                new_label = self.label_mapping[j, s]\n                if new_label in style_label_info:\n                    new_cont_label_info[cont_label_index] = new_label\n                    break\n        new_cont_seg = cont_seg.copy()\n        for i,current_label in enumerate(cont_label_info):\n            new_cont_seg[(cont_seg == current_label)] = new_cont_label_info[i]\n\n        cont_label_info = []\n        for label in np.unique(new_cont_seg):\n            cont_label_info.append(label)\n        styl_set_diff = set(style_label_info) - set(cont_label_info)\n        valid_styl_set = set(style_label_info) - set(styl_set_diff)\n        for s in styl_set_diff:\n            style_label_index = style_label_info.index(s)\n            for j in range(self.label_mapping.shape[0]):\n                new_label = self.label_mapping[j, s]\n                if new_label in valid_styl_set:\n                    new_style_label_info[style_label_index] = new_label\n                    break\n        new_styl_seg = styl_seg.copy()\n        for i,current_label in enumerate(style_label_info):\n            # print(\"%d -> %d\" %(current_label,new_style_label_info[i]))\n            new_styl_seg[(styl_seg == current_label)] = new_style_label_info[i]\n\n        return new_cont_seg, new_styl_seg\n\n    def self_remapping(self, seg):\n        init_ratio = self.min_ratio\n        # Assign label with small portions to label with large portion\n        new_seg = seg.copy()\n        [h,w] = new_seg.shape\n        n_pixels = h*w\n        # First scan through what are the available labels and their sizes\n        label_info = []\n        ratio_info = []\n        new_label_info = []\n        for label in np.unique(seg):\n            ratio = np.sum(np.float32((seg == label))[:])/n_pixels\n            label_info.append(label)\n            new_label_info.append(label)\n            ratio_info.append(ratio)\n        for i,current_label in enumerate(label_info):\n            if ratio_info[i] < init_ratio:\n                for j in range(self.label_mapping.shape[0]):\n                    new_label = self.label_mapping[j,current_label]\n                    if new_label in label_info:\n                        index = label_info.index(new_label)\n                        if index >= 0:\n                            if ratio_info[index] >= init_ratio:\n                                new_label_info[i] = new_label\n                                break\n        for i,current_label in enumerate(label_info):\n            new_seg[(seg == current_label)] = new_label_info[i]\n        return new_seg\n\n\ndef stylization(stylization_module, smoothing_module, content_image_path, style_image_path, content_seg_path,\n                style_seg_path, output_image_path,\n                cuda, save_intermediate, no_post, label_remapping, output_visualization=False):\n    # Load image\n    with torch.no_grad():\n        cont_img = Image.open(content_image_path).convert('RGB')\n        styl_img = Image.open(style_image_path).convert('RGB')\n\n        new_cw, new_ch = memory_limit_image_resize(cont_img)\n        new_sw, new_sh = memory_limit_image_resize(styl_img)\n        cont_pilimg = cont_img.copy()\n        styl_pilimg = styl_img.copy()\n        cw = cont_pilimg.width\n        ch = cont_pilimg.height\n        try:\n            cont_seg = Image.open(content_seg_path)\n            styl_seg = Image.open(style_seg_path)\n            cont_seg.resize((new_cw, new_ch), Image.NEAREST)\n            styl_seg.resize((new_sw, new_sh), Image.NEAREST)\n\n        except:\n            cont_seg = []\n            styl_seg = []\n\n        cont_img = transforms.ToTensor()(cont_img).unsqueeze(0)\n        styl_img = transforms.ToTensor()(styl_img).unsqueeze(0)\n\n        if cuda:\n            cont_img = cont_img.cuda(0)\n            styl_img = styl_img.cuda(0)\n            stylization_module.cuda(0)\n\n        # cont_img = Variable(cont_img, volatile=True)\n        # styl_img = Variable(styl_img, volatile=True)\n\n        cont_seg = np.asarray(cont_seg)\n        styl_seg = np.asarray(styl_seg)\n\n        cont_seg = label_remapping.self_remapping(cont_seg)\n        styl_seg = label_remapping.self_remapping(styl_seg)\n        cont_seg, styl_seg = label_remapping.cross_remapping(cont_seg, styl_seg)\n\n        if output_visualization:\n            import cv2\n            cont_seg_vis = visualize_result(cont_seg)\n            styl_seg_vis = visualize_result(styl_seg)\n            cont_seg_vis = overlay(cv2.imread(content_image_path), cont_seg_vis)\n            styl_seg_vis = overlay(cv2.imread(style_image_path), styl_seg_vis)\n            cv2.imwrite(content_seg_path + '.visualization.jpg', cont_seg_vis)\n            cv2.imwrite(style_seg_path + '.visualization.jpg', styl_seg_vis)\n\n        if save_intermediate:\n            with Timer(\"Elapsed time in stylization: %f\"):\n                stylized_img = stylization_module.transform(cont_img, styl_img, cont_seg, styl_seg)\n            if ch != new_ch or cw != new_cw:\n                print(\"De-resize image: (%d,%d)->(%d,%d)\" % (new_cw, new_ch, cw, ch))\n                stylized_img = nn.functional.upsample(stylized_img, size=(ch, cw), mode='bilinear')\n            utils.save_image(stylized_img.data.cpu().float(), output_image_path, nrow=1, padding=0)\n\n            with Timer(\"Elapsed time in propagation: %f\"):\n                out_img = smoothing_module.process(output_image_path, content_image_path)\n            out_img.save(output_image_path)\n\n            if not cuda:\n                print(\"NotImplemented: The CPU version of smooth filter has not been implemented currently.\")\n                return\n\n            if no_post is False:\n                with Timer(\"Elapsed time in post processing: %f\"):\n                    out_img = smooth_filter(output_image_path, content_image_path, f_radius=15, f_edge=1e-1)\n            out_img.save(output_image_path)\n        else:\n            with Timer(\"Elapsed time in stylization: %f\"):\n                stylized_img = stylization_module.transform(cont_img, styl_img, cont_seg, styl_seg)\n            if ch != new_ch or cw != new_cw:\n                print(\"De-resize image: (%d,%d)->(%d,%d)\" % (new_cw, new_ch, cw, ch))\n                stylized_img = nn.functional.upsample(stylized_img, size=(ch, cw), mode='bilinear')\n            grid = utils.make_grid(stylized_img.data, nrow=1, padding=0)\n            ndarr = grid.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()\n            out_img = Image.fromarray(ndarr)\n\n            with Timer(\"Elapsed time in propagation: %f\"):\n                out_img = smoothing_module.process(out_img, cont_pilimg)\n\n            if no_post is False:\n                with Timer(\"Elapsed time in post processing: %f\"):\n                    out_img = smooth_filter(out_img, cont_pilimg, f_radius=15, f_edge=1e-1)\n            out_img.save(output_image_path)\n    return\n\n"
  },
  {
    "path": "process_stylization_folder.py",
    "content": "\"\"\"\nCopyright (C) 2018 NVIDIA Corporation.  All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\nfrom __future__ import print_function\nimport argparse\nimport os\nimport torch\nfrom photo_wct import PhotoWCT\nimport process_stylization\n\nparser = argparse.ArgumentParser(description='Photorealistic Image Stylization')\nparser.add_argument('--model', default='./PhotoWCTModels/photo_wct.pth')\nparser.add_argument('--cuda', type=bool, default=True, help='Enable CUDA.')\nparser.add_argument('--save_intermediate', action='store_true', default=False)\nparser.add_argument('--fast', action='store_true', default=False)\nparser.add_argument('--no_post', action='store_true', default=False)\nparser.add_argument('--folder', type=str, default='examples')\nparser.add_argument('--beta', type=float, default=0.9999)\nparser.add_argument('--cont_img_ext', type=str, default='.png')\nparser.add_argument('--cont_seg_ext', type=str, default='.pgm')\nparser.add_argument('--styl_img_ext', type=str, default='.png')\nparser.add_argument('--styl_seg_ext', type=str, default='.pgm')\nargs = parser.parse_args()\n\nfolder = args.folder\ncont_img_folder = os.path.join(folder, 'content_img')\ncont_seg_folder = os.path.join(folder, 'content_seg')\nstyl_img_folder = os.path.join(folder, 'style_img')\nstyl_seg_folder = os.path.join(folder, 'style_seg')\noutp_img_folder = os.path.join(folder, 'results')\ncont_img_list = [f for f in os.listdir(cont_img_folder) if os.path.isfile(os.path.join(cont_img_folder, f))]\ncont_img_list.sort()\n\n# Load model\np_wct = PhotoWCT()\np_wct.load_state_dict(torch.load(args.model))\n# Load Propagator\nif args.fast:\n    from photo_gif import GIFSmoothing\n    p_pro = GIFSmoothing(r=35, eps=0.01)\nelse:\n    from photo_smooth import Propagator\n    p_pro = Propagator(args.beta)\n\nfor f in cont_img_list:\n    content_image_path = os.path.join(cont_img_folder, f)\n    content_seg_path = os.path.join(cont_seg_folder, f).replace(args.cont_img_ext, args.cont_seg_ext)\n    style_image_path = os.path.join(styl_img_folder, f)\n    style_seg_path = os.path.join(styl_seg_folder, f).replace(args.styl_img_ext, args.styl_seg_ext)\n    output_image_path = os.path.join(outp_img_folder, f)\n\n    print(\"Content image: \" + content_image_path )\n    if os.path.isfile(content_seg_path):\n        print(\"Content mask: \" + content_seg_path )\n\n    print(\"Style image: \" + style_image_path )\n    if os.path.isfile(style_seg_path):\n        print(\"Style mask: \" + style_seg_path )\n\n    process_stylization.stylization(\n        stylization_module=p_wct,\n        smoothing_module=p_pro,\n        content_image_path=content_image_path,\n        style_image_path=style_image_path,\n        content_seg_path=content_seg_path,\n        style_seg_path=style_seg_path,\n        output_image_path=output_image_path,\n        cuda=args.cuda,\n        save_intermediate=args.save_intermediate,\n        no_post=args.no_post\n    )\n"
  },
  {
    "path": "smooth_filter.py",
    "content": "\"\"\"\nCopyright (C) 2018 NVIDIA Corporation.  All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\nsrc = '''\n\t#include \"/usr/local/cuda/include/math_functions.h\"\n\t#define TB 256\n\t#define EPS 1e-7\n\n\t__device__ bool InverseMat4x4(double m_in[4][4], double inv_out[4][4]) {\n\t\tdouble m[16], inv[16];\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tfor (int j = 0; j < 4; j++) {\n\t\t\t\tm[i * 4 + j] = m_in[i][j];\n\t\t\t}\n\t\t}\n\n\t    inv[0] = m[5]  * m[10] * m[15] -\n\t             m[5]  * m[11] * m[14] -\n\t             m[9]  * m[6]  * m[15] +\n\t             m[9]  * m[7]  * m[14] +\n\t             m[13] * m[6]  * m[11] -\n\t             m[13] * m[7]  * m[10];\n\n\t    inv[4] = -m[4]  * m[10] * m[15] +\n\t              m[4]  * m[11] * m[14] +\n\t              m[8]  * m[6]  * m[15] -\n\t              m[8]  * m[7]  * m[14] -\n\t              m[12] * m[6]  * m[11] +\n\t              m[12] * m[7]  * m[10];\n\n\t    inv[8] = m[4]  * m[9] * m[15] -\n\t             m[4]  * m[11] * m[13] -\n\t             m[8]  * m[5] * m[15] +\n\t             m[8]  * m[7] * m[13] +\n\t             m[12] * m[5] * m[11] -\n\t             m[12] * m[7] * m[9];\n\n\t    inv[12] = -m[4]  * m[9] * m[14] +\n\t               m[4]  * m[10] * m[13] +\n\t               m[8]  * m[5] * m[14] -\n\t               m[8]  * m[6] * m[13] -\n\t               m[12] * m[5] * m[10] +\n\t               m[12] * m[6] * m[9];\n\n\t    inv[1] = -m[1]  * m[10] * m[15] +\n\t              m[1]  * m[11] * m[14] +\n\t              m[9]  * m[2] * m[15] -\n\t              m[9]  * m[3] * m[14] -\n\t              m[13] * m[2] * m[11] +\n\t              m[13] * m[3] * m[10];\n\n\t    inv[5] = m[0]  * m[10] * m[15] -\n\t             m[0]  * m[11] * m[14] -\n\t             m[8]  * m[2] * m[15] +\n\t             m[8]  * m[3] * m[14] +\n\t             m[12] * m[2] * m[11] -\n\t             m[12] * m[3] * m[10];\n\n\t    inv[9] = -m[0]  * m[9] * m[15] +\n\t              m[0]  * m[11] * m[13] +\n\t              m[8]  * m[1] * m[15] -\n\t              m[8]  * m[3] * m[13] -\n\t              m[12] * m[1] * m[11] +\n\t              m[12] * m[3] * m[9];\n\n\t    inv[13] = m[0]  * m[9] * m[14] -\n\t              m[0]  * m[10] * m[13] -\n\t              m[8]  * m[1] * m[14] +\n\t              m[8]  * m[2] * m[13] +\n\t              m[12] * m[1] * m[10] -\n\t              m[12] * m[2] * m[9];\n\n\t    inv[2] = m[1]  * m[6] * m[15] -\n\t             m[1]  * m[7] * m[14] -\n\t             m[5]  * m[2] * m[15] +\n\t             m[5]  * m[3] * m[14] +\n\t             m[13] * m[2] * m[7] -\n\t             m[13] * m[3] * m[6];\n\n\t    inv[6] = -m[0]  * m[6] * m[15] +\n\t              m[0]  * m[7] * m[14] +\n\t              m[4]  * m[2] * m[15] -\n\t              m[4]  * m[3] * m[14] -\n\t              m[12] * m[2] * m[7] +\n\t              m[12] * m[3] * m[6];\n\n\t    inv[10] = m[0]  * m[5] * m[15] -\n\t              m[0]  * m[7] * m[13] -\n\t              m[4]  * m[1] * m[15] +\n\t              m[4]  * m[3] * m[13] +\n\t              m[12] * m[1] * m[7] -\n\t              m[12] * m[3] * m[5];\n\n\t    inv[14] = -m[0]  * m[5] * m[14] +\n\t               m[0]  * m[6] * m[13] +\n\t               m[4]  * m[1] * m[14] -\n\t               m[4]  * m[2] * m[13] -\n\t               m[12] * m[1] * m[6] +\n\t               m[12] * m[2] * m[5];\n\n\t    inv[3] = -m[1] * m[6] * m[11] +\n\t              m[1] * m[7] * m[10] +\n\t              m[5] * m[2] * m[11] -\n\t              m[5] * m[3] * m[10] -\n\t              m[9] * m[2] * m[7] +\n\t              m[9] * m[3] * m[6];\n\n\t    inv[7] = m[0] * m[6] * m[11] -\n\t             m[0] * m[7] * m[10] -\n\t             m[4] * m[2] * m[11] +\n\t             m[4] * m[3] * m[10] +\n\t             m[8] * m[2] * m[7] -\n\t             m[8] * m[3] * m[6];\n\n\t    inv[11] = -m[0] * m[5] * m[11] +\n\t               m[0] * m[7] * m[9] +\n\t               m[4] * m[1] * m[11] -\n\t               m[4] * m[3] * m[9] -\n\t               m[8] * m[1] * m[7] +\n\t               m[8] * m[3] * m[5];\n\n\t    inv[15] = m[0] * m[5] * m[10] -\n\t              m[0] * m[6] * m[9] -\n\t              m[4] * m[1] * m[10] +\n\t              m[4] * m[2] * m[9] +\n\t              m[8] * m[1] * m[6] -\n\t              m[8] * m[2] * m[5];\n\n\t    double det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];\n\n\t    if (abs(det) < 1e-9) {\n\t        return false;\n\t    }\n\n\n\t    det = 1.0 / det;\n\n\t    for (int i = 0; i < 4; i++) {\n\t    \tfor (int j = 0; j < 4; j++) {\n\t    \t\tinv_out[i][j] = inv[i * 4 + j] * det;\n\t    \t}\n\t    }\n\n\t    return true;\n\t}\n\n  extern \"C\"\n\t__global__ void best_local_affine_kernel(\n\t\tfloat *output, float *input, float *affine_model,\n\t\tint h, int w, float epsilon, int kernel_radius\n\t)\n\t{\n\t\tint size = h * w;\n\t\tint id = blockIdx.x * blockDim.x + threadIdx.x;\n\n\t\tif (id < size) {\n\t\t\tint x = id % w, y = id / w;\n\n\t\t\tdouble Mt_M[4][4] = {}; // 4x4\n\t\t\tdouble invMt_M[4][4] = {};\n\t\t\tdouble Mt_S[3][4] = {}; // RGB -> 1x4\n\t\t\tdouble A[3][4] = {};\n\t\t\tfor (int i = 0; i < 4; i++)\n\t\t\t\tfor (int j = 0; j < 4; j++) {\n\t\t\t\t\tMt_M[i][j] = 0, invMt_M[i][j] = 0;\n\t\t\t\t\tif (i != 3) {\n\t\t\t\t\t\tMt_S[i][j] = 0, A[i][j] = 0;\n\t\t\t\t\t\tif (i == j)\n\t\t\t\t    \t\tMt_M[i][j] = 1e-3;\n\t\t\t\t    }\n\t\t\t\t}\n\n\t\t\tfor (int dy = -kernel_radius; dy <= kernel_radius; dy++) {\n\t\t\t\tfor (int dx = -kernel_radius; dx <= kernel_radius; dx++) {\n\n\t\t\t\t\tint xx = x + dx, yy = y + dy;\n\t\t\t\t\tint id2 = yy * w + xx;\n\n\t\t\t\t\tif (0 <= xx && xx < w && 0 <= yy && yy < h) {\n\n\t\t\t\t\t\tMt_M[0][0] += input[id2 + 2*size] * input[id2 + 2*size];\n\t\t\t\t\t\tMt_M[0][1] += input[id2 + 2*size] * input[id2 + size];\n\t\t\t\t\t\tMt_M[0][2] += input[id2 + 2*size] * input[id2];\n\t\t\t\t\t\tMt_M[0][3] += input[id2 + 2*size];\n\n\t\t\t\t\t\tMt_M[1][0] += input[id2 + size] * input[id2 + 2*size];\n\t\t\t\t\t\tMt_M[1][1] += input[id2 + size] * input[id2 + size];\n\t\t\t\t\t\tMt_M[1][2] += input[id2 + size] * input[id2];\n\t\t\t\t\t\tMt_M[1][3] += input[id2 + size];\n\n\t\t\t\t\t\tMt_M[2][0] += input[id2] * input[id2 + 2*size];\n\t\t\t\t\t\tMt_M[2][1] += input[id2] * input[id2 + size];\n\t\t\t\t\t\tMt_M[2][2] += input[id2] * input[id2];\n\t\t\t\t\t\tMt_M[2][3] += input[id2];\n\n\t\t\t\t\t\tMt_M[3][0] += input[id2 + 2*size];\n\t\t\t\t\t\tMt_M[3][1] += input[id2 + size];\n\t\t\t\t\t\tMt_M[3][2] += input[id2];\n\t\t\t\t\t\tMt_M[3][3] += 1;\n\n\t\t\t\t\t\tMt_S[0][0] += input[id2 + 2*size] * output[id2 + 2*size];\n\t\t\t\t\t\tMt_S[0][1] += input[id2 + size] * output[id2 + 2*size];\n\t\t\t\t\t\tMt_S[0][2] += input[id2] * output[id2 + 2*size];\n\t\t\t\t\t\tMt_S[0][3] += output[id2 + 2*size];\n\n\t\t\t\t\t\tMt_S[1][0] += input[id2 + 2*size] * output[id2 + size];\n\t\t\t\t\t\tMt_S[1][1] += input[id2 + size] * output[id2 + size];\n\t\t\t\t\t\tMt_S[1][2] += input[id2] * output[id2 + size];\n\t\t\t\t\t\tMt_S[1][3] += output[id2 + size];\n\n\t\t\t\t\t\tMt_S[2][0] += input[id2 + 2*size] * output[id2];\n\t\t\t\t\t\tMt_S[2][1] += input[id2 + size] * output[id2];\n\t\t\t\t\t\tMt_S[2][2] += input[id2] * output[id2];\n\t\t\t\t\t\tMt_S[2][3] += output[id2];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbool success = InverseMat4x4(Mt_M, invMt_M);\n\n\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\tfor (int j = 0; j < 4; j++) {\n\t\t\t\t\tfor (int k = 0; k < 4; k++) {\n\t\t\t\t\t\tA[i][j] += invMt_M[j][k] * Mt_S[i][k];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\tfor (int j = 0; j < 4; j++) {\n\t\t\t\t\tint affine_id = i * 4 + j;\n\t\t\t\t\taffine_model[12 * id + affine_id] = A[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ;\n\t}\n\n  extern \"C\"\n\t__global__ void bilateral_smooth_kernel(\n\t\tfloat *affine_model, float *filtered_affine_model, float *guide,\n\t\tint h, int w, int kernel_radius, float sigma1, float sigma2\n\t)\n\t{\n\t\tint id = blockIdx.x * blockDim.x + threadIdx.x;\n\t\tint size = h * w;\n\t\tif (id < size) {\n\t\t\tint x = id % w;\n\t\t\tint y = id / w;\n\n\t\t\tdouble sum_affine[12] = {};\n\t\t\tdouble sum_weight = 0;\n\t\t\tfor (int dx = -kernel_radius; dx <= kernel_radius; dx++) {\n\t\t\t\tfor (int dy = -kernel_radius; dy <= kernel_radius; dy++) {\n\t\t\t\t\tint yy = y + dy, xx = x + dx;\n\t\t\t\t\tint id2 = yy * w + xx;\n\t\t\t\t\tif (0 <= xx && xx < w && 0 <= yy && yy < h) {\n\t\t\t\t\t\tfloat color_diff1 = guide[yy*w + xx] - guide[y*w + x];\n\t\t\t\t\t\tfloat color_diff2 = guide[yy*w + xx + size] - guide[y*w + x + size];\n\t\t\t\t\t\tfloat color_diff3 = guide[yy*w + xx + 2*size] - guide[y*w + x + 2*size];\n\t\t\t\t\t\tfloat color_diff_sqr =\n\t\t\t\t\t\t\t(color_diff1*color_diff1 + color_diff2*color_diff2 + color_diff3*color_diff3) / 3;\n\n\t\t\t\t\t\tfloat v1 = exp(-(dx * dx + dy * dy) / (2 * sigma1 * sigma1));\n\t\t\t\t\t\tfloat v2 = exp(-(color_diff_sqr) / (2 * sigma2 * sigma2));\n\t\t\t\t\t\tfloat weight = v1 * v2;\n\n\t\t\t\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\t\t\t\tfor (int j = 0; j < 4; j++) {\n\t\t\t\t\t\t\t\tint affine_id = i * 4 + j;\n\t\t\t\t\t\t\t\tsum_affine[affine_id] += weight * affine_model[id2*12 + affine_id];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsum_weight += weight;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\tfor (int j = 0; j < 4; j++) {\n\t\t\t\t\tint affine_id = i * 4 + j;\n\t\t\t\t\tfiltered_affine_model[id*12 + affine_id] = sum_affine[affine_id] / sum_weight;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ;\n\t}\n\n\n  extern \"C\"\n\t__global__ void reconstruction_best_kernel(\n\t\tfloat *input, float *filtered_affine_model, float *filtered_best_output,\n\t\tint h, int w\n\t)\n\t{\n\t\tint id = blockIdx.x * blockDim.x + threadIdx.x;\n\t\tint size = h * w;\n\t\tif (id < size) {\n\t\t\tdouble out1 =\n\t\t\t\tinput[id + 2*size] * filtered_affine_model[id*12 + 0] + // A[0][0] +\n\t\t\t\tinput[id + size]   * filtered_affine_model[id*12 + 1] + // A[0][1] +\n\t\t\t\tinput[id]          * filtered_affine_model[id*12 + 2] + // A[0][2] +\n\t\t\t\t\t\t\t\t\t filtered_affine_model[id*12 + 3]; //A[0][3];\n\t\t\tdouble out2 =\n\t\t\t\tinput[id + 2*size] * filtered_affine_model[id*12 + 4] + //A[1][0] +\n\t\t\t\tinput[id + size]   * filtered_affine_model[id*12 + 5] + //A[1][1] +\n\t\t\t\tinput[id]          * filtered_affine_model[id*12 + 6] + //A[1][2] +\n\t\t\t\t\t\t\t\t\t filtered_affine_model[id*12 + 7]; //A[1][3];\n\t\t\tdouble out3 =\n\t\t\t\tinput[id + 2*size] * filtered_affine_model[id*12 + 8] + //A[2][0] +\n\t\t\t\tinput[id + size]   * filtered_affine_model[id*12 + 9] + //A[2][1] +\n\t\t\t\tinput[id]          * filtered_affine_model[id*12 + 10] + //A[2][2] +\n\t\t\t\t\t\t\t\t\t filtered_affine_model[id*12 + 11]; // A[2][3];\n\n\t\t\tfiltered_best_output[id] = out1;\n\t\t\tfiltered_best_output[id + size] = out2;\n\t\t\tfiltered_best_output[id + 2*size] = out3;\n\t\t}\n\t\treturn ;\n\t}\n\t'''\n\nimport torch\nimport numpy as np\nfrom PIL import Image\nfrom cupy.cuda import function\nfrom pynvrtc.compiler import Program\nfrom collections import namedtuple\n\n\ndef smooth_local_affine(output_cpu, input_cpu, epsilon, patch, h, w, f_r, f_e):\n    # program = Program(src.encode('utf-8'), 'best_local_affine_kernel.cu'.encode('utf-8'))\n    # ptx = program.compile(['-I/usr/local/cuda/include'.encode('utf-8')])\n    program = Program(src, 'best_local_affine_kernel.cu')\n    ptx = program.compile(['-I/usr/local/cuda/include'])\n    m = function.Module()\n    m.load(bytes(ptx.encode()))\n\n    _reconstruction_best_kernel = m.get_function('reconstruction_best_kernel')\n    _bilateral_smooth_kernel = m.get_function('bilateral_smooth_kernel')\n    _best_local_affine_kernel = m.get_function('best_local_affine_kernel')\n    Stream = namedtuple('Stream', ['ptr'])\n    s = Stream(ptr=torch.cuda.current_stream().cuda_stream)\n\n    filter_radius = f_r\n    sigma1 = filter_radius / 3\n    sigma2 = f_e\n    radius = (patch - 1) / 2\n\n    filtered_best_output = torch.zeros(np.shape(input_cpu)).cuda()\n    affine_model =    torch.zeros((h * w, 12)).cuda()\n    filtered_affine_model =torch.zeros((h * w, 12)).cuda()\n\n    input_ = torch.from_numpy(input_cpu).cuda()\n    output_ = torch.from_numpy(output_cpu).cuda()\n    _best_local_affine_kernel(\n        grid=(int((h * w) / 256 + 1), 1),\n        block=(256, 1, 1),\n        args=[output_.data_ptr(), input_.data_ptr(), affine_model.data_ptr(),\n             np.int32(h), np.int32(w), np.float32(epsilon), np.int32(radius)], stream=s\n     )\n\n    _bilateral_smooth_kernel(\n        grid=(int((h * w) / 256 + 1), 1),\n        block=(256, 1, 1),\n        args=[affine_model.data_ptr(), filtered_affine_model.data_ptr(), input_.data_ptr(), np.int32(h), np.int32(w), np.int32(f_r), np.float32(sigma1), np.float32(sigma2)], stream=s\n    )\n\n    _reconstruction_best_kernel(\n        grid=(int((h * w) / 256 + 1), 1),\n        block=(256, 1, 1),\n        args=[input_.data_ptr(), filtered_affine_model.data_ptr(), filtered_best_output.data_ptr(),\n        np.int32(h), np.int32(w)], stream=s\n    )\n    numpy_filtered_best_output = filtered_best_output.cpu().numpy()\n    return numpy_filtered_best_output\n\n\ndef smooth_filter(initImg, contentImg, f_radius=15,f_edge=1e-1):\n    '''\n    :param initImg: intermediate output. Either image path or PIL Image\n    :param contentImg: content image output. Either path or PIL Image\n    :return: stylized output image. PIL Image\n    '''\n    if type(initImg) == str:\n        initImg = Image.open(initImg).convert(\"RGB\")\n    best_image_bgr = np.array(initImg, dtype=np.float32)\n    bW, bH, bC = best_image_bgr.shape\n    best_image_bgr = best_image_bgr[:, :, ::-1]\n    best_image_bgr = best_image_bgr.transpose((2, 0, 1))\n\n    if type(contentImg) == str:\n        contentImg = Image.open(contentImg).convert(\"RGB\")\n    content_input = contentImg.resize((bH,bW))\n    content_input = np.array(content_input, dtype=np.float32)\n    content_input = content_input[:, :, ::-1]\n    content_input = content_input.transpose((2, 0, 1))\n    input_ = np.ascontiguousarray(content_input, dtype=np.float32) / 255.\n    _, H, W = np.shape(input_)\n    output_ = np.ascontiguousarray(best_image_bgr, dtype=np.float32) / 255.\n    best_ = smooth_local_affine(output_, input_, 1e-7, 3, H, W, f_radius, f_edge)\n    best_ = best_.transpose(1, 2, 0)\n    result = Image.fromarray(np.uint8(np.clip(best_ * 255., 0, 255.)))\n    return result\n"
  }
]