mirror of
https://github.com/Deepshift/DeepCreamPy.git
synced 2025-02-13 15:40:03 +00:00
Purge the old files
This commit is contained in:
parent
be82bde1e1
commit
6bd08ddfa6
@ -1,15 +0,0 @@
|
||||
FROM tensorflow/tensorflow:latest-py3
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y python3 python3-pip python3-tk python3-numpy libsm6 libxext6 libxrender-dev \
|
||||
&& apt-get clean
|
||||
RUN apt-get install -y vim
|
||||
|
||||
WORKDIR /app
|
||||
COPY . /app
|
||||
|
||||
RUN pip --no-cache-dir install --upgrade pip setuptools
|
||||
RUN pip --no-cache-dir install wheel
|
||||
RUN pip --no-cache-dir install -r requirements.txt
|
||||
|
||||
CMD ["python3", "decensor.py"]
|
120
LICENSE
120
LICENSE
@ -1,120 +0,0 @@
|
||||
|
||||
|
||||
Creative 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.
|
||||
|
||||
Using Creative Commons Public Licenses
|
||||
|
||||
Creative 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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
|
||||
|
||||
By 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.
|
||||
|
||||
Section 1 – Definitions.
|
||||
|
||||
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.
|
||||
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.
|
||||
BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
||||
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.
|
||||
Licensor means the individual(s) or entity(ies) granting rights under this Public License.
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
||||
|
||||
Section 2 – Scope.
|
||||
|
||||
License grant.
|
||||
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:
|
||||
reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
||||
produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
|
||||
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.
|
||||
Term. The term of this Public License is specified in Section 6(a).
|
||||
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.
|
||||
Downstream recipients.
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
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).
|
||||
|
||||
Other rights.
|
||||
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.
|
||||
Patent and trademark rights are not licensed under this Public License.
|
||||
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.
|
||||
|
||||
Section 3 – License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
||||
|
||||
Attribution.
|
||||
|
||||
If You Share the Licensed Material (including in modified form), You must:
|
||||
retain the following if it is supplied by the Licensor with the Licensed Material:
|
||||
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);
|
||||
a copyright notice;
|
||||
a notice that refers to this Public License;
|
||||
a notice that refers to the disclaimer of warranties;
|
||||
a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
||||
indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
||||
indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
||||
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.
|
||||
If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
||||
ShareAlike.
|
||||
|
||||
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
|
||||
Section 4 – Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
||||
|
||||
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;
|
||||
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
|
||||
You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
||||
|
||||
For 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.
|
||||
|
||||
Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Section 6 – Term and Termination.
|
||||
|
||||
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.
|
||||
|
||||
Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
||||
automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
||||
upon express reinstatement by the Licensor.
|
||||
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.
|
||||
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.
|
||||
Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
||||
|
||||
Section 7 – Other Terms and Conditions.
|
||||
|
||||
The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
||||
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.
|
||||
|
||||
Section 8 – Interpretation.
|
||||
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
|
||||
Creative 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.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. 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, 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.
|
||||
|
||||
Creative Commons may be contacted at creativecommons.org.
|
141
README.md
141
README.md
@ -1,141 +0,0 @@
|
||||
# DeepMindBreak
|
||||
*Decensoring Hentai with Deep Neural Networks*
|
||||
|
||||
This project applies an implementation of [Globally and Locally Consistent Image Completion](http://hi.cs.waseda.ac.jp/%7Eiizuka/projects/completion/data/completion_sig2017.pdf) to the problem of hentai decensorship. Using a deep fully convolutional neural network, DeepMindBreak can replace censored artwork in hentai with plausible reconstructions. The user needs to only specify the censored regions.
|
||||
|
||||
# **DeepMindBreak V2 (temporary name) will be released in 2018! Many improvements with a UI, higher resolution, and better looking decensors! Stay tuned!**
|
||||
|
||||
**Consider waiting for V2 since V1 looks amateurish and terrible in comparison.**
|
||||
|
||||
![Censored, decensored](/readme_images/collage.png)
|
||||
|
||||
# Limitations
|
||||
|
||||
This project is LIMITED in capability. It is a proof of concept of ongoing research.
|
||||
|
||||
The decensorship is intended to ONLY work on color hentai images that have minor bar censorship of the penis or vagina.
|
||||
|
||||
It does NOT work with:
|
||||
- Black and white images
|
||||
- Monochrome images
|
||||
- Hentai containing screentones (e.g. printed hentai)
|
||||
- Real life porn
|
||||
- Mosaic censorship
|
||||
- Censorship of nipples
|
||||
- Censorship of anus
|
||||
- Animated gifs/videos
|
||||
|
||||
In particular, if a vagina or penis is completely censored out, inpainting will be ineffective.
|
||||
|
||||
# Dependencies
|
||||
|
||||
- Python 2/3
|
||||
- TensorFlow 1.5
|
||||
- Pillow
|
||||
- OpenCV
|
||||
- tqdm
|
||||
- scipy
|
||||
- pyamg
|
||||
- matplotlib (only for running test.py)
|
||||
|
||||
No GPU required! Tested on Ubuntu 16.04 and Windows. (Tensorflow on Windows is compatible with Python 3 and not Python 2.)
|
||||
|
||||
Poisson blending is disabled by default since it has little effect on output quality.
|
||||
|
||||
Pillow, tqdm, scipy, pyamg, and matplotlib can all be installed using pip.
|
||||
|
||||
# Model
|
||||
Pretrained models can be downloaded from https://drive.google.com/open?id=1KveQ0aaye3tdlB7JR9bFEqMk1Lqp8GyC.
|
||||
|
||||
Unzip the contents into the /models/ folder.
|
||||
|
||||
# Usage
|
||||
|
||||
## I. Decensoring hentai
|
||||
|
||||
For each image you want to decensor, using image editing software like Photoshop or GIMP to paint the areas you want to decensor the color (0,255,0), which is a very bright green color.
|
||||
|
||||
Save these images in the PNG format to the "decensor_input" directory. Decensor the images by running
|
||||
|
||||
```
|
||||
$ python decensor.py
|
||||
```
|
||||
|
||||
Decensored images will be saved to the "decensor_output" directory.
|
||||
|
||||
## II. Train the pretrained model on custom dataset
|
||||
|
||||
You must have a GPU for training since training on a CPU will take weeks.
|
||||
|
||||
Your custom dataset should be 128 x 128 images of uncensored vaginas and penises cropped from hentai. The more images, the better: I used 70,000 images for training. Censoring these images yourself is unnecessary.
|
||||
|
||||
Put your custom dataset for training in the "training_data/images" directory and convert images to npy format.
|
||||
|
||||
```
|
||||
$ cd training_data
|
||||
$ python to_npy.py
|
||||
```
|
||||
|
||||
To train, run
|
||||
|
||||
```
|
||||
$ python train.py
|
||||
```
|
||||
|
||||
If desired, you can train the pretrained model on your custom dataset by running
|
||||
```
|
||||
$ python train.py --continue_training=True
|
||||
```
|
||||
|
||||
Training can be done separately for mosaics with train_mosaic.py, but decensor.py is not yet compatible with mosaic decensorship models.
|
||||
|
||||
# To do
|
||||
- ~~Add Python 3 compatibility~~
|
||||
- ~~Add random rotations in cropping rectangles~~
|
||||
- ~~Retrain for arbitrary shape censors~~
|
||||
- Add a user interface
|
||||
- Incorporate GAN loss into training
|
||||
- Update the model to the new version
|
||||
|
||||
Contributions are welcome! Special thanks to StartleStars for contributing code for mosaic decensorship and SoftArmpit for greatly simplifying decensoring!
|
||||
|
||||
# License
|
||||
|
||||
This code is for personal use and research use only.
|
||||
|
||||
Example image by dannychoo under [CC BY-NC-SA 2.0 License](https://creativecommons.org/licenses/by-nc-sa/2.0/). The example image is modified from the original, which can be found [here](https://www.flickr.com/photos/dannychoo/16081096643/in/photostream/).
|
||||
|
||||
Model is licensed under CC BY-NC-SA 4.0 License.
|
||||
|
||||
Code is licensed under CC BY-NC-SA 4.0 License and is modified from tadax's project [Globally and Locally Consistent Image Completion with TensorFlow ](https://github.com/tadax/glcic) and shinseung428's project [https://github.com/shinseung428/GlobalLocalImageCompletion_TF], which are implementations of the paper [Globally and Locally Consistent Image Completion](http://hi.cs.waseda.ac.jp/%7Eiizuka/projects/completion/data/completion_sig2017.pdf). It also has a modified version of parosky's project [poissonblending](https://github.com/parosky/poissonblending).
|
||||
|
||||
```
|
||||
# Copyright (c) 2018, deeppomf. All rights reserved.
|
||||
#
|
||||
# This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike
|
||||
# 4.0 International License. To view a copy of this license, visit
|
||||
# https://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to
|
||||
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
|
||||
```
|
||||
|
||||
```
|
||||
# Copyright (c) 2018 tadax, Seung Shin, parosky
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in all
|
||||
# copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
```
|
62
config.py
62
config.py
@ -1,62 +0,0 @@
|
||||
import argparse
|
||||
|
||||
def str2bool(v):
|
||||
if v.lower() in ('yes', 'true', 't', 'y', '1', True):
|
||||
return True
|
||||
elif v.lower() in ('no', 'false', 'f', 'n', '0', False):
|
||||
return False
|
||||
else:
|
||||
raise argparse.ArgumentTypeError('Boolean value expected.')
|
||||
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser(description='')
|
||||
|
||||
#Image settings
|
||||
parser.add_argument('--input_size', dest='input_size', default=128, help='input image size')
|
||||
parser.add_argument('--local_input_size', dest='local_input_size', default=64, help='local input image size')
|
||||
parser.add_argument('--input_channel_size', dest='input_channel_size', default=3, help='input image channel')
|
||||
parser.add_argument('--min_mask_size', dest='min_mask_size', default=24, help='minimum mask size')
|
||||
parser.add_argument('--max_mask_size', dest='max_mask_size', default=48, help='maximum mask size')
|
||||
parser.add_argument('--rotate_chance', dest='rotate_chance', default=0.7, help='chance the mask will be randomly rotated')
|
||||
parser.add_argument('--train_mosaic', dest ='train_mosaic', default=False, help='train neural network to decensor mosaics')
|
||||
|
||||
# parser.add_argument('--input_dim', dest='input_dim', default=100, help='input z size')
|
||||
|
||||
# #Training settings
|
||||
parser.add_argument('--continue_training', dest='continue_training', default=False, type=str2bool, help='flag to continue training')
|
||||
parser.add_argument('--training_samples_path', dest='training_samples_path', default='./training_samples/', help='samples images generated during training path')
|
||||
parser.add_argument('--batch_size', dest='batch_size', default=16, help='batch size')
|
||||
|
||||
# parser.add_argument('--data', dest='data', default='../ambientGAN_TF/data', help='cats image train path')
|
||||
|
||||
# parser.add_argument('--train_step', dest='train_step', default=400, help='total number of train_step')
|
||||
# parser.add_argument('--Tc', dest='Tc', default=100, help='Tc to train Completion Network')
|
||||
# parser.add_argument('--Td', dest='Td', default=1, help='Td to train Discriminator Network')
|
||||
|
||||
|
||||
parser.add_argument('--learning_rate', dest='learning_rate', default=0.001, help='learning rate of the optimizer')
|
||||
# parser.add_argument('--momentum', dest='momentum', default=0.5, help='momentum of the optimizer')
|
||||
|
||||
# #I set alpha to 1 to give more weights to the discriminator loss
|
||||
# parser.add_argument('--alpha', dest='alpha', default=1.0, help='alpha')
|
||||
|
||||
# parser.add_argument('--margin', dest='margin', default=5, help='margin')
|
||||
|
||||
# #Test image
|
||||
# parser.add_argument('--img_path', dest='img_path', default='', help='test image path')
|
||||
|
||||
# #Extra folders settings
|
||||
# parser.add_argument('--checkpoints_path', dest='checkpoints_path', default='./checkpoints/', help='saved model checkpoint path')
|
||||
# parser.add_argument('--graph_path', dest='graph_path', default='./graphs/', help='tensorboard graph')
|
||||
# parser.add_argument('--images_path', dest='images_path', default='./images/', help='result images path')
|
||||
parser.add_argument('--testing_output_path', dest='testing_output_path', default='./testing_output/', help='output images generated from running test.py path')
|
||||
parser.add_argument('--decensor_input_path', dest='decensor_input_path', default='./decensor_input/', help='input images to be decensored by decensor.py path')
|
||||
parser.add_argument('--decensor_output_path', dest='decensor_output_path', default='./decensor_output/', help='output images generated from running decensor.py path')
|
||||
|
||||
# Decensor settings
|
||||
parser.add_argument('--mask_color_red', dest='mask_color_red', default=0, help='red channel of mask color in decensoring')
|
||||
parser.add_argument('--mask_color_green', dest='mask_color_green', default=255, help='green channel of mask color in decensoring')
|
||||
parser.add_argument('--mask_color_blue', dest='mask_color_blue', default=0, help='blue channel of mask color in decensoring')
|
||||
|
||||
args = parser.parse_args()
|
127
decensor.py
127
decensor.py
@ -1,127 +0,0 @@
|
||||
import numpy as np
|
||||
import tensorflow as tf
|
||||
from PIL import Image
|
||||
import tqdm
|
||||
import os
|
||||
import matplotlib.pyplot as plt
|
||||
import stat
|
||||
import sys
|
||||
sys.path.append('..')
|
||||
|
||||
from model import Model
|
||||
from poisson_blend import blend
|
||||
from config import *
|
||||
import shape_detect as sd
|
||||
|
||||
#TODO: allow variable batch sizes when decensoring. changing BATCH_SIZE will likely result in crashing
|
||||
BATCH_SIZE = 1
|
||||
|
||||
mask_color = [args.mask_color_red, args.mask_color_green, args.mask_color_blue]
|
||||
poisson_blending_enabled = False
|
||||
|
||||
def is_file(file):
|
||||
try:
|
||||
return not stat.S_ISDIR(os.stat(file).st_mode)
|
||||
except:
|
||||
return False
|
||||
|
||||
def get_files(dir):
|
||||
all_files = os.listdir(dir)
|
||||
filtered_files = list(filter(lambda file: is_file(os.path.join(dir, file)), all_files))
|
||||
return filtered_files
|
||||
|
||||
def find_censor_boxes(image_path):
|
||||
(image, boxes) = sd.process_image_path(image_path, tuple(mask_color))
|
||||
|
||||
i = 0
|
||||
for (box_image, cx, cy) in boxes:
|
||||
pil_box_image = sd.cv_to_pillow(box_image)
|
||||
boxes[i] = (pil_box_image, cx, cy)
|
||||
i += 1
|
||||
|
||||
# boxes = map(lambda box: (sd.cv_to_pillow(box[0]), box[1], box[2]), boxes)
|
||||
return (image, boxes)
|
||||
|
||||
def decensor(args):
|
||||
subdir = args.decensor_input_path
|
||||
files = sorted(get_files(subdir))
|
||||
|
||||
for file in files:
|
||||
file_path = os.path.join(subdir, file)
|
||||
if os.path.isfile(file_path) and os.path.splitext(file_path)[1] == ".png":
|
||||
print(file_path)
|
||||
(image, boxes) = find_censor_boxes(file_path)
|
||||
decensored_boxes = decensor_boxes(args, boxes)
|
||||
for (box_pillow_image, cx, cy) in decensored_boxes:
|
||||
box_image = sd.pillow_to_cv(box_pillow_image)
|
||||
image = sd.insert_box((box_image, cx, cy), image)
|
||||
|
||||
sd.write_to_file(image, os.path.join(args.decensor_output_path, file))
|
||||
|
||||
def decensor_boxes(args, boxes):
|
||||
x = tf.placeholder(tf.float32, [BATCH_SIZE, args.input_size, args.input_size, args.input_channel_size])
|
||||
mask = tf.placeholder(tf.float32, [BATCH_SIZE, args.input_size, args.input_size, 1])
|
||||
local_x = tf.placeholder(tf.float32, [BATCH_SIZE, args.local_input_size, args.local_input_size, args.input_channel_size])
|
||||
global_completion = tf.placeholder(tf.float32, [BATCH_SIZE, args.input_size, args.input_size, args.input_channel_size])
|
||||
local_completion = tf.placeholder(tf.float32, [BATCH_SIZE, args.local_input_size, args.local_input_size, args.input_channel_size])
|
||||
is_training = tf.placeholder(tf.bool, [])
|
||||
|
||||
model = Model(x, mask, local_x, global_completion, local_completion, is_training, batch_size=BATCH_SIZE)
|
||||
sess = tf.Session()
|
||||
init_op = tf.global_variables_initializer()
|
||||
sess.run(init_op)
|
||||
|
||||
saver = tf.train.Saver()
|
||||
saver.restore(sess, './models/latest')
|
||||
|
||||
mask_decensor = []
|
||||
x_decensor = []
|
||||
|
||||
for (box_image, cx, cy) in boxes:
|
||||
image = np.array(box_image)
|
||||
image = np.array(image / 127.5 - 1)
|
||||
x_decensor.append(image)
|
||||
|
||||
x_decensor = np.array(x_decensor)
|
||||
print(x_decensor.shape)
|
||||
step_num = int(len(x_decensor) / BATCH_SIZE)
|
||||
|
||||
results = []
|
||||
|
||||
cnt = 0
|
||||
for i in tqdm.tqdm(range(step_num)):
|
||||
x_batch = x_decensor[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]
|
||||
mask_batch = get_mask(x_batch)
|
||||
completion = sess.run(model.completion, feed_dict={x: x_batch, mask: mask_batch, is_training: False})
|
||||
for i in range(BATCH_SIZE):
|
||||
img = completion[i]
|
||||
img = np.array((img + 1) * 127.5, dtype=np.uint8)
|
||||
original = x_batch[i]
|
||||
original = np.array((original + 1) * 127.5, dtype=np.uint8)
|
||||
if (poisson_blending_enabled):
|
||||
img = blend(original, img, mask_batch[0,:,:,0])
|
||||
output = Image.fromarray(img.astype('uint8'), 'RGB')
|
||||
results.append((output, boxes[cnt][1], boxes[cnt][2]))
|
||||
cnt += 1
|
||||
|
||||
tf.reset_default_graph()
|
||||
return results
|
||||
|
||||
def get_mask(x_batch):
|
||||
points = []
|
||||
mask = []
|
||||
for i in range(BATCH_SIZE):
|
||||
raw = x_batch[i]
|
||||
raw = np.array((raw + 1) * 127.5, dtype=np.uint8)
|
||||
m = np.zeros((args.input_size, args.input_size, 1), dtype=np.uint8)
|
||||
for x in range(args.input_size):
|
||||
for y in range(args.input_size):
|
||||
if np.array_equal(raw[x][y], mask_color):
|
||||
m[x, y] = 1
|
||||
mask.append(m)
|
||||
return np.array(mask)
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not os.path.exists(args.decensor_output_path):
|
||||
os.makedirs(args.decensor_output_path)
|
||||
decensor(args)
|
95
layer.py
95
layer.py
@ -1,95 +0,0 @@
|
||||
import tensorflow as tf
|
||||
|
||||
def conv_layer(x, filter_shape, stride):
|
||||
filters = tf.get_variable(
|
||||
name='weight',
|
||||
shape=filter_shape,
|
||||
dtype=tf.float32,
|
||||
initializer=tf.contrib.layers.xavier_initializer(),
|
||||
trainable=True)
|
||||
return tf.nn.conv2d(x, filters, [1, stride, stride, 1], padding='SAME')
|
||||
|
||||
|
||||
def dilated_conv_layer(x, filter_shape, dilation):
|
||||
filters = tf.get_variable(
|
||||
name='weight',
|
||||
shape=filter_shape,
|
||||
dtype=tf.float32,
|
||||
initializer=tf.contrib.layers.xavier_initializer(),
|
||||
trainable=True)
|
||||
return tf.nn.atrous_conv2d(x, filters, dilation, padding='SAME')
|
||||
|
||||
|
||||
def deconv_layer(x, filter_shape, output_shape, stride):
|
||||
filters = tf.get_variable(
|
||||
name='weight',
|
||||
shape=filter_shape,
|
||||
dtype=tf.float32,
|
||||
initializer=tf.contrib.layers.xavier_initializer(),
|
||||
trainable=True)
|
||||
return tf.nn.conv2d_transpose(x, filters, output_shape, [1, stride, stride, 1])
|
||||
|
||||
|
||||
def batch_normalize(x, is_training, decay=0.99, epsilon=0.001):
|
||||
def bn_train():
|
||||
batch_mean, batch_var = tf.nn.moments(x, axes=[0, 1, 2])
|
||||
train_mean = tf.assign(pop_mean, pop_mean * decay + batch_mean * (1 - decay))
|
||||
train_var = tf.assign(pop_var, pop_var * decay + batch_var * (1 - decay))
|
||||
with tf.control_dependencies([train_mean, train_var]):
|
||||
return tf.nn.batch_normalization(x, batch_mean, batch_var, beta, scale, epsilon)
|
||||
|
||||
def bn_inference():
|
||||
return tf.nn.batch_normalization(x, pop_mean, pop_var, beta, scale, epsilon)
|
||||
|
||||
dim = x.get_shape().as_list()[-1]
|
||||
beta = tf.get_variable(
|
||||
name='beta',
|
||||
shape=[dim],
|
||||
dtype=tf.float32,
|
||||
initializer=tf.truncated_normal_initializer(stddev=0.0),
|
||||
trainable=True)
|
||||
scale = tf.get_variable(
|
||||
name='scale',
|
||||
shape=[dim],
|
||||
dtype=tf.float32,
|
||||
initializer=tf.truncated_normal_initializer(stddev=0.1),
|
||||
trainable=True)
|
||||
pop_mean = tf.get_variable(
|
||||
name='pop_mean',
|
||||
shape=[dim],
|
||||
dtype=tf.float32,
|
||||
initializer=tf.constant_initializer(0.0),
|
||||
trainable=False)
|
||||
pop_var = tf.get_variable(
|
||||
name='pop_var',
|
||||
shape=[dim],
|
||||
dtype=tf.float32,
|
||||
initializer=tf.constant_initializer(1.0),
|
||||
trainable=False)
|
||||
|
||||
return tf.cond(is_training, bn_train, bn_inference)
|
||||
|
||||
|
||||
def flatten_layer(x):
|
||||
input_shape = x.get_shape().as_list()
|
||||
dim = input_shape[1] * input_shape[2] * input_shape[3]
|
||||
transposed = tf.transpose(x, (0, 3, 1, 2))
|
||||
return tf.reshape(transposed, [-1, dim])
|
||||
|
||||
|
||||
def full_connection_layer(x, out_dim):
|
||||
in_dim = x.get_shape().as_list()[-1]
|
||||
W = tf.get_variable(
|
||||
name='weight',
|
||||
shape=[in_dim, out_dim],
|
||||
dtype=tf.float32,
|
||||
initializer=tf.truncated_normal_initializer(stddev=0.1),
|
||||
trainable=True)
|
||||
b = tf.get_variable(
|
||||
name='bias',
|
||||
shape=[out_dim],
|
||||
dtype=tf.float32,
|
||||
initializer=tf.constant_initializer(0.0),
|
||||
trainable=True)
|
||||
return tf.add(tf.matmul(x, W), b)
|
||||
|
14
load.py
14
load.py
@ -1,14 +0,0 @@
|
||||
import os
|
||||
import numpy as np
|
||||
|
||||
def load(dir_='./training_data/npy'):
|
||||
x_train = np.load(os.path.join(dir_, 'x_train.npy'))
|
||||
x_test = np.load(os.path.join(dir_, 'x_test.npy'))
|
||||
return x_train, x_test
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
x_train, x_test = load()
|
||||
print(x_train.shape)
|
||||
print(x_test.shape)
|
||||
|
162
model.py
162
model.py
@ -1,162 +0,0 @@
|
||||
from layer import *
|
||||
|
||||
class Model:
|
||||
def __init__(self, x, mask, local_x, global_completion, local_completion, is_training, batch_size):
|
||||
self.batch_size = batch_size
|
||||
self.imitation = self.generator(x * (1 - mask), is_training)
|
||||
self.completion = self.imitation * mask + x * (1 - mask)
|
||||
self.real = self.discriminator(x, local_x, reuse=False)
|
||||
self.fake = self.discriminator(global_completion, local_completion, reuse=True)
|
||||
self.g_loss = self.calc_g_loss(x, self.completion)
|
||||
self.d_loss = self.calc_d_loss(self.real, self.fake)
|
||||
self.g_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='generator')
|
||||
self.d_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='discriminator')
|
||||
|
||||
|
||||
def generator(self, x, is_training):
|
||||
with tf.variable_scope('generator'):
|
||||
with tf.variable_scope('conv1'):
|
||||
x = conv_layer(x, [5, 5, 3, 64], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv2'):
|
||||
x = conv_layer(x, [3, 3, 64, 128], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv3'):
|
||||
x = conv_layer(x, [3, 3, 128, 128], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv4'):
|
||||
x = conv_layer(x, [3, 3, 128, 256], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv5'):
|
||||
x = conv_layer(x, [3, 3, 256, 256], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv6'):
|
||||
x = conv_layer(x, [3, 3, 256, 256], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('dilated1'):
|
||||
x = dilated_conv_layer(x, [3, 3, 256, 256], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('dilated2'):
|
||||
x = dilated_conv_layer(x, [3, 3, 256, 256], 4)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('dilated3'):
|
||||
x = dilated_conv_layer(x, [3, 3, 256, 256], 8)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('dilated4'):
|
||||
x = dilated_conv_layer(x, [3, 3, 256, 256], 16)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv7'):
|
||||
x = conv_layer(x, [3, 3, 256, 256], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv8'):
|
||||
x = conv_layer(x, [3, 3, 256, 256], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('deconv1'):
|
||||
x = deconv_layer(x, [4, 4, 128, 256], [self.batch_size, 64, 64, 128], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv9'):
|
||||
x = conv_layer(x, [3, 3, 128, 128], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('deconv2'):
|
||||
x = deconv_layer(x, [4, 4, 64, 128], [self.batch_size, 128, 128, 64], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv10'):
|
||||
x = conv_layer(x, [3, 3, 64, 32], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv11'):
|
||||
x = conv_layer(x, [3, 3, 32, 3], 1)
|
||||
x = tf.nn.tanh(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
def discriminator(self, global_x, local_x, reuse):
|
||||
def global_discriminator(x):
|
||||
is_training = tf.constant(True)
|
||||
with tf.variable_scope('global'):
|
||||
with tf.variable_scope('conv1'):
|
||||
x = conv_layer(x, [5, 5, 3, 64], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv2'):
|
||||
x = conv_layer(x, [5, 5, 64, 128], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv3'):
|
||||
x = conv_layer(x, [5, 5, 128, 256], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv4'):
|
||||
x = conv_layer(x, [5, 5, 256, 512], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv5'):
|
||||
x = conv_layer(x, [5, 5, 512, 512], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('fc'):
|
||||
x = flatten_layer(x)
|
||||
x = full_connection_layer(x, 1024)
|
||||
return x
|
||||
|
||||
def local_discriminator(x):
|
||||
is_training = tf.constant(True)
|
||||
with tf.variable_scope('local'):
|
||||
with tf.variable_scope('conv1'):
|
||||
x = conv_layer(x, [5, 5, 3, 64], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv2'):
|
||||
x = conv_layer(x, [5, 5, 64, 128], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv3'):
|
||||
x = conv_layer(x, [5, 5, 128, 256], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv4'):
|
||||
x = conv_layer(x, [5, 5, 256, 512], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('fc'):
|
||||
x = flatten_layer(x)
|
||||
x = full_connection_layer(x, 1024)
|
||||
return x
|
||||
|
||||
with tf.variable_scope('discriminator', reuse=reuse):
|
||||
global_output = global_discriminator(global_x)
|
||||
local_output = local_discriminator(local_x)
|
||||
with tf.variable_scope('concatenation'):
|
||||
output = tf.concat((global_output, local_output), 1)
|
||||
output = full_connection_layer(output, 1)
|
||||
|
||||
return output
|
||||
|
||||
|
||||
def calc_g_loss(self, x, completion):
|
||||
loss = tf.nn.l2_loss(x - completion)
|
||||
return tf.reduce_mean(loss)
|
||||
|
||||
|
||||
def calc_d_loss(self, real, fake):
|
||||
alpha = 4e-4
|
||||
d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=real, labels=tf.ones_like(real)))
|
||||
d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=fake, labels=tf.zeros_like(fake)))
|
||||
return tf.add(d_loss_real, d_loss_fake) * alpha
|
||||
|
163
model_mosaic.py
163
model_mosaic.py
@ -1,163 +0,0 @@
|
||||
from layer import *
|
||||
|
||||
class Model:
|
||||
def __init__(self, x, mosaic, mask, local_x, global_completion, local_completion, is_training, batch_size):
|
||||
self.batch_size = batch_size
|
||||
self.merged = x * (1 - mask) + mosaic * (mask)
|
||||
self.imitation = self.generator(self.merged, is_training)
|
||||
self.completion = self.imitation * mask + x * (1 - mask)
|
||||
self.real = self.discriminator(x, local_x, reuse=False)
|
||||
self.fake = self.discriminator(global_completion, local_completion, reuse=True)
|
||||
self.g_loss = self.calc_g_loss(x, self.completion)
|
||||
self.d_loss = self.calc_d_loss(self.real, self.fake)
|
||||
self.g_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='generator')
|
||||
self.d_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='discriminator')
|
||||
|
||||
|
||||
def generator(self, x, is_training):
|
||||
with tf.variable_scope('generator'):
|
||||
with tf.variable_scope('conv1'):
|
||||
x = conv_layer(x, [5, 5, 3, 64], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv2'):
|
||||
x = conv_layer(x, [3, 3, 64, 128], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv3'):
|
||||
x = conv_layer(x, [3, 3, 128, 128], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv4'):
|
||||
x = conv_layer(x, [3, 3, 128, 256], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv5'):
|
||||
x = conv_layer(x, [3, 3, 256, 256], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv6'):
|
||||
x = conv_layer(x, [3, 3, 256, 256], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('dilated1'):
|
||||
x = dilated_conv_layer(x, [3, 3, 256, 256], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('dilated2'):
|
||||
x = dilated_conv_layer(x, [3, 3, 256, 256], 4)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('dilated3'):
|
||||
x = dilated_conv_layer(x, [3, 3, 256, 256], 8)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('dilated4'):
|
||||
x = dilated_conv_layer(x, [3, 3, 256, 256], 16)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv7'):
|
||||
x = conv_layer(x, [3, 3, 256, 256], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv8'):
|
||||
x = conv_layer(x, [3, 3, 256, 256], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('deconv1'):
|
||||
x = deconv_layer(x, [4, 4, 128, 256], [self.batch_size, 64, 64, 128], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv9'):
|
||||
x = conv_layer(x, [3, 3, 128, 128], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('deconv2'):
|
||||
x = deconv_layer(x, [4, 4, 64, 128], [self.batch_size, 128, 128, 64], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv10'):
|
||||
x = conv_layer(x, [3, 3, 64, 32], 1)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv11'):
|
||||
x = conv_layer(x, [3, 3, 32, 3], 1)
|
||||
x = tf.nn.tanh(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
def discriminator(self, global_x, local_x, reuse):
|
||||
def global_discriminator(x):
|
||||
is_training = tf.constant(True)
|
||||
with tf.variable_scope('global'):
|
||||
with tf.variable_scope('conv1'):
|
||||
x = conv_layer(x, [5, 5, 3, 64], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv2'):
|
||||
x = conv_layer(x, [5, 5, 64, 128], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv3'):
|
||||
x = conv_layer(x, [5, 5, 128, 256], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv4'):
|
||||
x = conv_layer(x, [5, 5, 256, 512], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv5'):
|
||||
x = conv_layer(x, [5, 5, 512, 512], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('fc'):
|
||||
x = flatten_layer(x)
|
||||
x = full_connection_layer(x, 1024)
|
||||
return x
|
||||
|
||||
def local_discriminator(x):
|
||||
is_training = tf.constant(True)
|
||||
with tf.variable_scope('local'):
|
||||
with tf.variable_scope('conv1'):
|
||||
x = conv_layer(x, [5, 5, 3, 64], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv2'):
|
||||
x = conv_layer(x, [5, 5, 64, 128], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv3'):
|
||||
x = conv_layer(x, [5, 5, 128, 256], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('conv4'):
|
||||
x = conv_layer(x, [5, 5, 256, 512], 2)
|
||||
x = batch_normalize(x, is_training)
|
||||
x = tf.nn.relu(x)
|
||||
with tf.variable_scope('fc'):
|
||||
x = flatten_layer(x)
|
||||
x = full_connection_layer(x, 1024)
|
||||
return x
|
||||
|
||||
with tf.variable_scope('discriminator', reuse=reuse):
|
||||
global_output = global_discriminator(global_x)
|
||||
local_output = local_discriminator(local_x)
|
||||
with tf.variable_scope('concatenation'):
|
||||
output = tf.concat((global_output, local_output), 1)
|
||||
output = full_connection_layer(output, 1)
|
||||
|
||||
return output
|
||||
|
||||
|
||||
def calc_g_loss(self, x, completion):
|
||||
loss = tf.nn.l2_loss(x - completion)
|
||||
return tf.reduce_mean(loss)
|
||||
|
||||
|
||||
def calc_d_loss(self, real, fake):
|
||||
alpha = 4e-4
|
||||
d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=real, labels=tf.ones_like(real)))
|
||||
d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=fake, labels=tf.zeros_like(fake)))
|
||||
return tf.add(d_loss_real, d_loss_fake) * alpha
|
||||
|
108
poisson_blend.py
108
poisson_blend.py
@ -1,108 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import numpy as np
|
||||
import scipy.sparse
|
||||
import PIL.Image
|
||||
import pyamg
|
||||
import copy
|
||||
|
||||
# pre-process the mask array so that uint64 types from opencv.imread can be adapted
|
||||
def prepare_mask(mask):
|
||||
result = np.ndarray((mask.shape[0], mask.shape[1]), dtype=np.uint8)
|
||||
for i in range(mask.shape[0]):
|
||||
for j in range(mask.shape[1]):
|
||||
if mask[i][j] > 0:
|
||||
result[i][j] = 1
|
||||
else:
|
||||
result[i][j] = 0
|
||||
mask = result
|
||||
return mask
|
||||
|
||||
def blend(img_target, img_source, img_mask, offset=(0, 0)):
|
||||
# compute regions to be blended
|
||||
region_source = (
|
||||
max(-offset[0], 0),
|
||||
max(-offset[1], 0),
|
||||
min(img_target.shape[0]-offset[0], img_source.shape[0]),
|
||||
min(img_target.shape[1]-offset[1], img_source.shape[1]))
|
||||
region_target = (
|
||||
max(offset[0], 0),
|
||||
max(offset[1], 0),
|
||||
min(img_target.shape[0], img_source.shape[0]+offset[0]),
|
||||
min(img_target.shape[1], img_source.shape[1]+offset[1]))
|
||||
region_size = (region_source[2]-region_source[0], region_source[3]-region_source[1])
|
||||
|
||||
# clip and normalize mask image
|
||||
img_mask = img_mask[region_source[0]:region_source[2], region_source[1]:region_source[3]]
|
||||
#img_mask_copy = copy.deepcopy(img_mask)
|
||||
# prepare_mask doesn't change anything
|
||||
# img_mask = prepare_mask(img_mask)
|
||||
# if np.array_equal(img_mask, img_mask_copy):
|
||||
# print "eq"
|
||||
img_mask[img_mask==0] = False
|
||||
img_mask[img_mask!=False] = True
|
||||
|
||||
# create coefficient matrix
|
||||
A = scipy.sparse.identity(np.prod(region_size), format='lil')
|
||||
for y in range(region_size[0]):
|
||||
for x in range(region_size[1]):
|
||||
if img_mask[y,x]:
|
||||
index = x+y*region_size[1]
|
||||
A[index, index] = 4
|
||||
if index+1 < np.prod(region_size):
|
||||
A[index, index+1] = -1
|
||||
if index-1 >= 0:
|
||||
A[index, index-1] = -1
|
||||
if index+region_size[1] < np.prod(region_size):
|
||||
A[index, index+region_size[1]] = -1
|
||||
if index-region_size[1] >= 0:
|
||||
A[index, index-region_size[1]] = -1
|
||||
A = A.tocsr()
|
||||
|
||||
# create poisson matrix for b
|
||||
P = pyamg.gallery.poisson(img_mask.shape)
|
||||
|
||||
# for each layer (ex. RGB)
|
||||
for num_layer in range(img_target.shape[2]):
|
||||
# get subimages
|
||||
t = img_target[region_target[0]:region_target[2],region_target[1]:region_target[3],num_layer]
|
||||
s = img_source[region_source[0]:region_source[2], region_source[1]:region_source[3],num_layer]
|
||||
t = t.flatten()
|
||||
s = s.flatten()
|
||||
|
||||
# create b
|
||||
b = P * s
|
||||
for y in range(region_size[0]):
|
||||
for x in range(region_size[1]):
|
||||
if not img_mask[y,x]:
|
||||
index = x+y*region_size[1]
|
||||
b[index] = t[index]
|
||||
|
||||
# solve Ax = b
|
||||
x = pyamg.solve(A,b,verb=False,tol=1e-10)
|
||||
|
||||
# assign x to target image
|
||||
x = np.reshape(x, region_size)
|
||||
x[x>255] = 255
|
||||
x[x<0] = 0
|
||||
x = np.array(x, img_target.dtype)
|
||||
img_target[region_target[0]:region_target[2],region_target[1]:region_target[3],num_layer] = x
|
||||
|
||||
return img_target
|
||||
|
||||
|
||||
def test():
|
||||
img_mask = np.asarray(PIL.Image.open('./testimages/test1_mask.png'))
|
||||
img_mask.flags.writeable = True
|
||||
img_source = np.asarray(PIL.Image.open('./testimages/test1_src.png'))
|
||||
img_source.flags.writeable = True
|
||||
img_target = np.asarray(PIL.Image.open('./testimages/test1_target.png'))
|
||||
img_target.flags.writeable = True
|
||||
img_ret = blend(img_target, img_source, img_mask, offset=(40,-30))
|
||||
img_ret = PIL.Image.fromarray(np.uint8(img_ret))
|
||||
img_ret.save('./testimages/test1_ret.png')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test()
|
Binary file not shown.
Before Width: | Height: | Size: 777 KiB |
@ -1,22 +0,0 @@
|
||||
from PIL import Image
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def format_results(images, dst):
|
||||
fig = plt.figure()
|
||||
for i, image in enumerate(images):
|
||||
text, img = image
|
||||
fig.add_subplot(1, 3, i + 1)
|
||||
plt.imshow(img)
|
||||
plt.tick_params(labelbottom='off')
|
||||
plt.tick_params(labelleft='off')
|
||||
plt.gca().get_xaxis().set_ticks_position('none')
|
||||
plt.gca().get_yaxis().set_ticks_position('none')
|
||||
plt.xlabel(text)
|
||||
plt.savefig(dst)
|
||||
plt.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
masked = Image.open("censored.png")
|
||||
img = Image.open("decensored.png")
|
||||
raw = Image.open("original.png")
|
||||
format_results([['Input', masked], ['Output', img], ['Ground Truth', raw]], "result.png")
|
Binary file not shown.
Before Width: | Height: | Size: 240 KiB |
@ -1,6 +0,0 @@
|
||||
Pillow
|
||||
tqdm
|
||||
scipy
|
||||
pyamg
|
||||
matplotlib
|
||||
opencv-python
|
131
shape_detect.py
131
shape_detect.py
@ -1,131 +0,0 @@
|
||||
"""Shape detection.
|
||||
|
||||
Detect rectangle shapes in images, cut out 128px
|
||||
surrounding shape and then pass it to the decensoring
|
||||
program and replace the censored tile with the
|
||||
decensored one.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
import argparse
|
||||
from PIL import Image
|
||||
import os
|
||||
|
||||
|
||||
isExec = __name__ == '__main__'
|
||||
|
||||
|
||||
box_size = 128
|
||||
def cv_to_pillow(image, i = 0):
|
||||
"""
|
||||
converted = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
||||
conv_array = np.array(converted)
|
||||
pil_image = Image.fromarray(conv_array)
|
||||
print(converted)
|
||||
print(conv_array)
|
||||
print(pil_image)
|
||||
return pil_image
|
||||
"""
|
||||
|
||||
# TODO(SoftArmpit): This is inefficient, convert directly instead.
|
||||
file_path = os.path.join('/tmp/', str(i) + '.png')
|
||||
write_to_file(image, file_path)
|
||||
pil_box_image = Image.open(file_path).convert('RGB')
|
||||
return pil_box_image
|
||||
|
||||
|
||||
def pillow_to_cv(image):
|
||||
return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
||||
|
||||
|
||||
def insert_box(box, image):
|
||||
(box_image, x, y) = box
|
||||
image[y:y+box_image.shape[0], x:x+box_image.shape[1]] = box_image
|
||||
return image
|
||||
|
||||
|
||||
def detect_shape(c):
|
||||
perim = cv2.arcLength(c, True)
|
||||
vertices = cv2.approxPolyDP(c, 0.04 * perim, True)
|
||||
|
||||
print('Vertices: ' + str(len(vertices)))
|
||||
return len(vertices) == 4
|
||||
|
||||
|
||||
def process_contour(image, c):
|
||||
M = cv2.moments(c)
|
||||
print(M)
|
||||
|
||||
if M['m00'] == 0:
|
||||
return None
|
||||
|
||||
cx = int(M['m10'] / M['m00'] - box_size / 2)
|
||||
cy = int(M['m01'] / M['m00'] - box_size / 2)
|
||||
# NOTE(SoftArmpit): Limit box to image boundaries
|
||||
cx = min(max(cx, 0), image.shape[1] - box_size)
|
||||
cy = min(max(cy, 0), image.shape[0] - box_size)
|
||||
box = image[cy:cy+box_size, cx:cx+box_size]
|
||||
|
||||
print(str(cx) + ", " + str(cy))
|
||||
area = cv2.contourArea(c)
|
||||
|
||||
if area < 148:
|
||||
print('Area too small: ' + str(area) + "at " + str(cx) + 'x' + str(cy))
|
||||
return None
|
||||
|
||||
return (box, cx, cy)
|
||||
|
||||
|
||||
def process_image(image, mask_color):
|
||||
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
|
||||
green_mask = cv2.inRange(image, mask_color, mask_color)
|
||||
if isExec:
|
||||
cv2.imshow("Mask", green_mask)
|
||||
(_, cs, _) = cv2.findContours(green_mask,
|
||||
cv2.RETR_EXTERNAL,
|
||||
cv2.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
boxes = []
|
||||
for c in cs:
|
||||
isRect = detect_shape(c)
|
||||
|
||||
if isRect or True:
|
||||
print("Rectangle detected")
|
||||
pc = process_contour(image, c)
|
||||
if pc is not None:
|
||||
boxes.append(pc)
|
||||
|
||||
return boxes
|
||||
|
||||
|
||||
def process_image_path(image_path, mask_color):
|
||||
image = cv2.imread(image_path)
|
||||
return (image, process_image(image, mask_color))
|
||||
|
||||
|
||||
def write_to_file(image, path):
|
||||
cv2.imwrite(path, image)
|
||||
|
||||
|
||||
def main():
|
||||
"""Entry function."""
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('-f', '--file', required=True, help='Path to image file')
|
||||
ap.add_argument('-g', '--green', required=False, default=255)
|
||||
ap.add_argument('-r', '--red', required=False, default=0)
|
||||
ap.add_argument('-b', '--blue', required=False, default=0)
|
||||
args = ap.parse_args()
|
||||
|
||||
(image, boxes) = process_image_path(args.file, (args.red, args.green, args.blue))
|
||||
|
||||
print(len(boxes))
|
||||
for (box_image, cx, cy) in boxes:
|
||||
cv2.imshow("Box " + str(cx) + 'x' + str(cy), box_image)
|
||||
|
||||
cv2.waitKey(0)
|
||||
cv2.destroyAllWindows()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
98
test.py
98
test.py
@ -1,98 +0,0 @@
|
||||
import numpy as np
|
||||
import tensorflow as tf
|
||||
from PIL import Image
|
||||
import tqdm
|
||||
import os
|
||||
import matplotlib.pyplot as plt
|
||||
import sys
|
||||
sys.path.append('..')
|
||||
|
||||
from model import Model
|
||||
from config import *
|
||||
|
||||
IMAGE_SIZE = 128
|
||||
LOCAL_SIZE = 64
|
||||
HOLE_MIN = 24
|
||||
HOLE_MAX = 48
|
||||
BATCH_SIZE = 16
|
||||
|
||||
test_npy = './lfw.npy'
|
||||
|
||||
def test(args):
|
||||
x = tf.placeholder(tf.float32, [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, 3])
|
||||
mask = tf.placeholder(tf.float32, [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, 1])
|
||||
local_x = tf.placeholder(tf.float32, [BATCH_SIZE, LOCAL_SIZE, LOCAL_SIZE, 3])
|
||||
global_completion = tf.placeholder(tf.float32, [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, 3])
|
||||
local_completion = tf.placeholder(tf.float32, [BATCH_SIZE, LOCAL_SIZE, LOCAL_SIZE, 3])
|
||||
is_training = tf.placeholder(tf.bool, [])
|
||||
|
||||
model = Model(x, mask, local_x, global_completion, local_completion, is_training, batch_size=BATCH_SIZE)
|
||||
sess = tf.Session()
|
||||
init_op = tf.global_variables_initializer()
|
||||
sess.run(init_op)
|
||||
|
||||
saver = tf.train.Saver()
|
||||
saver.restore(sess, './models/latest')
|
||||
|
||||
x_test = np.load(test_npy)
|
||||
np.random.shuffle(x_test)
|
||||
x_test = np.array([a / 127.5 - 1 for a in x_test])
|
||||
|
||||
step_num = int(len(x_test) / BATCH_SIZE)
|
||||
|
||||
cnt = 0
|
||||
for i in tqdm.tqdm(range(step_num)):
|
||||
x_batch = x_test[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]
|
||||
_, mask_batch = get_points()
|
||||
completion = sess.run(model.completion, feed_dict={x: x_batch, mask: mask_batch, is_training: False})
|
||||
for i in range(BATCH_SIZE):
|
||||
cnt += 1
|
||||
raw = x_batch[i]
|
||||
raw = np.array((raw + 1) * 127.5, dtype=np.uint8)
|
||||
masked = raw * (1 - mask_batch[i]) + np.ones_like(raw) * mask_batch[i] * 255
|
||||
img = completion[i]
|
||||
img = np.array((img + 1) * 127.5, dtype=np.uint8)
|
||||
dst = args.testing_output_path + '{}.jpg'.format("{0:06d}".format(cnt))
|
||||
output_image([['Input', masked], ['Output', img], ['Ground Truth', raw]], dst)
|
||||
|
||||
|
||||
def get_points():
|
||||
points = []
|
||||
mask = []
|
||||
for i in range(BATCH_SIZE):
|
||||
x1, y1 = np.random.randint(0, IMAGE_SIZE - LOCAL_SIZE + 1, 2)
|
||||
x2, y2 = np.array([x1, y1]) + LOCAL_SIZE
|
||||
points.append([x1, y1, x2, y2])
|
||||
|
||||
w, h = np.random.randint(HOLE_MIN, HOLE_MAX + 1, 2)
|
||||
p1 = x1 + np.random.randint(0, LOCAL_SIZE - w)
|
||||
q1 = y1 + np.random.randint(0, LOCAL_SIZE - h)
|
||||
p2 = p1 + w
|
||||
q2 = q1 + h
|
||||
|
||||
m = np.zeros((IMAGE_SIZE, IMAGE_SIZE, 1), dtype=np.uint8)
|
||||
m[q1:q2 + 1, p1:p2 + 1] = 1
|
||||
mask.append(m)
|
||||
|
||||
return np.array(points), np.array(mask)
|
||||
|
||||
|
||||
def output_image(images, dst):
|
||||
fig = plt.figure()
|
||||
for i, image in enumerate(images):
|
||||
text, img = image
|
||||
fig.add_subplot(1, 3, i + 1)
|
||||
plt.imshow(img)
|
||||
plt.tick_params(labelbottom='off')
|
||||
plt.tick_params(labelleft='off')
|
||||
plt.gca().get_xaxis().set_ticks_position('none')
|
||||
plt.gca().get_yaxis().set_ticks_position('none')
|
||||
plt.xlabel(text)
|
||||
plt.savefig(dst)
|
||||
plt.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not os.path.exists(args.testing_output_path):
|
||||
os.makedirs(args.testing_output_path)
|
||||
test(args)
|
159
train.py
159
train.py
@ -1,159 +0,0 @@
|
||||
import numpy as np
|
||||
import tensorflow as tf
|
||||
from PIL import Image
|
||||
import tqdm
|
||||
import scipy.ndimage
|
||||
import os
|
||||
|
||||
from model import Model
|
||||
import load
|
||||
from config import *
|
||||
|
||||
PRETRAIN_EPOCH = 100
|
||||
|
||||
def train(args):
|
||||
x = tf.placeholder(tf.float32, [args.batch_size, args.input_size, args.input_size, args.input_channel_size])
|
||||
mask = tf.placeholder(tf.float32, [args.batch_size, args.input_size, args.input_size, 1])
|
||||
local_x = tf.placeholder(tf.float32, [args.batch_size, args.local_input_size, args.local_input_size, args.input_channel_size])
|
||||
global_completion = tf.placeholder(tf.float32, [args.batch_size, args.input_size, args.input_size, args.input_channel_size])
|
||||
local_completion = tf.placeholder(tf.float32, [args.batch_size, args.local_input_size, args.local_input_size, args.input_channel_size])
|
||||
is_training = tf.placeholder(tf.bool, [])
|
||||
|
||||
model = Model(x, mask, local_x, global_completion, local_completion, is_training, batch_size=args.batch_size)
|
||||
sess = tf.Session()
|
||||
global_step = tf.Variable(0, name='global_step', trainable=False)
|
||||
epoch = tf.Variable(0, name='epoch', trainable=False)
|
||||
|
||||
opt = tf.train.AdamOptimizer(learning_rate=args.learning_rate)
|
||||
g_train_op = opt.minimize(model.g_loss, global_step=global_step, var_list=model.g_variables)
|
||||
d_train_op = opt.minimize(model.d_loss, global_step=global_step, var_list=model.d_variables)
|
||||
|
||||
init_op = tf.global_variables_initializer()
|
||||
sess.run(init_op)
|
||||
|
||||
if args.continue_training:
|
||||
if tf.train.get_checkpoint_state('./models'):
|
||||
print("Continuing training from checkpoint.")
|
||||
saver = tf.train.Saver()
|
||||
saver.restore(sess, './models/latest')
|
||||
else:
|
||||
print("Checkpoint not found! Training new model from scratch.")
|
||||
|
||||
x_train, x_test = load.load()
|
||||
x_train = np.array([a / 127.5 - 1 for a in x_train])
|
||||
x_test = np.array([a / 127.5 - 1 for a in x_test])
|
||||
|
||||
step_num = int(len(x_train) / args.batch_size)
|
||||
|
||||
while True:
|
||||
sess.run(tf.assign(epoch, tf.add(epoch, 1)))
|
||||
print('epoch: {}'.format(sess.run(epoch)))
|
||||
|
||||
np.random.shuffle(x_train)
|
||||
|
||||
x_batch = []
|
||||
mask_batch = []
|
||||
|
||||
# Completion
|
||||
if sess.run(epoch) <= PRETRAIN_EPOCH:
|
||||
g_loss_value = 0
|
||||
for i in tqdm.tqdm(range(step_num)):
|
||||
x_batch = x_train[i * args.batch_size:(i + 1) * args.batch_size]
|
||||
_, mask_batch = get_points()
|
||||
|
||||
_, g_loss = sess.run([g_train_op, model.g_loss], feed_dict={x: x_batch, mask: mask_batch, is_training: True})
|
||||
g_loss_value += g_loss
|
||||
|
||||
print('Completion loss: {}'.format(g_loss_value))
|
||||
|
||||
#stop gap solution. sample images only generated when number of test images greater than or equal to batch size
|
||||
if x_test.shape[0] >= args.batch_size:
|
||||
np.random.shuffle(x_test)
|
||||
x_batch = x_test[:args.batch_size]
|
||||
completion = sess.run(model.completion, feed_dict={x: x_batch, mask: mask_batch, is_training: False})
|
||||
sample = np.array((completion[0] + 1) * 127.5, dtype=np.uint8)
|
||||
result = Image.fromarray(sample)
|
||||
result.save(args.training_samples_path + '{}.jpg'.format("{0:06d}".format(sess.run(epoch))))
|
||||
|
||||
saver = tf.train.Saver()
|
||||
saver.save(sess, './models/latest', write_meta_graph=False)
|
||||
if sess.run(epoch) == PRETRAIN_EPOCH:
|
||||
saver.save(sess, './models/pretrained', write_meta_graph=False)
|
||||
|
||||
|
||||
# Discrimitation
|
||||
else:
|
||||
g_loss_value = 0
|
||||
d_loss_value = 0
|
||||
for i in tqdm.tqdm(range(step_num)):
|
||||
x_batch = x_train[i * args.batch_size:(i + 1) * args.batch_size]
|
||||
#janky way of doing horizonal flips
|
||||
if (np.random.random() < 0.5):
|
||||
x_batch = np.fliplr(x_batch)
|
||||
points_batch, mask_batch = get_points()
|
||||
|
||||
_, g_loss, completion = sess.run([g_train_op, model.g_loss, model.completion], feed_dict={x: x_batch, mask: mask_batch, is_training: True})
|
||||
g_loss_value += g_loss
|
||||
|
||||
local_x_batch = []
|
||||
local_completion_batch = []
|
||||
for i in range(args.batch_size):
|
||||
x1, y1, x2, y2 = points_batch[i]
|
||||
local_x_batch.append(x_batch[i][y1:y2, x1:x2, :])
|
||||
local_completion_batch.append(completion[i][y1:y2, x1:x2, :])
|
||||
local_x_batch = np.array(local_x_batch)
|
||||
local_completion_batch = np.array(local_completion_batch)
|
||||
|
||||
_, d_loss = sess.run(
|
||||
[d_train_op, model.d_loss],
|
||||
feed_dict={x: x_batch, mask: mask_batch, local_x: local_x_batch, global_completion: completion, local_completion: local_completion_batch, is_training: True})
|
||||
d_loss_value += d_loss
|
||||
|
||||
print('Completion loss: {}'.format(g_loss_value))
|
||||
print('Discriminator loss: {}'.format(d_loss_value))
|
||||
|
||||
#stop gap solution. sample images only generated when number of test images greater than or equal to batch size
|
||||
if x_test.shape[0] >= args.batch_size:
|
||||
np.random.shuffle(x_test)
|
||||
x_batch = x_test[:args.batch_size]
|
||||
completion = sess.run(model.completion, feed_dict={x: x_batch, mask: mask_batch, is_training: False})
|
||||
sample = np.array((completion[0] + 1) * 127.5, dtype=np.uint8)
|
||||
result = Image.fromarray(sample)
|
||||
result.save(args.training_samples_path + '{}.jpg'.format("{0:06d}".format(sess.run(epoch))))
|
||||
|
||||
saver = tf.train.Saver()
|
||||
saver.save(sess, './models/latest', write_meta_graph=False)
|
||||
|
||||
|
||||
def get_points():
|
||||
points = []
|
||||
mask = []
|
||||
for i in range(args.batch_size):
|
||||
x1, y1 = np.random.randint(0, args.input_size - args.local_input_size + 1, 2)
|
||||
x2, y2 = np.array([x1, y1]) + args.local_input_size
|
||||
points.append([x1, y1, x2, y2])
|
||||
|
||||
w, h = np.random.randint(args.min_mask_size, args.max_mask_size + 1, 2)
|
||||
p1 = x1 + np.random.randint(0, args.local_input_size - w)
|
||||
q1 = y1 + np.random.randint(0, args.local_input_size - h)
|
||||
p2 = p1 + w
|
||||
q2 = q1 + h
|
||||
|
||||
m = np.zeros((args.input_size, args.input_size, 1), dtype=np.uint8)
|
||||
m[q1:q2 + 1, p1:p2 + 1] = 1
|
||||
|
||||
if (np.random.random() < args.rotate_chance):
|
||||
#rotate random amount between 0 and 90 degrees
|
||||
m = scipy.ndimage.rotate(m, np.random.random()*90, reshape = False)
|
||||
#set all elements greater than 0.5 to 1
|
||||
m[m > 0.5] = 1
|
||||
|
||||
mask.append(m)
|
||||
|
||||
return np.array(points), np.array(mask)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not os.path.exists(args.training_samples_path):
|
||||
os.makedirs(args.training_samples_path)
|
||||
train(args)
|
176
train_mosaic.py
176
train_mosaic.py
@ -1,176 +0,0 @@
|
||||
import numpy as np
|
||||
import tensorflow as tf
|
||||
from PIL import Image, ImageFilter
|
||||
import tqdm
|
||||
from model_mosaic import Model
|
||||
import load
|
||||
|
||||
IMAGE_SIZE = 128
|
||||
LOCAL_SIZE = 64
|
||||
HOLE_MIN = 24
|
||||
HOLE_MAX = 48
|
||||
MOSAIC_MIN = 8 #Minimum number of mosaic squares across image
|
||||
MOSAIC_MAX = 32 #Maximum number of mosaic squares across image
|
||||
MOSAIC_GAUSSIAN_P = 0.5 #represent images that have been compressed post-mosaic
|
||||
MOSAIC_GAUSSIAN_MIN = 0.2
|
||||
MOSAIC_GAUSSIAN_MAX = 1.2
|
||||
LEARNING_RATE = 1e-3
|
||||
BATCH_SIZE = 16
|
||||
PRETRAIN_EPOCH = 100
|
||||
|
||||
def train():
|
||||
x = tf.placeholder(tf.float32, [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, 3])
|
||||
mosaic = tf.placeholder(tf.float32, [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, 3])
|
||||
mask = tf.placeholder(tf.float32, [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, 1])
|
||||
local_x = tf.placeholder(tf.float32, [BATCH_SIZE, LOCAL_SIZE, LOCAL_SIZE, 3])
|
||||
global_completion = tf.placeholder(tf.float32, [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, 3])
|
||||
local_completion = tf.placeholder(tf.float32, [BATCH_SIZE, LOCAL_SIZE, LOCAL_SIZE, 3])
|
||||
is_training = tf.placeholder(tf.bool, [])
|
||||
|
||||
model = Model(x, mosaic, mask, local_x, global_completion, local_completion, is_training, batch_size=BATCH_SIZE)
|
||||
sess = tf.Session()
|
||||
global_step = tf.Variable(0, name='global_step', trainable=False)
|
||||
epoch = tf.Variable(0, name='epoch', trainable=False)
|
||||
|
||||
opt = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE)
|
||||
g_train_op = opt.minimize(model.g_loss, global_step=global_step, var_list=model.g_variables)
|
||||
d_train_op = opt.minimize(model.d_loss, global_step=global_step, var_list=model.d_variables)
|
||||
|
||||
init_op = tf.global_variables_initializer()
|
||||
sess.run(init_op)
|
||||
|
||||
if tf.train.get_checkpoint_state('./models'):
|
||||
saver = tf.train.Saver()
|
||||
saver.restore(sess, './models/latest')
|
||||
|
||||
x_train, x_test = load.load()
|
||||
x_train = np.array([a / 127.5 - 1 for a in x_train])
|
||||
x_test = np.array([a / 127.5 - 1 for a in x_test])
|
||||
|
||||
step_num = int(len(x_train) / BATCH_SIZE)
|
||||
|
||||
while True:
|
||||
sess.run(tf.assign(epoch, tf.add(epoch, 1)))
|
||||
print('epoch: {}'.format(sess.run(epoch)))
|
||||
|
||||
np.random.shuffle(x_train)
|
||||
|
||||
# Completion
|
||||
if sess.run(epoch) <= PRETRAIN_EPOCH:
|
||||
g_loss_value = 0
|
||||
for i in tqdm.tqdm(range(step_num)):
|
||||
x_batch = x_train[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]
|
||||
points_batch, mask_batch = get_points()
|
||||
mosaic_batch = get_mosaic(x_batch)
|
||||
|
||||
_, g_loss = sess.run([g_train_op, model.g_loss], feed_dict={x: x_batch, mask: mask_batch, mosaic: mosaic_batch, is_training: True})
|
||||
g_loss_value += g_loss
|
||||
|
||||
print('Completion loss: {}'.format(g_loss_value))
|
||||
|
||||
f = open("loss.csv","a+")
|
||||
f.write(str(sess.run(epoch)) + "," + str(g_loss_value) + "," + "0" + "\n")
|
||||
f.close()
|
||||
|
||||
np.random.shuffle(x_test)
|
||||
x_batch = x_test[:BATCH_SIZE]
|
||||
mosaic_batch = get_mosaic(x_batch)
|
||||
merged, completion = sess.run([model.merged, model.completion], feed_dict={x: x_batch, mask: mask_batch, mosaic: mosaic_batch, is_training: False})
|
||||
sample = np.array((merged[0] + 1) * 127.5, dtype=np.uint8)
|
||||
result = Image.fromarray(sample)
|
||||
result.save('./training_output_images/{}_0.png'.format("{0:06d}".format(sess.run(epoch))))
|
||||
sample = np.array((completion[0] + 1) * 127.5, dtype=np.uint8)
|
||||
result = Image.fromarray(sample)
|
||||
result.save('./training_output_images/{}_1.png'.format("{0:06d}".format(sess.run(epoch))))
|
||||
|
||||
saver = tf.train.Saver()
|
||||
saver.save(sess, './models/latest', write_meta_graph=False)
|
||||
if sess.run(epoch) == PRETRAIN_EPOCH:
|
||||
saver.save(sess, './models/pretrained', write_meta_graph=False)
|
||||
|
||||
|
||||
# Discrimitation
|
||||
else:
|
||||
g_loss_value = 0
|
||||
d_loss_value = 0
|
||||
for i in tqdm.tqdm(range(step_num)):
|
||||
x_batch = x_train[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]
|
||||
points_batch, mask_batch = get_points()
|
||||
mosaic_batch = get_mosaic(x_batch)
|
||||
|
||||
_, g_loss, completion = sess.run([g_train_op, model.g_loss, model.completion], feed_dict={x: x_batch, mask: mask_batch, mosaic: mosaic_batch, is_training: True})
|
||||
g_loss_value += g_loss
|
||||
|
||||
local_x_batch = []
|
||||
local_completion_batch = []
|
||||
for i in range(BATCH_SIZE):
|
||||
x1, y1, x2, y2 = points_batch[i]
|
||||
local_x_batch.append(x_batch[i][y1:y2, x1:x2, :])
|
||||
local_completion_batch.append(completion[i][y1:y2, x1:x2, :])
|
||||
local_x_batch = np.array(local_x_batch)
|
||||
local_completion_batch = np.array(local_completion_batch)
|
||||
|
||||
_, d_loss = sess.run(
|
||||
[d_train_op, model.d_loss],
|
||||
feed_dict={x: x_batch, mask: mask_batch, local_x: local_x_batch, global_completion: completion, local_completion: local_completion_batch, is_training: True})
|
||||
d_loss_value += d_loss
|
||||
|
||||
print('Completion loss: {}'.format(g_loss_value))
|
||||
print('Discriminator loss: {}'.format(d_loss_value))
|
||||
|
||||
np.random.shuffle(x_test)
|
||||
x_batch = x_test[:BATCH_SIZE]
|
||||
mosaic_batch = get_mosaic(x_batch)
|
||||
merged, completion = sess.run([model.merged, model.completion], feed_dict={x: x_batch, mask: mask_batch, mosaic: mosaic_batch, is_training: False})
|
||||
sample = np.array((merged[0] + 1) * 127.5, dtype=np.uint8)
|
||||
result = Image.fromarray(sample)
|
||||
result.save('./training_output_images/{}_0.png'.format("{0:06d}".format(sess.run(epoch))))
|
||||
sample = np.array((completion[0] + 1) * 127.5, dtype=np.uint8)
|
||||
result = Image.fromarray(sample)
|
||||
result.save('./training_output_images/{}_1.png'.format("{0:06d}".format(sess.run(epoch))))
|
||||
|
||||
saver = tf.train.Saver()
|
||||
saver.save(sess, './models/latest', write_meta_graph=False)
|
||||
|
||||
|
||||
def get_points():
|
||||
points = []
|
||||
mask = []
|
||||
for i in range(BATCH_SIZE):
|
||||
x1, y1 = np.random.randint(0, IMAGE_SIZE - LOCAL_SIZE + 1, 2)
|
||||
x2, y2 = np.array([x1, y1]) + LOCAL_SIZE
|
||||
points.append([x1, y1, x2, y2])
|
||||
|
||||
w, h = np.random.randint(HOLE_MIN, HOLE_MAX + 1, 2)
|
||||
p1 = x1 + np.random.randint(0, LOCAL_SIZE - w)
|
||||
q1 = y1 + np.random.randint(0, LOCAL_SIZE - h)
|
||||
p2 = p1 + w
|
||||
q2 = q1 + h
|
||||
|
||||
m = np.zeros((IMAGE_SIZE, IMAGE_SIZE, 1), dtype=np.uint8)
|
||||
m[q1:q2 + 1, p1:p2 + 1] = 1
|
||||
mask.append(m)
|
||||
|
||||
return np.array(points), np.array(mask)
|
||||
|
||||
|
||||
def get_mosaic(x_batch):
|
||||
mosaic = []
|
||||
for i in range(BATCH_SIZE):
|
||||
im = np.array((x_batch[i] + 1) * 127.5, dtype=np.uint8)
|
||||
im = Image.fromarray(im)
|
||||
size = np.random.randint(MOSAIC_MIN, MOSAIC_MAX)
|
||||
im = im.resize((size,size),Image.LANCZOS)
|
||||
im = im.resize((IMAGE_SIZE,IMAGE_SIZE),Image.NEAREST)
|
||||
if np.random.rand() < MOSAIC_GAUSSIAN_P:
|
||||
im = im.filter(ImageFilter.GaussianBlur(np.random.uniform(MOSAIC_GAUSSIAN_MIN, MOSAIC_GAUSSIAN_MAX)))
|
||||
|
||||
mosaic.append(np.array(im))
|
||||
|
||||
mosaic = np.array([a / 127.5 - 1 for a in mosaic])
|
||||
return mosaic
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
train()
|
||||
|
3
training_data/.gitignore
vendored
3
training_data/.gitignore
vendored
@ -1,3 +0,0 @@
|
||||
images/*
|
||||
npy/*
|
||||
!.gitkeep
|
@ -1,37 +0,0 @@
|
||||
import glob
|
||||
import os
|
||||
#import cv2
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
ratio = 0.95
|
||||
image_size = 128
|
||||
|
||||
x = []
|
||||
paths = glob.glob('images/*')
|
||||
for path in paths:
|
||||
#img = cv2.imread(path)
|
||||
#img = Image.open(path)
|
||||
#img = cv2.resize(img, (image_size, image_size))
|
||||
#img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
||||
#x.append(img)
|
||||
temp = Image.open(path)
|
||||
#remove alpha channel
|
||||
if temp.mode=='RGBA':
|
||||
temp = temp.convert('RGB')
|
||||
keep = temp.copy()
|
||||
keep = np.array(keep)
|
||||
x.append(keep)
|
||||
temp.close()
|
||||
|
||||
x = np.array(x, dtype=np.uint8)
|
||||
#np.random.shuffle(x)
|
||||
|
||||
p = int(ratio * len(x))
|
||||
x_train = x[:p]
|
||||
x_test = x[p:]
|
||||
|
||||
if not os.path.exists('./npy'):
|
||||
os.mkdir('./npy')
|
||||
np.save('./npy/x_train.npy', x_train)
|
||||
np.save('./npy/x_test.npy', x_test)
|
Loading…
x
Reference in New Issue
Block a user