├── .gitignore ├── LICENSE ├── README.md ├── demo.py ├── demo.yaml ├── imgs ├── GUI.gif ├── earring.jpg ├── face_edit.jpg ├── restoration.jpg ├── restoration2.jpg └── teaser.jpg ├── model.py ├── ops.py ├── requirements.txt ├── samples ├── 00001.png ├── 00011.png ├── 00018.png ├── 00221.png └── 00225.png ├── ui ├── mouse_event.py └── ui.py └── utils └── config.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | ## creative commons 2 | 3 | # Attribution-NonCommercial 4.0 International 4 | 5 | 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. 6 | 7 | ### Using Creative Commons Public Licenses 8 | 9 | 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. 10 | 11 | * __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). 12 | 13 | * __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). 14 | 15 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License 16 | 17 | 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 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. 18 | 19 | ### Section 1 – Definitions. 20 | 21 | a. __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. 22 | 23 | b. __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. 24 | 25 | c. __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. 26 | 27 | d. __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. 28 | 29 | e. __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. 30 | 31 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 32 | 33 | g. __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. 34 | 35 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 36 | 37 | i. __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. 38 | 39 | j. __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. 40 | 41 | k. __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. 42 | 43 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 44 | 45 | ### Section 2 – Scope. 46 | 47 | a. ___License grant.___ 48 | 49 | 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: 50 | 51 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 52 | 53 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 54 | 55 | 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. 56 | 57 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 58 | 59 | 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. 60 | 61 | 5. __Downstream recipients.__ 62 | 63 | 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. 64 | 65 | B. __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. 66 | 67 | 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). 68 | 69 | b. ___Other rights.___ 70 | 71 | 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. 72 | 73 | 2. Patent and trademark rights are not licensed under this Public License. 74 | 75 | 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. 76 | 77 | ### Section 3 – License Conditions. 78 | 79 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 80 | 81 | a. ___Attribution.___ 82 | 83 | 1. If You Share the Licensed Material (including in modified form), You must: 84 | 85 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 86 | 87 | 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); 88 | 89 | ii. a copyright notice; 90 | 91 | iii. a notice that refers to this Public License; 92 | 93 | iv. a notice that refers to the disclaimer of warranties; 94 | 95 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 96 | 97 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 98 | 99 | 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. 100 | 101 | 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. 102 | 103 | 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. 104 | 105 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 106 | 107 | ### Section 4 – Sui Generis Database Rights. 108 | 109 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 110 | 111 | a. 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; 112 | 113 | b. 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; and 114 | 115 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 116 | 117 | 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. 118 | 119 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 120 | 121 | a. __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.__ 122 | 123 | b. __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.__ 124 | 125 | c. 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. 126 | 127 | ### Section 6 – Term and Termination. 128 | 129 | a. 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. 130 | 131 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 132 | 133 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 134 | 135 | 2. upon express reinstatement by the Licensor. 136 | 137 | 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. 138 | 139 | c. 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. 140 | 141 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 142 | 143 | ### Section 7 – Other Terms and Conditions. 144 | 145 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 146 | 147 | b. 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. 148 | 149 | ### Section 8 – Interpretation. 150 | 151 | a. 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. 152 | 153 | b. 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. 154 | 155 | c. 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. 156 | 157 | d. 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. 158 | 159 | > 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.” 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. 160 | > -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SC-FEGAN 2 | SC-FEGAN : Face Editing Generative Adversarial Network with User's Sketch and Color (ICCV 2019) 3 | 4 | Youngjoo Jo, Jongyoul Park 5 | 6 | arXiv: [https://arxiv.org/abs/1902.06838](https://arxiv.org/abs/1902.06838) 7 | 8 | ![Teaser GUI](imgs/GUI.gif) 9 | 10 | ## Overview 11 | Edit face images using a a deep neural network. Users can edit face images using intuitive inputs such as sketching and coloring, from which our network SC-FEGAN generates high quality synthetic images. We used SN-patchGAN discriminator and Unet-like generator with gated convolutional layers. 12 | 13 | ![Teaser Image](imgs/teaser.jpg) 14 | 15 | ## Dependencies 16 | - tensorflow 17 | - numpy 18 | - Python3 19 | - PyQt5 20 | - opencv-python 21 | - pyyaml 22 | 23 | ## Setup 24 | First, download the model from [Google drive](https://drive.google.com/open?id=1VPsYuIK_DY3Gw07LEjUhg2LwbEDlFpq1). 25 | 26 | Run these commands to start the program. 27 | ``` 28 | mv /${HOME}/SC-FEGAN.ckpt.* /${HOME}/ckpt/ 29 | python3 demo.py 30 | ``` 31 | 32 | Select the number of GPUs you want to use by editing `demo.yaml` file (multi-GPUs are not supported). 33 | ``` 34 | GPU_NUM: 1 (the number you want to use) 35 | #GPU_NUM: (if you want to use only CPU, erase the number) 36 | ``` 37 | 38 | ## How to Use 39 | Edit face images using a simple GUI. Only erased regions of the image are filled in by the network. 40 | 41 | Explanation of the buttons: 42 | 43 | - `Open Image`: Open the image you want to edit. 44 | - `Mask`: Draw a mask on the desired regions of the face on the left viewer. 45 | - `Sketches`: Sketch the desired lines on the left viewer. 46 | - `Color`: Draw colored lines. If you click this button the first time, you have to choose a color from the palette. 47 | - `Palette`: Change color. After choosing a color, click the `Color` button to apply the change. 48 | - `Save Img`: Save the results. It is saved as '*name.jpg*'. 49 | - `Arrange`: Arrange the editing works. 50 | - `Undo`: Undo previous editing work. 51 | - `Complete`: Generate the image and show it on the right viewer. 52 | 53 | 54 | We recommend using the following workflow: 55 | ``` 56 | 1. Draw the sketch plausibly referring to the original image. 57 | 2. Draw the mask on the sketched region. 58 | 3. Click the `Arrange` button. 59 | 4. Draw the color on the masked region. 60 | 5. Click `Complete'. 61 | ``` 62 | 63 | ## Example Results 64 | ### Face editing 65 | ![Face editing](imgs/face_edit.jpg) 66 | 67 | ### Edit earring 68 | ![Earring](imgs/earring.jpg) 69 | 70 | ### Face restoration 71 | ![restore1](imgs/restoration.jpg) 72 | 73 | ### Face restoration (with only sketch and color) 74 | ![restore2](imgs/restoration2.jpg) 75 | 76 | ## License 77 | CC 4.0 Attribution-NonCommercial International 78 | 79 | The software is for educational and academic research purpose only. 80 | 81 | ## Notes 82 | 83 | - This is developed on Linux machine running Ubuntu 18.04.1 84 | - Provided model and sample code is under a non-commercial creative commons license. 85 | 86 | ## Citing 87 | ``` 88 | @InProceedings{Jo_2019_ICCV, 89 | author = {Jo, Youngjoo and Park, Jongyoul}, 90 | title = {SC-FEGAN: Face Editing Generative Adversarial Network With User's Sketch and Color}, 91 | booktitle = {The IEEE International Conference on Computer Vision (ICCV)}, 92 | month = {October}, 93 | year = {2019} 94 | } 95 | ``` 96 | 97 | ## Next 98 | - Update training code 99 | 100 | ## Acknowledgement 101 | We acknowledge the official code [DeepFillv1](https://github.com/JiahuiYu/generative_inpainting). We thank all the researchers at ETRI, especially Kimin Yun and Jinwoo Jung, for insightful discussions. 102 | -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5.QtCore import * 3 | from PyQt5.QtGui import * 4 | from PyQt5.QtWidgets import * 5 | from PyQt5.QtPrintSupport import QPrintDialog, QPrinter 6 | from ui.ui import Ui_Form 7 | from ui.mouse_event import GraphicsScene 8 | import cv2 9 | import numpy as np 10 | from utils.config import Config 11 | from model import Model 12 | import os 13 | import time 14 | 15 | class Ex(QWidget, Ui_Form): 16 | def __init__(self, model, config): 17 | super().__init__() 18 | self.setupUi(self) 19 | self.show() 20 | self.model = model 21 | self.config = config 22 | self.model.load_demo_graph(config) 23 | 24 | self.output_img = None 25 | 26 | self.mat_img = None 27 | 28 | self.ld_mask = None 29 | self.ld_sk = None 30 | 31 | self.modes = [0,0,0] 32 | self.mouse_clicked = False 33 | self.scene = GraphicsScene(self.modes) 34 | self.graphicsView.setScene(self.scene) 35 | self.graphicsView.setAlignment(Qt.AlignTop | Qt.AlignLeft) 36 | self.graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 37 | self.graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 38 | 39 | self.result_scene = QGraphicsScene() 40 | self.graphicsView_2.setScene(self.result_scene) 41 | self.graphicsView_2.setAlignment(Qt.AlignTop | Qt.AlignLeft) 42 | self.graphicsView_2.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 43 | self.graphicsView_2.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 44 | 45 | self.dlg = QColorDialog(self.graphicsView) 46 | self.color = None 47 | 48 | def mode_select(self, mode): 49 | for i in range(len(self.modes)): 50 | self.modes[i] = 0 51 | self.modes[mode] = 1 52 | 53 | def open(self): 54 | fileName, _ = QFileDialog.getOpenFileName(self, "Open File", 55 | QDir.currentPath()) 56 | if fileName: 57 | image = QPixmap(fileName) 58 | mat_img = cv2.imread(fileName) 59 | if image.isNull(): 60 | QMessageBox.information(self, "Image Viewer", 61 | "Cannot load %s." % fileName) 62 | return 63 | 64 | # redbrush = QBrush(Qt.red) 65 | # blackpen = QPen(Qt.black) 66 | # blackpen.setWidth(5) 67 | self.image = image.scaled(self.graphicsView.size(), Qt.IgnoreAspectRatio) 68 | mat_img = cv2.resize(mat_img, (512, 512), interpolation=cv2.INTER_CUBIC) 69 | mat_img = mat_img/127.5 - 1 70 | self.mat_img = np.expand_dims(mat_img,axis=0) 71 | self.scene.reset() 72 | if len(self.scene.items())>0: 73 | self.scene.reset_items() 74 | self.scene.addPixmap(self.image) 75 | if len(self.result_scene.items())>0: 76 | self.result_scene.removeItem(self.result_scene.items()[-1]) 77 | self.result_scene.addPixmap(self.image) 78 | 79 | def mask_mode(self): 80 | self.mode_select(0) 81 | 82 | def sketch_mode(self): 83 | self.mode_select(1) 84 | 85 | def stroke_mode(self): 86 | if not self.color: 87 | self.color_change_mode() 88 | self.scene.get_stk_color(self.color) 89 | self.mode_select(2) 90 | 91 | def color_change_mode(self): 92 | self.dlg.exec_() 93 | self.color = self.dlg.currentColor().name() 94 | self.pushButton_4.setStyleSheet("background-color: %s;" % self.color) 95 | self.scene.get_stk_color(self.color) 96 | 97 | def complete(self): 98 | sketch = self.make_sketch(self.scene.sketch_points) 99 | stroke = self.make_stroke(self.scene.stroke_points) 100 | mask = self.make_mask(self.scene.mask_points) 101 | if not type(self.ld_mask)==type(None): 102 | ld_mask = np.expand_dims(self.ld_mask[:,:,0:1],axis=0) 103 | ld_mask[ld_mask>0] = 1 104 | ld_mask[ld_mask<1] = 0 105 | mask = mask+ld_mask 106 | mask[mask>0] = 1 107 | mask[mask<1] = 0 108 | mask = np.asarray(mask,dtype=np.uint8) 109 | print(mask.shape) 110 | 111 | if not type(self.ld_sk)==type(None): 112 | sketch = sketch+self.ld_sk 113 | sketch[sketch>0]=1 114 | 115 | noise = self.make_noise() 116 | 117 | sketch = sketch*mask 118 | stroke = stroke*mask 119 | noise = noise*mask 120 | 121 | batch = np.concatenate( 122 | [self.mat_img, 123 | sketch, 124 | stroke, 125 | mask, 126 | noise],axis=3) 127 | start_t = time.time() 128 | result = self.model.demo(self.config, batch) 129 | end_t = time.time() 130 | print('inference time : {}'.format(end_t-start_t)) 131 | result = (result+1)*127.5 132 | result = np.asarray(result[0,:,:,:],dtype=np.uint8) 133 | self.output_img = result 134 | result = np.concatenate([result[:,:,2:3],result[:,:,1:2],result[:,:,:1]],axis=2) 135 | qim = QImage(result.data, result.shape[1], result.shape[0], result.strides[0], QImage.Format_RGB888) 136 | self.result_scene.removeItem(self.result_scene.items()[-1]) 137 | self.result_scene.addPixmap(QPixmap.fromImage(qim)) 138 | 139 | def make_noise(self): 140 | noise = np.zeros([512, 512, 1],dtype=np.uint8) 141 | noise = cv2.randn(noise, 0, 255) 142 | noise = np.asarray(noise/255,dtype=np.uint8) 143 | noise = np.expand_dims(noise,axis=0) 144 | return noise 145 | 146 | def make_mask(self, pts): 147 | if len(pts)>0: 148 | mask = np.zeros((512,512,3)) 149 | for pt in pts: 150 | cv2.line(mask,pt['prev'],pt['curr'],(255,255,255),12) 151 | mask = np.asarray(mask[:,:,0]/255,dtype=np.uint8) 152 | mask = np.expand_dims(mask,axis=2) 153 | mask = np.expand_dims(mask,axis=0) 154 | else: 155 | mask = np.zeros((512,512,3)) 156 | mask = np.asarray(mask[:,:,0]/255,dtype=np.uint8) 157 | mask = np.expand_dims(mask,axis=2) 158 | mask = np.expand_dims(mask,axis=0) 159 | return mask 160 | 161 | def make_sketch(self, pts): 162 | if len(pts)>0: 163 | sketch = np.zeros((512,512,3)) 164 | # sketch = 255*sketch 165 | for pt in pts: 166 | cv2.line(sketch,pt['prev'],pt['curr'],(255,255,255),1) 167 | sketch = np.asarray(sketch[:,:,0]/255,dtype=np.uint8) 168 | sketch = np.expand_dims(sketch,axis=2) 169 | sketch = np.expand_dims(sketch,axis=0) 170 | else: 171 | sketch = np.zeros((512,512,3)) 172 | # sketch = 255*sketch 173 | sketch = np.asarray(sketch[:,:,0]/255,dtype=np.uint8) 174 | sketch = np.expand_dims(sketch,axis=2) 175 | sketch = np.expand_dims(sketch,axis=0) 176 | return sketch 177 | 178 | def make_stroke(self, pts): 179 | if len(pts)>0: 180 | stroke = np.zeros((512,512,3)) 181 | for pt in pts: 182 | c = pt['color'].lstrip('#') 183 | color = tuple(int(c[i:i+2], 16) for i in (0, 2 ,4)) 184 | color = (color[2],color[1],color[0]) 185 | cv2.line(stroke,pt['prev'],pt['curr'],color,4) 186 | stroke = stroke/127.5 - 1 187 | stroke = np.expand_dims(stroke,axis=0) 188 | else: 189 | stroke = np.zeros((512,512,3)) 190 | stroke = stroke/127.5 - 1 191 | stroke = np.expand_dims(stroke,axis=0) 192 | return stroke 193 | 194 | def arrange(self): 195 | image = np.asarray((self.mat_img[0]+1)*127.5,dtype=np.uint8) 196 | if len(self.scene.mask_points)>0: 197 | for pt in self.scene.mask_points: 198 | cv2.line(image,pt['prev'],pt['curr'],(255,255,255),12) 199 | if len(self.scene.stroke_points)>0: 200 | for pt in self.scene.stroke_points: 201 | c = pt['color'].lstrip('#') 202 | color = tuple(int(c[i:i+2], 16) for i in (0, 2 ,4)) 203 | color = (color[2],color[1],color[0]) 204 | cv2.line(image,pt['prev'],pt['curr'],color,4) 205 | if len(self.scene.sketch_points)>0: 206 | for pt in self.scene.sketch_points: 207 | cv2.line(image,pt['prev'],pt['curr'],(0,0,0),1) 208 | cv2.imwrite('tmp.jpg',image) 209 | image = QPixmap('tmp.jpg') 210 | self.scene.history.append(3) 211 | self.scene.addPixmap(image) 212 | 213 | def save_img(self): 214 | if type(self.output_img): 215 | fileName, _ = QFileDialog.getSaveFileName(self, "Save File", 216 | QDir.currentPath()) 217 | cv2.imwrite(fileName+'.jpg',self.output_img) 218 | 219 | def undo(self): 220 | self.scene.undo() 221 | 222 | def clear(self): 223 | self.scene.reset_items() 224 | self.scene.reset() 225 | if type(self.image): 226 | self.scene.addPixmap(self.image) 227 | 228 | if __name__ == '__main__': 229 | config = Config('demo.yaml') 230 | os.environ["CUDA_VISIBLE_DEVICES"] = str(config.GPU_NUM) 231 | model = Model(config) 232 | 233 | app = QApplication(sys.argv) 234 | ex = Ex(model, config) 235 | sys.exit(app.exec_()) 236 | -------------------------------------------------------------------------------- /demo.yaml: -------------------------------------------------------------------------------- 1 | INPUT_SIZE: 512 2 | BATCH_SIZE: 1 3 | 4 | GPU_NUM: 1 5 | 6 | # directories 7 | CKPT_DIR: './ckpt/SC-FEGAN.ckpt' 8 | -------------------------------------------------------------------------------- /imgs/GUI.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/imgs/GUI.gif -------------------------------------------------------------------------------- /imgs/earring.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/imgs/earring.jpg -------------------------------------------------------------------------------- /imgs/face_edit.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/imgs/face_edit.jpg -------------------------------------------------------------------------------- /imgs/restoration.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/imgs/restoration.jpg -------------------------------------------------------------------------------- /imgs/restoration2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/imgs/restoration2.jpg -------------------------------------------------------------------------------- /imgs/teaser.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/imgs/teaser.jpg -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import tensorflow.contrib.slim.nets as nets 3 | import numpy as np 4 | from ops import * 5 | 6 | class Model(object): 7 | def __init__(self, config): 8 | self.input_size = config.INPUT_SIZE 9 | self.batch_size = config.BATCH_SIZE 10 | image_dims = [self.input_size, self.input_size, 3] 11 | sk_dims = [self.input_size, self.input_size, 1] 12 | color_dims = [self.input_size, self.input_size, 3] 13 | masks_dims = [self.input_size, self.input_size, 1] 14 | noises_dims = [self.input_size, self.input_size, 1] 15 | 16 | self.dtype = tf.float32 17 | 18 | self.images = tf.placeholder( 19 | self.dtype, [self.batch_size] + image_dims, name='real_images') 20 | self.sketches = tf.placeholder( 21 | self.dtype, [self.batch_size] + sk_dims, name='sketches') 22 | self.color = tf.placeholder( 23 | self.dtype, [self.batch_size] + color_dims, name='color') 24 | self.masks = tf.placeholder( 25 | self.dtype, [self.batch_size] + masks_dims, name='masks') 26 | self.noises = tf.placeholder( 27 | self.dtype, [self.batch_size] + noises_dims, name='noises') 28 | 29 | def build_gen(self, x, mask, name='generator',reuse=False, trainig=True): 30 | cnum = 64 31 | s_h, s_w = self.input_size, self.input_size 32 | s_h2, s_w2 = int(self.input_size/2), int(self.input_size/2) 33 | s_h4, s_w4 = int(self.input_size/4), int(self.input_size/4) 34 | s_h8, s_w8 = int(self.input_size/8), int(self.input_size/8) 35 | s_h16, s_w16 = int(self.input_size/16), int(self.input_size/16) 36 | s_h32, s_w32 = int(self.input_size/32), int(self.input_size/32) 37 | s_h64, s_w64 = int(self.input_size/64), int(self.input_size/64) 38 | with tf.variable_scope(name, reuse=reuse): 39 | # encoder 40 | x_now = x 41 | x1, mask1 = gate_conv(x,cnum,7,2,use_lrn=False,name='gconv1_ds') 42 | x2, mask2 = gate_conv(x1,2*cnum,5,2,name='gconv2_ds') 43 | x3, mask3 = gate_conv(x2,4*cnum,5,2,name='gconv3_ds') 44 | x4, mask4 = gate_conv(x3,8*cnum,3,2,name='gconv4_ds') 45 | x5, mask5 = gate_conv(x4,8*cnum,3,2,name='gconv5_ds') 46 | x6, mask6 = gate_conv(x5,8*cnum,3,2,name='gconv6_ds') 47 | x7, mask7 = gate_conv(x6,8*cnum,3,2,name='gconv7_ds') 48 | 49 | # dilated conv 50 | x7,_ = gate_conv(x7, 8*cnum, 3, 1, rate=2, name='co_conv1_dlt') 51 | x7,_ = gate_conv(x7, 8*cnum, 3, 1, rate=4, name='co_conv2_dlt') 52 | x7,_ = gate_conv(x7, 8*cnum, 3, 1, rate=8, name='co_conv3_dlt') 53 | x7,_ = gate_conv(x7, 8*cnum, 3, 1, rate=16, name='co_conv4_dlt') 54 | 55 | # decoder 56 | x8, _ = gate_deconv(x7,[self.batch_size, s_h64, s_w64, 8*cnum], name='deconv1') 57 | x8 = tf.concat([x6,x8],axis=3) 58 | x8, mask8 = gate_conv(x8,8*cnum,3,1,name='gconv8') 59 | 60 | x9, _ = gate_deconv(x8,[self.batch_size, s_h32, s_w32, 8*cnum], name='deconv2') 61 | x9 = tf.concat([x5,x9],axis=3) 62 | x9, mask9 = gate_conv(x9,8*cnum,3,1,name='gconv9') 63 | 64 | x10, _ = gate_deconv(x9,[self.batch_size, s_h16, s_w16, 8*cnum], name='deconv3') 65 | x10 = tf.concat([x4,x10],axis=3) 66 | x10, mask10 = gate_conv(x10,8*cnum,3,1,name='gconv10') 67 | 68 | x11, _ = gate_deconv(x10,[self.batch_size, s_h8, s_w8, 4*cnum], name='deconv4') 69 | x11 = tf.concat([x3,x11],axis=3) 70 | x11, mask11 = gate_conv(x11,4*cnum,3,1,name='gconv11') 71 | 72 | x12, _ = gate_deconv(x11,[self.batch_size, s_h4, s_w4, 2*cnum], name='deconv5') 73 | x12 = tf.concat([x2,x12],axis=3) 74 | x12, mask12 = gate_conv(x12,2*cnum,3,1,name='gconv12') 75 | 76 | x13, _ = gate_deconv(x12,[self.batch_size, s_h2, s_w2, cnum], name='deconv6') 77 | x13 = tf.concat([x1,x13],axis=3) 78 | x13, mask13 = gate_conv(x13,cnum,3,1,name='gconv13') 79 | 80 | x14, _ = gate_deconv(x13,[self.batch_size, s_h, s_w, 3], name='deconv7') 81 | x14 = tf.concat([x_now,x14],axis=3) 82 | x14, mask14 = gate_conv(x14,3,3,1,activation=None,use_lrn=False,name='gconv14') 83 | 84 | output = tf.tanh(x14) 85 | 86 | return output, mask14 87 | 88 | def build_demo_graph(self, config): 89 | incom_imgs = self.images*(1-self.masks) 90 | batch_data = tf.concat([incom_imgs,self.sketches,\ 91 | self.color,self.masks,self.noises],axis=3) 92 | gen_img, output_mask = self.build_gen(batch_data,self.masks) 93 | self.demo_output= gen_img*self.masks + incom_imgs 94 | 95 | def load_demo_graph(self, config): 96 | sess_config = tf.ConfigProto() 97 | sess_config.gpu_options.allow_growth = True 98 | self.sess = tf.Session(config=sess_config) 99 | self.build_demo_graph(config) 100 | init_op = tf.global_variables_initializer() 101 | self.sess.run(init_op) 102 | vars_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) 103 | assign_ops = [] 104 | ckpt_path = config.CKPT_DIR 105 | if ckpt_path: 106 | print('Model loaded from {}....start'.format(ckpt_path)) 107 | for var in vars_list: 108 | vname = var.name 109 | from_name = vname 110 | # print(from_name) 111 | var_value = tf.contrib.framework.load_variable(ckpt_path, from_name) 112 | # self.sess.run(tf.assign(var, var_value)) 113 | assign_ops.append(tf.assign(var, var_value)) 114 | self.sess.run(assign_ops) 115 | self.warmup(config) 116 | print('Model loaded from {}....end'.format(ckpt_path)) 117 | else: 118 | print('Model loading is fail') 119 | 120 | def warmup(self,config): 121 | size = config.INPUT_SIZE 122 | bc = config.BATCH_SIZE 123 | _ = self.sess.run(self.demo_output, 124 | feed_dict={ 125 | self.images: np.zeros([bc,size,size,3]), 126 | self.sketches: np.zeros([bc,size,size,1]), 127 | self.color: np.zeros([bc,size,size,3]), 128 | self.masks: np.zeros([bc,size,size,1]), 129 | self.noises: np.zeros([bc,size,size,1])}) 130 | 131 | def demo(self, config, batch): 132 | demo_output = self.sess.run(self.demo_output, 133 | feed_dict={ 134 | self.images: batch[:,:,:,:3], 135 | self.sketches: batch[:,:,:,3:4], 136 | self.color: batch[:,:,:,4:7], 137 | self.masks: batch[:,:,:,7:8], 138 | self.noises: batch[:,:,:,8:9]}) 139 | return demo_output 140 | 141 | -------------------------------------------------------------------------------- /ops.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import tensorflow as tf 4 | from tensorflow.contrib.framework.python.ops import add_arg_scope 5 | 6 | # The gate convolution is made with reference to Deepfillv1(https://github.com/JiahuiYu/generative_inpainting) 7 | 8 | @add_arg_scope 9 | def gate_conv(x_in, cnum, ksize, stride=1, rate=1, name='conv', 10 | padding='SAME', activation='leaky_relu', use_lrn=True,training=True): 11 | assert padding in ['SYMMETRIC', 'SAME', 'REFELECT'] 12 | if padding == 'SYMMETRIC' or padding == 'REFELECT': 13 | p = int(rate*(ksize-1)/2) 14 | x = tf.pad(x_in, [[0,0], [p, p], [p, p], [0,0]], mode=padding) 15 | padding = 'VALID' 16 | x = tf.layers.conv2d( 17 | x_in, cnum, ksize, stride, dilation_rate=rate, 18 | activation=None, padding=padding, name=name) 19 | if use_lrn: 20 | x = tf.nn.lrn(x, bias=0.00005) 21 | if activation=='leaky_relu': 22 | x = tf.nn.leaky_relu(x) 23 | 24 | g = tf.layers.conv2d( 25 | x_in, cnum, ksize, stride, dilation_rate=rate, 26 | activation=tf.nn.sigmoid, padding=padding, name=name+'_g') 27 | 28 | x = tf.multiply(x,g) 29 | return x, g 30 | 31 | @add_arg_scope 32 | def gate_deconv(input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, 33 | name="deconv", training=True): 34 | with tf.variable_scope(name): 35 | # filter : [height, width, output_channels, in_channels] 36 | w = tf.get_variable('w', [k_h, k_w, output_shape[-1], input_.get_shape()[-1]], 37 | initializer=tf.random_normal_initializer(stddev=stddev)) 38 | 39 | deconv = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape, 40 | strides=[1, d_h, d_w, 1]) 41 | 42 | biases = tf.get_variable('biases1', [output_shape[-1]], initializer=tf.constant_initializer(0.0)) 43 | deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape()) 44 | deconv = tf.nn.leaky_relu(deconv) 45 | 46 | g = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape, 47 | strides=[1, d_h, d_w, 1]) 48 | b = tf.get_variable('biases2', [output_shape[-1]], initializer=tf.constant_initializer(0.0)) 49 | g = tf.reshape(tf.nn.bias_add(g, b), deconv.get_shape()) 50 | g = tf.nn.sigmoid(deconv) 51 | 52 | deconv = tf.multiply(g,deconv) 53 | 54 | return deconv, g 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | absl-py==0.7.0 2 | astor==0.7.1 3 | gast==0.2.2 4 | grpcio==1.18.0 5 | h5py==2.9.0 6 | Keras-Applications==1.0.7 7 | Keras-Preprocessing==1.0.9 8 | Markdown==3.0.1 9 | mock==2.0.0 10 | numpy==1.16.1 11 | opencv-python==4.0.0.21 12 | pbr==5.1.2 13 | protobuf==3.6.1 14 | PyQt5==5.12 15 | PyQt5-sip==4.19.14 16 | pyyaml>=4.2b1 17 | six==1.12.0 18 | tensorboard==1.12.2 19 | tensorflow==1.13.0rc2 20 | -------------------------------------------------------------------------------- /samples/00001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/samples/00001.png -------------------------------------------------------------------------------- /samples/00011.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/samples/00011.png -------------------------------------------------------------------------------- /samples/00018.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/samples/00018.png -------------------------------------------------------------------------------- /samples/00221.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/samples/00221.png -------------------------------------------------------------------------------- /samples/00225.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/run-youngjoo/SC-FEGAN/1f9d47f9516f6121dc7da37aa2ffbc3013f67195/samples/00225.png -------------------------------------------------------------------------------- /ui/mouse_event.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from PyQt5.QtCore import * 4 | from PyQt5.QtGui import * 5 | from PyQt5.QtWidgets import * 6 | import numpy as np 7 | 8 | class GraphicsScene(QGraphicsScene): 9 | def __init__(self, mode_list, parent=None): 10 | QGraphicsScene.__init__(self, parent) 11 | self.modes = mode_list 12 | self.mouse_clicked = False 13 | self.prev_pt = None 14 | 15 | # self.masked_image = None 16 | 17 | # save the points 18 | self.mask_points = [] 19 | self.sketch_points = [] 20 | self.stroke_points = [] 21 | 22 | # save the history of edit 23 | self.history = [] 24 | 25 | # strokes color 26 | self.stk_color = None 27 | 28 | def reset(self): 29 | # save the points 30 | self.mask_points = [] 31 | self.sketch_points = [] 32 | self.stroke_points = [] 33 | 34 | # save the history of edit 35 | self.history = [] 36 | 37 | # strokes color 38 | self.stk_color = None 39 | 40 | self.prev_pt = None 41 | 42 | def mousePressEvent(self, event): 43 | self.mouse_clicked = True 44 | 45 | def mouseReleaseEvent(self, event): 46 | self.prev_pt = None 47 | self.mouse_clicked = False 48 | 49 | def mouseMoveEvent(self, event): 50 | if self.mouse_clicked: 51 | if self.modes[0] == 1: 52 | if self.prev_pt: 53 | self.drawMask(self.prev_pt, event.scenePos()) 54 | pts = {} 55 | pts['prev'] = (int(self.prev_pt.x()),int(self.prev_pt.y())) 56 | pts['curr'] = (int(event.scenePos().x()),int(event.scenePos().y())) 57 | self.mask_points.append(pts) 58 | self.history.append(0) 59 | self.prev_pt = event.scenePos() 60 | else: 61 | self.prev_pt = event.scenePos() 62 | elif self.modes[1] == 1: 63 | if self.prev_pt: 64 | self.drawSketch(self.prev_pt, event.scenePos()) 65 | pts = {} 66 | pts['prev'] = (int(self.prev_pt.x()),int(self.prev_pt.y())) 67 | pts['curr'] = (int(event.scenePos().x()),int(event.scenePos().y())) 68 | self.sketch_points.append(pts) 69 | self.history.append(1) 70 | self.prev_pt = event.scenePos() 71 | else: 72 | self.prev_pt = event.scenePos() 73 | elif self.modes[2] == 1: 74 | if self.prev_pt: 75 | self.drawStroke(self.prev_pt, event.scenePos()) 76 | pts = {} 77 | pts['prev'] = (int(self.prev_pt.x()),int(self.prev_pt.y())) 78 | pts['curr'] = (int(event.scenePos().x()),int(event.scenePos().y())) 79 | pts['color'] = self.stk_color 80 | self.stroke_points.append(pts) 81 | self.history.append(2) 82 | self.prev_pt = event.scenePos() 83 | else: 84 | self.prev_pt = event.scenePos() 85 | 86 | def drawMask(self, prev_pt, curr_pt): 87 | lineItem = QGraphicsLineItem(QLineF(prev_pt, curr_pt)) 88 | lineItem.setPen(QPen(Qt.white, 12, Qt.SolidLine)) # rect 89 | self.addItem(lineItem) 90 | 91 | def drawSketch(self, prev_pt, curr_pt): 92 | lineItem = QGraphicsLineItem(QLineF(prev_pt, curr_pt)) 93 | lineItem.setPen(QPen(Qt.black, 1, Qt.SolidLine)) # rect 94 | self.addItem(lineItem) 95 | 96 | def drawStroke(self, prev_pt, curr_pt): 97 | lineItem = QGraphicsLineItem(QLineF(prev_pt, curr_pt)) 98 | lineItem.setPen(QPen(QColor(self.stk_color), 4, Qt.SolidLine)) # rect 99 | self.addItem(lineItem) 100 | 101 | def get_stk_color(self, color): 102 | self.stk_color = color 103 | 104 | def erase_prev_pt(self): 105 | self.prev_pt = None 106 | 107 | def reset_items(self): 108 | for i in range(len(self.items())): 109 | item = self.items()[0] 110 | self.removeItem(item) 111 | 112 | def undo(self): 113 | if len(self.items())>1: 114 | if len(self.items())>=9: 115 | for i in range(8): 116 | item = self.items()[0] 117 | self.removeItem(item) 118 | if self.history[-1] == 0: 119 | self.mask_points.pop() 120 | self.history.pop() 121 | elif self.history[-1] == 1: 122 | self.sketch_points.pop() 123 | self.history.pop() 124 | elif self.history[-1] == 2: 125 | self.stroke_points.pop() 126 | self.history.pop() 127 | elif self.history[-1] == 3: 128 | self.history.pop() 129 | else: 130 | for i in range(len(self.items())-1): 131 | item = self.items()[0] 132 | self.removeItem(item) 133 | if self.history[-1] == 0: 134 | self.mask_points.pop() 135 | self.history.pop() 136 | elif self.history[-1] == 1: 137 | self.sketch_points.pop() 138 | self.history.pop() 139 | elif self.history[-1] == 2: 140 | self.stroke_points.pop() 141 | self.history.pop() 142 | elif self.history[-1] == 3: 143 | self.history.pop() 144 | -------------------------------------------------------------------------------- /ui/ui.py: -------------------------------------------------------------------------------- 1 | from PyQt5 import QtCore, QtGui, QtWidgets 2 | 3 | class Ui_Form(object): 4 | def setupUi(self, Form): 5 | Form.setObjectName("Form") 6 | Form.resize(1200, 660) 7 | self.pushButton = QtWidgets.QPushButton(Form) 8 | self.pushButton.setGeometry(QtCore.QRect(10, 10, 97, 27)) 9 | self.pushButton.setObjectName("pushButton") 10 | self.pushButton_2 = QtWidgets.QPushButton(Form) 11 | self.pushButton_2.setGeometry(QtCore.QRect(130, 10, 97, 27)) 12 | self.pushButton_2.setObjectName("pushButton_2") 13 | self.pushButton_3 = QtWidgets.QPushButton(Form) 14 | self.pushButton_3.setGeometry(QtCore.QRect(250, 10, 97, 27)) 15 | self.pushButton_3.setObjectName("pushButton_3") 16 | self.pushButton_4 = QtWidgets.QPushButton(Form) 17 | self.pushButton_4.setGeometry(QtCore.QRect(370, 10, 97, 27)) 18 | self.pushButton_4.setObjectName("pushButton_4") 19 | self.pushButton_5 = QtWidgets.QPushButton(Form) 20 | self.pushButton_5.setGeometry(QtCore.QRect(560, 360, 81, 27)) 21 | self.pushButton_5.setObjectName("pushButton_5") 22 | self.pushButton_6 = QtWidgets.QPushButton(Form) 23 | self.pushButton_6.setGeometry(QtCore.QRect(490, 40, 97, 27)) 24 | self.pushButton_6.setObjectName("pushButton_6") 25 | self.pushButton_7 = QtWidgets.QPushButton(Form) 26 | self.pushButton_7.setGeometry(QtCore.QRect(490, 10, 97, 27)) 27 | self.pushButton_7.setObjectName("pushButton_7") 28 | self.pushButton_8 = QtWidgets.QPushButton(Form) 29 | self.pushButton_8.setGeometry(QtCore.QRect(370, 40, 97, 27)) 30 | self.pushButton_8.setObjectName("pushButton_8") 31 | self.graphicsView = QtWidgets.QGraphicsView(Form) 32 | self.graphicsView.setGeometry(QtCore.QRect(20, 120, 512, 512)) 33 | self.graphicsView.setObjectName("graphicsView") 34 | self.graphicsView_2 = QtWidgets.QGraphicsView(Form) 35 | self.graphicsView_2.setGeometry(QtCore.QRect(660, 120, 512, 512)) 36 | self.graphicsView_2.setObjectName("graphicsView_2") 37 | 38 | self.saveImg = QtWidgets.QPushButton(Form) 39 | self.saveImg.setGeometry(QtCore.QRect(610, 10, 97, 27)) 40 | self.saveImg.setObjectName("saveImg") 41 | 42 | self.arrangement = QtWidgets.QPushButton(Form) 43 | self.arrangement.setGeometry(QtCore.QRect(610, 40, 97, 27)) 44 | self.arrangement.setObjectName("arrangement") 45 | 46 | self.retranslateUi(Form) 47 | self.pushButton.clicked.connect(Form.open) 48 | self.pushButton_2.clicked.connect(Form.mask_mode) 49 | self.pushButton_3.clicked.connect(Form.sketch_mode) 50 | self.pushButton_4.clicked.connect(Form.stroke_mode) 51 | self.pushButton_5.clicked.connect(Form.complete) 52 | self.pushButton_6.clicked.connect(Form.undo) 53 | self.pushButton_7.clicked.connect(Form.color_change_mode) 54 | self.pushButton_8.clicked.connect(Form.clear) 55 | 56 | self.saveImg.clicked.connect(Form.save_img) 57 | 58 | self.arrangement.clicked.connect(Form.arrange) 59 | 60 | QtCore.QMetaObject.connectSlotsByName(Form) 61 | 62 | def retranslateUi(self, Form): 63 | _translate = QtCore.QCoreApplication.translate 64 | Form.setWindowTitle(_translate("Form", "SC-FEGAN")) 65 | self.pushButton.setText(_translate("Form", "Open Image")) 66 | self.pushButton_2.setText(_translate("Form", "Mask")) 67 | self.pushButton_3.setText(_translate("Form", "Sketches")) 68 | self.pushButton_4.setText(_translate("Form", "Color")) 69 | self.pushButton_5.setText(_translate("Form", "Complete")) 70 | self.pushButton_6.setText(_translate("Form", "Undo")) 71 | self.pushButton_7.setText(_translate("Form", "Palette")) 72 | self.pushButton_8.setText(_translate("Form", "Clear")) 73 | 74 | self.saveImg.setText(_translate("Form", "Save Img")) 75 | 76 | self.arrangement.setText(_translate("Form", "Arrange")) 77 | 78 | 79 | if __name__ == "__main__": 80 | import sys 81 | app = QtWidgets.QApplication(sys.argv) 82 | Form = QtWidgets.QWidget() 83 | ui = Ui_Form() 84 | ui.setupUi(Form) 85 | Form.show() 86 | sys.exit(app.exec_()) 87 | -------------------------------------------------------------------------------- /utils/config.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import yaml 3 | import os 4 | import logging 5 | 6 | logger = logging.getLogger() 7 | 8 | class Config(object): 9 | def __init__(self, filename=None): 10 | assert os.path.exists(filename), "ERROR: Config File doesn't exist." 11 | try: 12 | with open(filename, 'r') as f: 13 | self._cfg_dict = yaml.load(f) 14 | # parent of IOError, OSError *and* WindowsError where available 15 | except EnvironmentError: 16 | logger.error('Please check the file with name of "%s"', filename) 17 | logger.info(' APP CONFIG '.center(80, '-')) 18 | logger.info(''.center(80, '-')) 19 | 20 | def __getattr__(self, name): 21 | value = self._cfg_dict[name] 22 | if isinstance(value, dict): 23 | value = DictAsMember(value) 24 | return value --------------------------------------------------------------------------------