├── GANnotation.py ├── LICENSE ├── README.md ├── demo_gannotation.py ├── model.py ├── test_images ├── test_1.jpg └── test_1.txt ├── training ├── GANnotation.py ├── LICENSE ├── README.md ├── Train_options.py ├── databases.py ├── model_GAN.py ├── train.py └── utils.py └── utils.py /GANnotation.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import torch 3 | import numpy as np 4 | import scipy.io as sio 5 | import os 6 | from model import Generator 7 | import utils 8 | 9 | class GANnotation: 10 | 11 | def __init__(self, path_to_model='',enable_cuda=True, train=False): 12 | self.GEN = Generator() 13 | self.enable_cuda = enable_cuda 14 | self.size = 128 15 | self.tight = 16 16 | net_weigths = torch.load(path_to_model,map_location=lambda storage, loc: storage) 17 | net_dict = {k.replace('module.',''): v for k, v in net_weigths['state_dict'].items()} 18 | self.GEN.load_state_dict(net_dict) 19 | if self.enable_cuda: 20 | self.GEN = self.GEN.cuda() 21 | self.GEN.eval() 22 | 23 | 24 | def reenactment(self,image,videocoords): 25 | #image, points = utils.process_image(image,coords,angle=0, flip=False, sigma=1,size=128, tight=16) # do this outside 26 | frame_w = int(np.floor(2*videocoords.max())) 27 | frame = np.zeros((frame_w,frame_w,3)) 28 | if videocoords.ndim == 2: 29 | videocoords = videocoords.reshape((66,2,1)) 30 | n_frames = videocoords.shape[2] 31 | cropped_points = np.zeros((66,2,n_frames)) 32 | images = [] 33 | for i in range(0,n_frames): 34 | print(i) 35 | if videocoords[0,0,i] > 0: 36 | target = videocoords[:,:,i] 37 | _, target = utils.crop( frame , target, size=128, tight=16 ) 38 | cropped_points[:,:,i] = target 39 | A_to_B = utils.generate_Ginput(image,target,sigma=1,size=128).unsqueeze(0) 40 | if self.enable_cuda: 41 | A_to_B = A_to_B.cuda() 42 | generated = 0.5*(self.GEN(torch.autograd.Variable(A_to_B)).data[0,:,:,:].cpu().numpy().swapaxes(0,1).swapaxes(1,2) + 1) 43 | imout = (255*generated).astype('uint8') 44 | images.append(imout) 45 | return images, cropped_points 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | ## Copyright © 2019. All Rights Reserved. 2 | 3 | Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. 4 | 5 | ## Attribution-NonCommercial 4.0 International 6 | 7 | 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. 8 | 9 | ### Using Creative Commons Public Licenses 10 | 11 | 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. 12 | 13 | * __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). 14 | 15 | * __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). 16 | 17 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License 18 | 19 | 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. 20 | 21 | ### Section 1 – Definitions. 22 | 23 | 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. 24 | 25 | 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. 26 | 27 | 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. 28 | 29 | 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. 30 | 31 | 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. 32 | 33 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 34 | 35 | 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. 36 | 37 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 38 | 39 | 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. 40 | 41 | 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. 42 | 43 | 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. 44 | 45 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 46 | 47 | ### Section 2 – Scope. 48 | 49 | a. ___License grant.___ 50 | 51 | 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: 52 | 53 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 54 | 55 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 56 | 57 | 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. 58 | 59 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 60 | 61 | 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. 62 | 63 | 5. __Downstream recipients.__ 64 | 65 | 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. 66 | 67 | 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. 68 | 69 | 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). 70 | 71 | b. ___Other rights.___ 72 | 73 | 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. 74 | 75 | 2. Patent and trademark rights are not licensed under this Public License. 76 | 77 | 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. 78 | 79 | ### Section 3 – License Conditions. 80 | 81 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 82 | 83 | a. ___Attribution.___ 84 | 85 | 1. If You Share the Licensed Material (including in modified form), You must: 86 | 87 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 88 | 89 | 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); 90 | 91 | ii. a copyright notice; 92 | 93 | iii. a notice that refers to this Public License; 94 | 95 | iv. a notice that refers to the disclaimer of warranties; 96 | 97 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 98 | 99 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 100 | 101 | 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. 102 | 103 | 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. 104 | 105 | 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. 106 | 107 | 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. 108 | 109 | ### Section 4 – Sui Generis Database Rights. 110 | 111 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 112 | 113 | 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; 114 | 115 | 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 116 | 117 | 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. 118 | 119 | 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. 120 | 121 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 122 | 123 | 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.__ 124 | 125 | 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.__ 126 | 127 | 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. 128 | 129 | ### Section 6 – Term and Termination. 130 | 131 | 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. 132 | 133 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 134 | 135 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 136 | 137 | 2. upon express reinstatement by the Licensor. 138 | 139 | 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. 140 | 141 | 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. 142 | 143 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 144 | 145 | ### Section 7 – Other Terms and Conditions. 146 | 147 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 148 | 149 | 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. 150 | 151 | ### Section 8 – Interpretation. 152 | 153 | 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. 154 | 155 | 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. 156 | 157 | 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. 158 | 159 | 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. 160 | 161 | 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. 162 | 163 | Creative Commons may be contacted at creativecommons.org 164 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GANnotation 2 | ## Face to face synthesis using Generative Adversarial Networks ([model](https://drive.google.com/open?id=1YhpFXME3pnwy_WhgBtyhGhI1Y9WYYEOz)) ([paper](https://arxiv.org/pdf/1811.03492.pdf)) 3 | 4 | GANnotation example 7 | 8 | This is the PyTorch repository for the GANnotation implementation. GANnotation is a landmark-guided face to face synthesis network that incorporates a triple consistency loss to bridge the gap between the input and target distributions 9 | 10 | Release v1 (Nov. 2018): Demo showing the performance of our GANnotation 11 | 12 | Release v2 (Nov. 2019): Training script is already available 13 | 14 | Paper has been accepted to FG'2020 as an Oral presentation, see citation below. 15 | 16 | NOTE: The re-training of the StarGAN using the triple consistency loss can be found [here](https://github.com/ESanchezLozano/stargan) 17 | 18 | 19 | ## License 20 | 21 | Copyright © 2019. All Rights Reserved. 22 | 23 | Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. 24 | 25 | All the material, including source code, is made freely available for non-commercial use under the Creative Commons CC BY-NC 4.0 license. Feel free to use any of the material in your own work, as long as you give us appropriate credit by mentioning the title and author list of our paper. 26 | 27 | All the third-party libraries (Python, PyTorch, Torchvision, Numpy, OpenCV, Visdom, Torchnet, GPUtil and SciPy) are owned by their respective authors, and must be used according to their respective licenses. 28 | 29 | ## Requirements 30 | * Linux 31 | * Python 3.6 or further 32 | * PyTorch 1.X with torchvision 33 | * Numpy 34 | * OpenCV (cv2) 35 | 36 | For visualization, the code above uses [Visdom](https://github.com/facebookresearch/visdom), through its wrapper [TorchNet](https://github.com/pytorch/tnt). You can alternatively disable the visualization by setting --visdom False when running the code. No source code would be needed in that case. 37 | 38 | This code assigns a CUDA device directly based on availability, with [GPUtil](https://github.com/anderskm/gputil). This option can be disabled by setting --cuda to the target GPU device. Again, no need to have GPUtil installed in such case. 39 | 40 | ## Test 41 | 42 | The model can be downloaded from [https://drive.google.com/open?id=1YhpFXME3pnwy_WhgBtyhGhI1Y9WYYEOz] 43 | 44 | Please, see the demo_gannotation.py file for usage 45 | 46 | 47 | ## Contributions 48 | 49 | All contributions are welcome 50 | 51 | ## Citation 52 | 53 | Should you use this code or the ideas from the paper, please cite the following paper: 54 | 55 | ``` 56 | @inproceedings{Sanchez2020Gannotation, 57 | title={A recurrent cycle consistency loss for progressive face-to-face synthesis}, 58 | author={Enrique Sanchez and Michel Valstar}, 59 | booktitle={IEEE Int'l Conf. on Automatic Face and Gesture Recognition (FG)}, 60 | year={2020} 61 | } 62 | ``` 63 | -------------------------------------------------------------------------------- /demo_gannotation.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import GANnotation 3 | import matplotlib.pyplot as plt 4 | import utils 5 | import cv2 6 | import torch 7 | myGAN = GANnotation.GANnotation(path_to_model='myGEN.pth') 8 | points = np.loadtxt('test_images/test_1.txt').transpose().reshape(66,2,-1) 9 | 10 | image = cv2.cvtColor(cv2.imread('test_images/test_1.jpg'),cv2.COLOR_BGR2RGB) 11 | image = image/255.0 12 | image = torch.from_numpy(image.swapaxes(2,1).swapaxes(1,0)) 13 | image = image.type_as(torch.FloatTensor()) 14 | 15 | images, cropped_pts = myGAN.reenactment(image,points) 16 | 17 | fourcc = cv2.VideoWriter_fourcc(*'XVID') 18 | out = cv2.VideoWriter('test_1.avi',fourcc, 30.0, (128,128)) 19 | for imout in images: 20 | out.write(cv2.cvtColor(imout, cv2.COLOR_RGB2BGR)) 21 | 22 | out.release() 23 | np.savetxt('test_1_cropped.txt', cropped_pts.reshape((132,-1)).transpose()) 24 | -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.init as weight_init 4 | import csv 5 | import math 6 | import torch.nn.functional as F 7 | import functools 8 | 9 | def init_weights(net, init_type='normal', gain=0.02): 10 | def init_func(m): 11 | classname = m.__class__.__name__ 12 | if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1): 13 | if init_type == 'normal': 14 | weight_init.normal_(m.weight.data, 0.0, gain) 15 | elif init_type == 'xavier': 16 | weight_init.xavier_normal_(m.weight.data, gain=gain) 17 | elif init_type == 'kaiming': 18 | weight_init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') 19 | elif init_type == 'orthogonal': 20 | weight_init.orthogonal_(m.weight.data, gain=gain) 21 | else: 22 | raise NotImplementedError('initialization method [%s] is not implemented' % init_type) 23 | if hasattr(m, 'bias') and m.bias is not None: 24 | weight_init.constant_(m.bias.data, 0.0) 25 | elif classname.find('BatchNorm2d') != -1: 26 | weight_init.normal_(m.weight.data, 1.0, gain) 27 | weight_init.constant_(m.bias.data, 0.0) 28 | 29 | print('initialize network with %s' % init_type) 30 | net.apply(init_func) 31 | 32 | 33 | def downsample_block(input_channels=64, output_channels=128, norm_layer=nn.BatchNorm2d): 34 | # This block applies a downsample of factor = 4 in the scale (x,y) 35 | block = [nn.Conv2d( input_channels, output_channels, kernel_size=4, stride=2, padding=1)] 36 | block += [norm_layer(output_channels)] 37 | block += [nn.LeakyReLU(0.2)] 38 | return block 39 | 40 | 41 | 42 | class BasicBlock(nn.Module): 43 | expansion = 1 44 | 45 | def __init__(self, inplanes, planes, stride=1): 46 | super(BasicBlock, self).__init__() 47 | self.reflection1 = nn.ReflectionPad2d(1) 48 | self.conv1 = nn.Conv2d(inplanes,planes,kernel_size=3,stride=1,padding=0) 49 | self.bn1 = nn.BatchNorm2d(planes) 50 | self.relu = nn.LeakyReLU(0.2,inplace=True) 51 | self.reflection2 = nn.ReflectionPad2d(1) 52 | self.conv2 = nn.Conv2d(inplanes,planes,kernel_size=3,stride=1,padding=0) 53 | self.bn2 = nn.BatchNorm2d(planes) 54 | self.stride = stride 55 | 56 | def forward(self, x): 57 | residual = x 58 | 59 | out = self.reflection1(x) 60 | out = self.conv1(x) 61 | out = self.bn1(out) 62 | out = self.relu(out) 63 | out = self.reflection2(x) 64 | out = self.conv2(out) 65 | out = self.bn2(out) 66 | out = x + residual 67 | return out 68 | 69 | class ResidualBlock(nn.Module): 70 | def __init__(self, channels, norm_layer=nn.InstanceNorm2d ): 71 | super(ResidualBlock, self).__init__() 72 | self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1) 73 | self.bn1 = norm_layer(channels) 74 | self.prelu = nn.LeakyReLU(0.2,inplace=True) #parametric ReLU 75 | self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1) 76 | self.bn2 = norm_layer(channels) 77 | 78 | def forward(self, x): 79 | residual = self.conv1(x) 80 | residual = self.bn1(residual) 81 | residual = self.prelu(residual) 82 | residual = self.conv2(residual) 83 | residual = self.bn2(residual) 84 | 85 | return x + residual 86 | 87 | 88 | class Generator(nn.Module): 89 | def __init__(self, conv_dim=64, c_dim=66, repeat_num=6): 90 | super(Generator, self).__init__() 91 | initial_layer = [nn.Conv2d(3+c_dim, conv_dim, kernel_size=7, stride=1,padding=3, bias=False)] 92 | initial_layer += [nn.InstanceNorm2d(conv_dim, affine=True)] 93 | initial_layer += [nn.LeakyReLU(0.2, inplace=True)] 94 | 95 | curr_dim = conv_dim 96 | for i in range(2): 97 | initial_layer += [nn.Conv2d(curr_dim, curr_dim*2, kernel_size=4, stride=2, padding=1, bias=False)] 98 | initial_layer += [nn.InstanceNorm2d(curr_dim*2, affine=True)] 99 | initial_layer += [nn.LeakyReLU(0.2, inplace=True)] 100 | curr_dim = curr_dim * 2 101 | 102 | self.down_conv = nn.Sequential(*initial_layer) 103 | 104 | bottleneck = [] 105 | for i in range(repeat_num): 106 | bottleneck += [ResidualBlock(curr_dim)] 107 | 108 | self.bottleneck = nn.Sequential(*bottleneck) 109 | 110 | features = [] 111 | for i in range(2): 112 | features += [nn.ConvTranspose2d(curr_dim, curr_dim//2, kernel_size=4, stride=2, padding=1, bias=False)] 113 | features += [nn.InstanceNorm2d(curr_dim//2, affine=True)] 114 | features += [nn.LeakyReLU(0.2,inplace=True)] 115 | curr_dim = curr_dim // 2 116 | 117 | self.feature_layer = nn.Sequential(*features) 118 | 119 | colour = [nn.Conv2d(curr_dim, 3, kernel_size=7, stride=1, padding=3, bias=False)] 120 | colour += [nn.Tanh()] 121 | self.colour_layer = nn.Sequential(*colour) 122 | 123 | mask = [nn.Conv2d(curr_dim, 1, kernel_size=7, stride=1, padding=3, bias=False)] 124 | mask += [nn.Sigmoid()] 125 | self.mask_layer = nn.Sequential(*mask) 126 | init_weights(self) 127 | 128 | def forward( self, x ): 129 | down = self.down_conv(x) 130 | bottle = self.bottleneck(down) 131 | features = self.feature_layer(bottle) 132 | col = self.colour_layer(features) 133 | mask = self.mask_layer(features) 134 | output = mask * ( x[:,0:3,:,:] - col ) + col 135 | return output 136 | 137 | 138 | -------------------------------------------------------------------------------- /test_images/test_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ESanchezLozano/GANnotation/c2a7c171406d4b866f61f804a7cb8ef4120c91e8/test_images/test_1.jpg -------------------------------------------------------------------------------- /training/GANnotation.py: -------------------------------------------------------------------------------- 1 | import glob, os, sys, csv, math, functools, collections, numpy as np, torch, torch.nn as nn 2 | import torch.nn.functional as F 3 | from torchvision.models.vgg import vgg16 4 | from utils import LossNetwork, init_weights 5 | from model_GAN import Generator, Discriminator 6 | import itertools 7 | from torch.autograd import Variable 8 | 9 | def _gradient_penalty_D(D, real_img, fake_img, maps=None): 10 | alpha = torch.rand(real_img.size(0),1,1,1).cuda().expand_as(real_img) 11 | interpolated = alpha * real_img + (1 - alpha) * fake_img 12 | interpolated.required_grad = True 13 | if maps is not None: 14 | interpolated_prob,_ = D(torch.cat((interpolated,maps),1)) 15 | else: 16 | interpolated_prob = D(interpolated) 17 | 18 | grad = torch.autograd.grad(outputs=interpolated_prob, 19 | inputs=interpolated, 20 | grad_outputs=torch.ones(interpolated_prob.size()).cuda(), 21 | retain_graph=True, 22 | create_graph=True, 23 | only_inputs=True)[0] 24 | 25 | grad = grad.view(grad.size(0),-1) 26 | grad_l2norm = torch.sqrt(torch.sum(grad ** 2, dim=1)) 27 | loss_d_gp = torch.mean((grad_l2norm-1)**2) 28 | return loss_d_gp 29 | 30 | def TVLoss(x): 31 | batch_size = x.size()[0] 32 | h_x = x.size()[2] 33 | w_x = x.size()[3] 34 | count_h = torch.numel(x[:,:,1:,:]) 35 | count_w = torch.numel(x[:,:,:,1:]) 36 | h_tv = torch.pow((x[:,:,1:,:] - x[:,:, :h_x -1,:]),2).sum() 37 | w_tv = torch.pow((x[:,:,:,1:] - x[:,:,:, :w_x -1]),2).sum() 38 | return 2 * (h_tv / count_h + w_tv / count_w) / batch_size 39 | 40 | 41 | 42 | 43 | class GANnotation(): 44 | 45 | def __init__(self, 46 | losses = dict(adv=1, rec=100, self=100, triple=100, tv=1e-5, percep=0), 47 | gradclip=0, gantype='wgan-gp', edge=False 48 | ): 49 | 50 | self.npoints = 68 51 | self.gradclip = gradclip 52 | self.l = losses 53 | 54 | # - define models 55 | self.DIS = Discriminator(ndim=0) 56 | self.GEN = Generator(conv_dim=64, c_dim=self.npoints if not edge else 3) 57 | init_weights(self.DIS) 58 | init_weights(self.GEN) 59 | if torch.cuda.device_count() > 1: 60 | self.GEN = torch.nn.DataParallel(self.GEN) 61 | self.DIS = torch.nn.DataParallel(self.DIS) 62 | 63 | self.DIS.to('cuda').train() 64 | self.GEN.to('cuda').train() 65 | 66 | if self.l['percep'] > 0: 67 | # - VGG for perceptual loss 68 | self.loss_network = LossNetwork(torch.nn.DataParallel(vgg16(pretrained=True))) if torch.cuda.device_count() > 1 else LossNetwork(vgg16(pretrained=True)) 69 | self.loss_network.eval() 70 | self.loss_network.to('cuda') 71 | 72 | self.TripleLoss = (lambda x,y : torch.mean(torch.abs(x-y))) if self.l['triple'] > 0 else None 73 | self.SelfLoss = torch.nn.L1Loss().to('cuda') if self.l['self'] > 0 else None 74 | self.RecLoss = torch.nn.L1Loss().to('cuda') if self.l['rec'] > 0 else None 75 | self.PercepLoss = torch.nn.MSELoss().to('cuda') if self.l['percep'] > 0 else None 76 | self.TVLoss = TVLoss if self.l['tv'] > 0 else None 77 | self.gantype = gantype 78 | self.loss = dict(G=dict.fromkeys(['adv','self','triple','percep','rec','tv','all']), D=dict.fromkeys(['real','fake','gp','all'])) 79 | 80 | 81 | def _advloss_D(self, score, real=True): 82 | if self.gantype == 'wgan-gp': 83 | return -torch.mean(score) if real else torch.mean(score) 84 | elif self.gantype == 'hinge': 85 | return torch.mean(torch.nn.ReLU()(1.0 - score)) if real else torch.mean(torch.nn.ReLU()(1.0 + score)) 86 | 87 | def _pp_loss(self,fake_im,real_im): 88 | vgg_fake = self.loss_network(fake_im) 89 | vgg_target = self.loss_network(real_im) 90 | perceptualLoss = 0 91 | for vgg_idx in range(0,4): 92 | perceptualLoss += self.PercepLoss(vgg_fake[vgg_idx], vgg_target[vgg_idx].detach()) 93 | return perceptualLoss 94 | 95 | def _resume(self,path_fan, path_gen): 96 | self.DIS.load_state_dict(torch.load(path_dis)) 97 | self.GEN.load_state_dict(torch.load(path_gen)) 98 | 99 | def _save(self, path_to_models, epoch): 100 | torch.save(self.DIS.state_dict(), path_to_models + str(epoch) + '.dis.pth') 101 | torch.save(self.GEN.state_dict(), path_to_models + str(epoch) + '.gen.pth') 102 | 103 | def __call__(self, A, HB): 104 | return self.GEN(A,HB) 105 | 106 | def _forward_D(self, data): 107 | # - reset losses 108 | for p in self.DIS.parameters(): 109 | p.requires_grad = True 110 | self.loss['D'].update( dict.fromkeys(self.loss['D'].keys(), None)) 111 | self.DIS.zero_grad() 112 | # - generate fake image A -> B 113 | AB = self.GEN(data['A_Im'], data['B_Hm']).detach() 114 | AB.requires_grad = True 115 | fakeAB = self.DIS(AB) 116 | realAB = self.DIS(data['B_Im']) 117 | self.loss['D']['real'] = self._advloss_D(realAB, True) 118 | self.loss['D']['fake'] = self._advloss_D(fakeAB, False) 119 | self.loss['D']['gp'] = 10*_gradient_penalty_D(self.DIS, data['B_Im'], AB, maps=None) if self.gantype =='wgan-gp' else None 120 | self.loss['D']['all'] = sum(filter(lambda x : x is not None, self.loss['D'].values())) 121 | self.loss['D']['all'].backward() 122 | if self.gradclip: 123 | torch.nn.utils.clip_grad_norm_(self.DIS.parameters(), 1, norm_type=2) 124 | 125 | def _forward_G(self, data): 126 | for p in self.DIS.parameters(): 127 | p.requires_grad = False 128 | 129 | # - reset losses 130 | self.loss['G'].update( dict.fromkeys(self.loss['G'].keys(), None)) 131 | self.GEN.zero_grad() 132 | 133 | # - adversarial loss 134 | AB = self.GEN(data['A_Im'], data['B_Hm']) 135 | pred_AB = self.DIS(AB) 136 | self.loss['G']['adv'] = -pred_AB.mean() * self.l['adv'] 137 | 138 | # - reconstruction loss 139 | self.loss['G']['rec'] = self.l['rec'] * self.RecLoss( AB, data['B_Im']) if self.RecLoss is not None else None 140 | 141 | # - self-consistency loss 142 | if self.SelfLoss is not None: 143 | ABA = self.GEN(AB, data['A_Hm']) 144 | self.loss['G']['self'] = self.l['self'] * self.SelfLoss(ABA, data['A_Im']) 145 | 146 | # - triple consistency loss 147 | if self.TripleLoss is not None: 148 | AC = self.GEN(data['A_Im'], data['C_Hm']) 149 | BC = self.GEN(AB, data['C_Hm']) 150 | self.loss['G']['triple'] = self.l['triple'] * self.TripleLoss(AC, BC) 151 | 152 | # - perceptual loss 153 | self.loss['G']['percep'] = self.l['percep'] * self._pp_loss(AB, data['B_Im']) if self.PercepLoss is not None else None 154 | 155 | # - total variation loss 156 | self.loss['G']['tv'] = self.l['tv'] * self.TVLoss(AB) if self.TVLoss is not None else None 157 | 158 | # - all losses and backward 159 | self.loss['G']['all'] = sum(filter(lambda x : x is not None, self.loss['G'].values())) 160 | self.loss['G']['all'].backward() 161 | if self.gradclip: 162 | torch.nn.utils.clip_grad_norm_(self.GEN.parameters(), 1, norm_type=2) 163 | 164 | return AB 165 | 166 | -------------------------------------------------------------------------------- /training/LICENSE: -------------------------------------------------------------------------------- 1 | ## Copyright © 2019. All Rights Reserved. 2 | 3 | Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. 4 | 5 | ## Attribution-NonCommercial 4.0 International 6 | 7 | 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. 8 | 9 | ### Using Creative Commons Public Licenses 10 | 11 | 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. 12 | 13 | * __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). 14 | 15 | * __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). 16 | 17 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License 18 | 19 | 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. 20 | 21 | ### Section 1 – Definitions. 22 | 23 | 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. 24 | 25 | 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. 26 | 27 | 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. 28 | 29 | 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. 30 | 31 | 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. 32 | 33 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 34 | 35 | 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. 36 | 37 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 38 | 39 | 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. 40 | 41 | 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. 42 | 43 | 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. 44 | 45 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 46 | 47 | ### Section 2 – Scope. 48 | 49 | a. ___License grant.___ 50 | 51 | 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: 52 | 53 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 54 | 55 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 56 | 57 | 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. 58 | 59 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 60 | 61 | 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. 62 | 63 | 5. __Downstream recipients.__ 64 | 65 | 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. 66 | 67 | 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. 68 | 69 | 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). 70 | 71 | b. ___Other rights.___ 72 | 73 | 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. 74 | 75 | 2. Patent and trademark rights are not licensed under this Public License. 76 | 77 | 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. 78 | 79 | ### Section 3 – License Conditions. 80 | 81 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 82 | 83 | a. ___Attribution.___ 84 | 85 | 1. If You Share the Licensed Material (including in modified form), You must: 86 | 87 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 88 | 89 | 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); 90 | 91 | ii. a copyright notice; 92 | 93 | iii. a notice that refers to this Public License; 94 | 95 | iv. a notice that refers to the disclaimer of warranties; 96 | 97 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 98 | 99 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 100 | 101 | 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. 102 | 103 | 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. 104 | 105 | 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. 106 | 107 | 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. 108 | 109 | ### Section 4 – Sui Generis Database Rights. 110 | 111 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 112 | 113 | 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; 114 | 115 | 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 116 | 117 | 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. 118 | 119 | 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. 120 | 121 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 122 | 123 | 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.__ 124 | 125 | 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.__ 126 | 127 | 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. 128 | 129 | ### Section 6 – Term and Termination. 130 | 131 | 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. 132 | 133 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 134 | 135 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 136 | 137 | 2. upon express reinstatement by the Licensor. 138 | 139 | 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. 140 | 141 | 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. 142 | 143 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 144 | 145 | ### Section 7 – Other Terms and Conditions. 146 | 147 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 148 | 149 | 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. 150 | 151 | ### Section 8 – Interpretation. 152 | 153 | 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. 154 | 155 | 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. 156 | 157 | 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. 158 | 159 | 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. 160 | 161 | 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. 162 | 163 | Creative Commons may be contacted at creativecommons.org 164 | -------------------------------------------------------------------------------- /training/README.md: -------------------------------------------------------------------------------- 1 | # GANnotation training scripts 2 | 3 | This code is the re-polished version of the training pipeline of GANnotation I developed whilst holding a post-doc position at the University of Nottingham. Due to the clean-up, it might be the case that the models trained under this script are not suitable to be tested under the previously released testing code. A new testing pipeline will follow up. 4 | 5 | # Data 6 | 7 | Example of training: 8 | ``` 9 | python train.py --bSize 64 --db 300VW --path '' --use_edge 10 | ``` 11 | 12 | This code uses the 300VW. We have first processed it by extracting its frames and gathering the landmarks in the files pts.pt. In order to run the code as is you need to extract the frames and gather the corresponding points into the pts.pt file. A script to process it might follow-up. 13 | 14 | Alternatively, you can use your own data. It is suggested to use the skeleton provided in databases.py as it enables the use of multiple databases in a much easier way: 15 | 16 | ``` 17 | ConcatDataset([SuperDB(path=args.path[i], db=db, size=128, hm_size=128, flip=True, angle=15, tight=int(args.tight), edge=args.use_edge) for i,db in enumerate(args.db)]) 18 | ``` 19 | 20 | The skeleton only needs an init function to gather the needed information, and a collect function, that yields a list with images and corresponding points. The rest will be processed within the main SuperDB class. 21 | 22 | ``` 23 | if db == 'Skeleton': # this is an example of what to prepare in a db 24 | def init(self): 25 | # - here there's the stuff needed to collect points and images and labels or whatever 26 | # - they are then set to db as 27 | keys = ['frames','images'] 28 | for k in keys: 29 | setattr(self, k, eval(k)) # if the variables are named after the keys 30 | setattr(self,'len', lenval ) # set value of len 31 | def collect(idx): 32 | # - function to collect a sample to be processed in getitem 33 | return [image], [points] 34 | init(self) # - do the initialisation 35 | setattr(self,'collect', collect) # - add collect function to the class 36 | ``` 37 | 38 | 39 | # Notes 40 | 41 | - Use of heatmaps is not supported in this code yet. You should train your network with the flag --use_edge 42 | 43 | - This README.md file will be uploaded properly in due time 44 | 45 | 46 | # LICENSE 47 | 48 | Copyright © 2019. The University of Nottingham. All Rights Reserved. 49 | 50 | Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. 51 | 52 | All the material, including source code, is made freely available for non-commercial use under the Creative Commons CC BY-NC 4.0 license. Feel free to use any of the material in your own work, as long as you give us appropriate credit by mentioning the title and author list of our paper. 53 | 54 | All the third-party libraries (Python, PyTorch, Torchvision, Numpy, OpenCV, Visdom, Torchnet, GPUtil and SciPy) are owned by their respective authors, and must be used according to their respective licenses. The same applies to the models defined in model_GAN.py, mainly adopted from StarGAN. 55 | -------------------------------------------------------------------------------- /training/Train_options.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | 4 | class Options(): 5 | 6 | def __init__(self): 7 | self._parser = argparse.ArgumentParser(description='GANnotation training script') 8 | self.initialize() 9 | self.args = self.parse_args() 10 | self.write_args() 11 | 12 | def initialize(self): 13 | #### - Main options (filename, folder, print frequency, resume) 14 | self._parser.add_argument('--resume', default='', type=str, metavar='PATH', help='path to the latest checkpoint (default: none)') 15 | self._parser.add_argument('--print-freq', '-p', default=10, type=int, metavar='N', help='print frequency (default: 10)') 16 | self._parser.add_argument('--file', default='model_',help='Store model') 17 | self._parser.add_argument('--folder', default='.', help='Folder to save intermediate models') 18 | 19 | #### - Training details (bSize, gradient clippng, learning rate, gan type) 20 | self._parser.add_argument('--bSize', default=64, type=int,help='Batch Size') 21 | self._parser.add_argument('--gc', default=1, help='Use gradient clipping') 22 | self._parser.add_argument('--lr_dis', default=0.0001, type=float, help='learning rate dis') 23 | self._parser.add_argument('--lr_gen', default=0.0001, type=float, help='learning rate gen') 24 | self._parser.add_argument('--gantype', default='wgan-gp', type=str, help='GAN type') 25 | self._parser.add_argument('--num_workers', default=12, type=int, help='Number of workers') 26 | 27 | #### - Optimizer 28 | self._parser.add_argument('--optim',default='Adam',help='Optimizer') 29 | self._parser.add_argument('--params', nargs='+', help='List of optim params', default=['betas','(0.5,0.9)']) 30 | self._parser.add_argument('--weight_decay', default=5*1e-4, type=float, help='weight decay') 31 | self._parser.add_argument('--step_size', default=1, type=int, help='Step size for scheduler') 32 | self._parser.add_argument('--gamma', default=0.1, type=float, help='Gamma for scheduler') 33 | 34 | #### - Weights 35 | self._parser.add_argument('--l_adv', default=0.01, type=float, help='Adv loss') 36 | self._parser.add_argument('--l_rec', default=1, type=float, help='Reconstruction loss') 37 | self._parser.add_argument('--l_self', default=1, type=float, help='Cycle consistency loss') 38 | self._parser.add_argument('--l_triple', default=1, type=float, help='Triple consistency loss') 39 | self._parser.add_argument('--l_percep', default=0.1, type=float, help='Perceptual loss') 40 | self._parser.add_argument('--l_tv', default=1e-8, type=float, help='Total variation loss') 41 | 42 | #### - Data 43 | self._parser.add_argument('--tight', default=16, help='Tight') 44 | self._parser.add_argument('--path', nargs='+', help='Path to the data') 45 | self._parser.add_argument('--db', nargs='+', help='Path to the data') 46 | self._parser.add_argument('--use_edge', action='store_true', help='Use edge-maps') 47 | 48 | #### - Miscellanea 49 | self._parser.add_argument('--visdom', action='store_true', help='Use visdom') 50 | self._parser.add_argument('--port', default=9001, help='visdom port') 51 | self._parser.add_argument('--cuda', default='auto', type=str, help='cuda') 52 | 53 | 54 | def parse_args(self): 55 | self.args = self._parser.parse_args() 56 | if self.args.folder == '.': 57 | experimentname = sorted([l for l in os.listdir(os.getcwd()) if os.path.isdir(l) and l.find('Exp') > -1]) 58 | self.args.folder = 'Exp_{:d}'.format(len(experimentname)) 59 | return self.args 60 | 61 | def write_args(self): 62 | if not os.path.exists('./' + self.args.folder): 63 | os.mkdir('./' + self.args.folder) 64 | if not os.path.exists(os.path.join(self.args.folder, 'code')): 65 | os.mkdir(os.path.join(self.args.folder,'code')) 66 | with open(self.args.folder + '/args_' + self.args.file[0:-8] + '.txt','w') as f: 67 | print(self.args,file=f) 68 | 69 | 70 | -------------------------------------------------------------------------------- /training/databases.py: -------------------------------------------------------------------------------- 1 | import inspect, torch, pickle, cv2, os, numpy as np, scipy.io as sio, random, glob 2 | from torch.utils.data import Dataset 3 | from utils import process_image, NumpyHeatmap, EdgeMap 4 | import torchvision.transforms as tr 5 | 6 | class SuperDB(Dataset): 7 | 8 | def __init__(self, path=None, size=128, hm_size=128, flip=False, angle=0, tight=16, nimages=3, db='300VW', transform=None, edge=False): 9 | # - automatically add attributes to the class with the values given by the class 10 | args, _, _, values = inspect.getargvalues(inspect.currentframe()) 11 | del args[0] 12 | for k in args: 13 | setattr(self,k,values[k]) 14 | preparedb(self,db) 15 | self.db = db 16 | if transform is None: 17 | transform = tr.Compose([tr.ToTensor(), 18 | tr.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5)) 19 | ]) 20 | self.transform = transform 21 | if not edge: 22 | self.heatmap = NumpyHeatmap(out_res=hm_size, num_parts=68) 23 | else: 24 | self.heatmap = EdgeMap(out_res=hm_size, num_parts=3) 25 | self.ratio = int(size/hm_size) 26 | 27 | def __len__(self): 28 | return self.len 29 | 30 | def __getitem__(self,idx): 31 | image, points = self.collect(idx) 32 | nimg = len(image) 33 | sample = {} 34 | flip = np.random.rand(1)[0] > 0.5 if self.flip else False # flip both or none 35 | for j in range(self.nimages): 36 | out = process_image(image=image[j%nimg],points=points[j%nimg],angle=(j+1)*self.angle, flip=flip, size=self.size, tight=self.tight) 37 | if j == 0: 38 | sample['B_Im'] = self.transform(out['image']) 39 | sample['B_Hm'] = 2*(torch.from_numpy(self.heatmap(out['points']/self.ratio))-0.5) 40 | if j == 1: 41 | sample['A_Im'] = self.transform(out['image']) 42 | sample['A_Hm'] = 2*(torch.from_numpy(self.heatmap(out['points']/self.ratio))-0.5) 43 | if j == 2: 44 | sample['C_Im'] = self.transform(out['image']) 45 | sample['C_Hm'] = 2*(torch.from_numpy(self.heatmap(out['points']/self.ratio))-0.5) 46 | return sample 47 | 48 | 49 | # Define a function that returns the initialisation and the collect function 50 | def preparedb(self, db): 51 | 52 | if db == 'Skeleton': # this is an example of what to prepare in a db 53 | def init(self): 54 | # - here there's the stuff needed to collect points and images and labels or whatever 55 | # - they are then set to db as 56 | keys = ['frames','images'] 57 | for k in keys: 58 | setattr(self, k, eval(k)) # if the variables are named after the keys 59 | setattr(self,'len', lenval ) # set value of len 60 | def collect(idx): 61 | # - function to collect a sample to be processed in getitem 62 | return [image], [points] 63 | init(self) # - do the initialisation 64 | setattr(self,'collect', collect) # - add collect function to the class 65 | 66 | if db == '300VW': 67 | def init(self): 68 | catC = ['410', '411', '516', '517', '526', '528', '529', '530', '531', '533', '557', '558', '559', '562'] 69 | mylist = next(os.walk(self.path))[1] 70 | data = dict.fromkeys(sorted(set(mylist) - set(catC))) 71 | for i,name in enumerate(data.keys()): 72 | pathtocheck = self.path + name + '/frames/' 73 | files = list(map(lambda x: x.split('/')[-1], sorted(glob.glob(f'{pathtocheck}/*.jpg')))) 74 | pathtocheck = self.path + name + '/pts.pt' 75 | pts = torch.load(pathtocheck) 76 | data[name] = dict(zip(files,pts)) 77 | setattr(self, 'data', data) 78 | setattr(self, 'map', [(x,y) for x in data.keys() for y in data[x].keys()]) 79 | setattr(self, 'len', len(self.map)) 80 | setattr(self, 'getim', lambda vid, frame: cv2.cvtColor(cv2.imread(os.path.join(self.path, vid, 'frames', frame)), cv2.COLOR_BGR2RGB)) 81 | def collect(idx): 82 | vid, frame = self.map[idx] 83 | frames = list(self.data[vid].keys()) 84 | subframes = frames[max(0, frames.index(frame)-200):min(len(frames)-1, frames.index(frame)+200)] 85 | subframes = [s for s in subframes if np.abs(int(s.split('.')[0]) - int(frame.split('.')[0])) > 50] 86 | target = random.sample(subframes, 1)[0] 87 | third = random.sample(subframes,1)[0] 88 | image = [self.getim(vid,frame), self.getim(vid,target), self.getim(vid,third)] 89 | points = [self.data[vid][frame].numpy(), self.data[vid][target].numpy(), self.data[vid][third].numpy()] 90 | return image, points 91 | init(self) 92 | setattr(self,'collect', collect) 93 | 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /training/model_GAN.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import numpy as np 5 | 6 | 7 | class ResidualBlock(nn.Module): 8 | """Residual Block with instance normalization.""" 9 | def __init__(self, dim_in, dim_out): 10 | super(ResidualBlock, self).__init__() 11 | self.main = nn.Sequential( 12 | nn.Conv2d(dim_in, dim_out, kernel_size=3, stride=1, padding=1, bias=False), 13 | nn.InstanceNorm2d(dim_out, affine=True, track_running_stats=True), 14 | nn.ReLU(inplace=True), 15 | nn.Conv2d(dim_out, dim_out, kernel_size=3, stride=1, padding=1, bias=False), 16 | nn.InstanceNorm2d(dim_out, affine=True, track_running_stats=True)) 17 | 18 | def forward(self, x): 19 | return x + self.main(x) 20 | 21 | 22 | class Generator(nn.Module): 23 | """Generator network.""" 24 | def __init__(self, conv_dim=64, c_dim=3, repeat_num=6): 25 | super(Generator, self).__init__() 26 | 27 | layers = [] 28 | layers.append(nn.Conv2d(3+c_dim, conv_dim, kernel_size=7, stride=1, padding=3, bias=False)) 29 | layers.append(nn.InstanceNorm2d(conv_dim, affine=True, track_running_stats=True)) 30 | layers.append(nn.ReLU(inplace=True)) 31 | 32 | # Down-sampling layers. 33 | curr_dim = conv_dim 34 | for i in range(2): 35 | layers.append(nn.Conv2d(curr_dim, curr_dim*2, kernel_size=4, stride=2, padding=1, bias=False)) 36 | layers.append(nn.InstanceNorm2d(curr_dim*2, affine=True, track_running_stats=True)) 37 | layers.append(nn.ReLU(inplace=True)) 38 | curr_dim = curr_dim * 2 39 | 40 | # Bottleneck layers. 41 | for i in range(repeat_num): 42 | layers.append(ResidualBlock(dim_in=curr_dim, dim_out=curr_dim)) 43 | 44 | # Up-sampling layers. 45 | for i in range(2): 46 | layers.append(nn.ConvTranspose2d(curr_dim, curr_dim//2, kernel_size=4, stride=2, padding=1, bias=False)) 47 | layers.append(nn.InstanceNorm2d(curr_dim//2, affine=True, track_running_stats=True)) 48 | layers.append(nn.ReLU(inplace=True)) 49 | curr_dim = curr_dim // 2 50 | 51 | layers.append(nn.Conv2d(curr_dim, 3, kernel_size=7, stride=1, padding=3, bias=False)) 52 | layers.append(nn.Tanh()) 53 | self.main = nn.Sequential(*layers) 54 | 55 | def forward(self, x, maps): 56 | # Replicate spatially and concatenate domain information. 57 | # Note that this type of label conditioning does not work at all if we use reflection padding in Conv2d. 58 | # This is because instance normalization ignores the shifting (or bias) effect. 59 | x = torch.cat((x, maps), 1) 60 | return self.main(x) 61 | 62 | 63 | class Discriminator(nn.Module): 64 | """Discriminator network with PatchGAN.""" 65 | def __init__(self, image_size=128, conv_dim=64, ndim=66, repeat_num=6): 66 | super(Discriminator, self).__init__() 67 | layers = [] 68 | layers.append(nn.Conv2d(3+ndim, conv_dim, kernel_size=4, stride=2, padding=1)) 69 | layers.append(nn.LeakyReLU(0.01)) 70 | 71 | curr_dim = conv_dim 72 | for i in range(1, repeat_num): 73 | layers.append(nn.Conv2d(curr_dim, curr_dim*2, kernel_size=4, stride=2, padding=1)) 74 | layers.append(nn.LeakyReLU(0.01)) 75 | curr_dim = curr_dim * 2 76 | 77 | kernel_size = int(image_size / np.power(2, repeat_num)) 78 | self.main = nn.Sequential(*layers) 79 | self.conv1 = nn.Conv2d(curr_dim, 1, kernel_size=3, stride=1, padding=1, bias=False) 80 | #self.conv2 = nn.Conv2d(curr_dim, c_dim, kernel_size=kernel_size, bias=False) 81 | 82 | def forward(self, x): 83 | h = self.main(x) 84 | out_src = self.conv1(h) 85 | return out_src#, out_cls.view(out_cls.size(0), out_cls.size(1)) -------------------------------------------------------------------------------- /training/train.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function, division 2 | import glob, os, sys, pickle, torch, cv2, time, numpy as np 3 | from torch.utils.data import Dataset, DataLoader, ConcatDataset 4 | from torchvision.utils import save_image 5 | from shutil import copy2 6 | # mystuff 7 | from GANnotation import GANnotation as model 8 | from databases import SuperDB 9 | from utils import AverageMeter 10 | from Train_options import Options 11 | 12 | def main(): 13 | # parse args 14 | global args 15 | args = Options().args 16 | 17 | # copy all files from experiment 18 | cwd = os.getcwd() 19 | for ff in glob.glob("*.py"): 20 | copy2(os.path.join(cwd,ff), os.path.join(args.folder,'code')) 21 | 22 | # initialise seeds 23 | torch.backends.cudnn.benchmark = True 24 | torch.manual_seed(1000) 25 | torch.cuda.manual_seed(1000) 26 | np.random.seed(1000) 27 | 28 | # choose cuda 29 | if args.cuda == 'auto': 30 | import GPUtil as GPU 31 | GPUs = GPU.getGPUs() 32 | idx = [GPUs[j].memoryUsed for j in range(len(GPUs))] 33 | print(idx) 34 | assert min(idx) < 11.0, 'All {} GPUs are in use'.format(len(GPUs)) 35 | idx = idx.index(min(idx)) 36 | print('Assigning CUDA_VISIBLE_DEVICES={}'.format(idx)) 37 | os.environ["CUDA_VISIBLE_DEVICES"] = str(idx) 38 | else: 39 | os.environ["CUDA_VISIBLE_DEVICES"] = str(args.cuda) 40 | 41 | # get lambdas for the losses in the model and define model (GANnotation) 42 | myvars = [u for u in list(args.__dict__.keys()) if 'l_' in u] 43 | losses = dict(zip([m.replace('l_','') for m in myvars],[float(args.__getattribute__(val)) for val in myvars])) 44 | print(losses) 45 | with open(args.folder + '/args_' + args.file[0:-8] + '.txt','a') as f: 46 | print( losses , file=f) 47 | GANnotation = model(losses=losses, gradclip=int(args.gc), gantype=args.gantype, edge=args.use_edge) 48 | if args.resume: 49 | GANnotation._resume(path_to_gen=args.resume + str(args.start_epoch)+'.gen.pth', path_to_dis=args.resume + str(args.start_epoch) + 'dis.pth') 50 | 51 | # define the plotting keys 52 | plotkeys = ['input','target','generated'] 53 | genkeys = list(GANnotation.loss['G'].keys()) 54 | diskeys = list(GANnotation.loss['D'].keys()) 55 | 56 | # define plotters 57 | global plotter 58 | if not args.visdom: 59 | print('No Visdom') 60 | plotter = None 61 | else: 62 | from torchnet.logger import VisdomPlotLogger, VisdomLogger, VisdomSaver, VisdomTextLogger 63 | experimentsName = str(args.visdom) 64 | plotter = dict.fromkeys(['images','G','D']) 65 | plotter['images'] = dict( [ (key, VisdomLogger("images", port=int(args.port), env=experimentsName, opts={'title' : key})) for key in plotkeys ]) 66 | plotter['G'] = dict( [ (key, VisdomPlotLogger("line", port=int(args.port), env=experimentsName,opts={'title': f'G : {key}', 'xlabel' : 'Iteration', 'ylabel' : 'Loss'})) for key in genkeys] ) 67 | plotter['D'] = dict( [ (key, VisdomPlotLogger("line", port=int(args.port), env=experimentsName,opts={'title': f'D : {key}', 'xlabel' : 'Iteration', 'ylabel' : 'Loss'})) for key in diskeys] ) 68 | 69 | # prepare average meters 70 | global meters, l_iteration 71 | meterskey = ['batch_time', 'data_time'] 72 | meters = dict([(key,AverageMeter()) for key in meterskey]) 73 | meters['G'] = dict([(key,AverageMeter()) for key in genkeys]) 74 | meters['D'] = dict([(key,AverageMeter()) for key in diskeys]) 75 | l_iteration = float(0.0) 76 | 77 | # plot number of parameters 78 | params = sum([p.numel() for p in filter(lambda p: p.requires_grad, GANnotation.GEN.parameters())]) 79 | print('GEN # trainable parameters: {}'.format(params)) 80 | params = sum([p.numel() for p in filter(lambda p: p.requires_grad, GANnotation.DIS.parameters())]) 81 | print('DIS # trainable parameters: {}'.format(params)) 82 | 83 | # define data 84 | assert len(args.db) == len(args.path), 'Number of root paths not equal to number of dbs' 85 | videoloader = DataLoader(ConcatDataset([SuperDB(path=args.path[i], db=db, size=128, hm_size=128, flip=True, angle=15, tight=int(args.tight), edge=args.use_edge) for i,db in enumerate(args.db)]), 86 | batch_size=args.bSize, shuffle=True, num_workers=int(args.num_workers), pin_memory=True) 87 | print('Number of workers is {:d}, and bSize is {:d}'.format(int(args.num_workers),args.bSize)) 88 | 89 | # define optimizers 90 | args.params[1::2] = [eval(args.params[2*j+1]) for j in range(int(len(args.params)/2))] 91 | optim = getattr(args, 'optim', 'Adam') 92 | params = dict(zip(args.params[::2], args.params[1::2])) 93 | optimizerGEN = getattr(torch.optim,optim)(GANnotation.GEN.parameters(), lr=args.lr_gen, **params, weight_decay=args.weight_decay) 94 | optimizerDIS = getattr(torch.optim,optim)(GANnotation.DIS.parameters(), lr=args.lr_dis, **params, weight_decay=args.weight_decay) 95 | schedulerGEN = torch.optim.lr_scheduler.StepLR(optimizerGEN, step_size=args.step_size, gamma=args.gamma) 96 | schedulerDIS = torch.optim.lr_scheduler.StepLR(optimizerDIS, step_size=args.step_size, gamma=args.gamma) 97 | myoptimizers = {'GEN': optimizerGEN, 'DIS': optimizerDIS} 98 | 99 | # path to save models and images 100 | path_to_model = os.path.join(args.folder,args.file) 101 | 102 | # train 103 | for epoch in range(0,80): 104 | train_epoch(videoloader, GANnotation, myoptimizers, epoch, args.bSize) 105 | GANnotation._save(path_to_model,epoch) 106 | schedulerDIS.step() 107 | schedulerGEN.step() 108 | 109 | 110 | def train_epoch(dataloader, model, myoptimizers, epoch, bSize): 111 | 112 | global l_iteration 113 | log_epoch = {} 114 | end = time.time() 115 | disiters = 5 if args.gantype == 'wgan-gp' else 2 116 | for i, data in enumerate(dataloader): 117 | data = {k: v.to('cuda') for k,v in data.items()} 118 | if i > 10000: 119 | break 120 | 121 | if (i+1) % disiters == 0: 122 | model._forward_G(data) 123 | myoptimizers['GEN'].step() 124 | for k in meters['G'].keys(): 125 | meters['G'][k].update( model.loss['G'][k].item() if model.loss['G'] is not None else 0, bSize) 126 | 127 | else: 128 | model._forward_D(data) 129 | myoptimizers['DIS'].step() 130 | for k in meters['D'].keys(): 131 | meters['D'][k].update( model.loss['D'][k].item() if model.loss['D'] is not None else 0, bSize) 132 | 133 | l_iteration = l_iteration + 1 134 | 135 | 136 | if i % 100 == 0: 137 | # - plot some images 138 | with torch.no_grad(): 139 | AB = model(data['A_Im'], data['B_Hm']) 140 | 141 | if plotter is not None: 142 | plotter['images']['input'].log(0.5*(1+data['A_Im'].data)) 143 | plotter['images']['target'].log(0.5*(1+data['B_Im'].data)) 144 | plotter['images']['generated'].log(0.5*(1+AB.cpu().data)) 145 | 146 | for k in ['G','D']: 147 | for (j,_) in filter(lambda x: x[1] is not None, model.loss[k].items()): 148 | plotter[k][j].log(l_iteration, model.loss[k][j].item()) 149 | 150 | 151 | saveA = 0.5*(torch.nn.functional.interpolate(data['A_Im'],scale_factor=0.25)+1) 152 | saveB = 0.5*(torch.nn.functional.interpolate(data['B_Im'],scale_factor=0.25)+1) 153 | saveAB = 0.5*(torch.nn.functional.interpolate(AB,scale_factor=0.25)+1) 154 | save = torch.cat((saveA, saveB, saveAB), 2) 155 | save_image(save, args.folder + '/{}_{}.png'.format(epoch,i)) 156 | 157 | log_epoch[i] = model.loss 158 | meters['batch_time'].update(time.time()-end) 159 | end = time.time() 160 | if i % args.print_freq == 0: 161 | mystr = 'Epoch [{}][{}/{}] '.format(epoch, i, len(dataloader)) 162 | mystr += 'Time {:.2f} ({:.2f}) '.format(meters['data_time'].val , meters['data_time'].avg ) 163 | mystr += ' '.join(['G: {:s} {:.3f} ({:.3f}) '.format(k, meters['G'][k].val , meters['G'][k].avg ) for k in meters['G'].keys()]) 164 | mystr += ' '.join(['D: {:s} {:.3f} ({:.3f}) '.format(k, meters['D'][k].val , meters['D'][k].avg ) for k in meters['D'].keys()]) 165 | print( mystr ) 166 | with open(args.folder + '/args_' + args.file[0:-8] + '.txt','a') as f: 167 | print( mystr , file=f) 168 | 169 | with open(args.folder + '/args_' + args.file[0:-8] + '_' + str(epoch) + '.pkl','wb') as f: 170 | pickle.dump(log_epoch,f) 171 | 172 | if __name__ == '__main__': 173 | main() 174 | 175 | -------------------------------------------------------------------------------- /training/utils.py: -------------------------------------------------------------------------------- 1 | import os, sys, time, torch, math, numpy as np, cv2, collections, itertools 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | ################################### - classes 6 | 7 | class AverageMeter(object): 8 | """Computes and stores the average and current value""" 9 | def __init__(self): 10 | self.reset() 11 | 12 | def reset(self): 13 | self.val = 0 14 | self.avg = 0 15 | self.sum = 0 16 | self.count = 0 17 | 18 | def update(self, val, n=1): 19 | self.val = val 20 | self.sum += val * n 21 | self.count += n 22 | self.avg = self.sum / self.count 23 | 24 | class LossNetwork(torch.nn.Module): 25 | def __init__(self, vgg_model): 26 | super(LossNetwork, self).__init__() 27 | self.LossOutput = collections.namedtuple("LossOutput", ["relu1_2", "relu2_2", "relu3_3", "relu4_3"]) 28 | self.vgg_layers = vgg_model.features if hasattr(vgg_model,'features') else vgg_model.module.features #### to allow use in DataParallel 29 | self.layer_name_mapping = { 30 | '3': "relu1_2", 31 | '8': "relu2_2", 32 | '15': "relu3_3", 33 | '22': "relu4_3" 34 | } 35 | 36 | def forward(self, x): 37 | output = {} 38 | for name, module in self.vgg_layers._modules.items(): 39 | x = module(x) 40 | if name in self.layer_name_mapping: 41 | output[self.layer_name_mapping[name]] = x 42 | return self.LossOutput(**output) 43 | 44 | 45 | class EdgeMap(object): 46 | def __init__(self,out_res, num_parts=3): 47 | self.out_res = out_res 48 | self.num_parts = num_parts 49 | self.groups = [ 50 | [np.arange(0,17,1), (255,0,0)], 51 | [np.arange(17,22,1), (0,255,0)], 52 | [np.arange(22,27,1), (0,255,0)], 53 | [np.arange(27,31,1), (0,0,255)], 54 | [np.arange(31,36,1), (0,0,255)], 55 | [list(np.arange(36,42,1))+[36], (0,255,0)], 56 | [list(np.arange(42,48,1))+[42], (0,255,0)], 57 | [list(np.arange(48,60,1))+[48], (0,0,255)], 58 | [list(np.arange(60,68,1))+[60], (0,0,255)] 59 | ] 60 | 61 | def __call__(self,shape): 62 | image = np.zeros((self.out_res, self.out_res, self.num_parts), dtype=np.float32) 63 | for g in self.groups: 64 | for i in range(len(g[0]) - 1): 65 | start = int(shape[g[0][i]][0]), int(shape[g[0][i]][1]) 66 | end = int(shape[g[0][i+1]][0]), int(shape[g[0][i+1]][1]) 67 | cv2.line(image, start, end, g[1], 3) 68 | 69 | return image.transpose(2,0,1)/255.0 70 | 71 | class NumpyHeatmap(object): 72 | def __init__(self, out_res, num_parts=68): 73 | pass 74 | def __call__(self, shape): 75 | raise NameError('To be added') 76 | 77 | 78 | ################################ functions 79 | 80 | def process_image(image,points,angle=0, flip=False, sigma=1,size=128, tight=16, hmsize=64): 81 | output = dict.fromkeys(['image','points','M']) 82 | if angle > 0: 83 | tmp_angle = np.clip(np.random.randn(1) * angle, -40.0, 40.0) 84 | image,points,M = affine_trans(image,points, tmp_angle) 85 | output['M'] = M 86 | tight = int(tight + 4*np.random.randn()) 87 | image, points = crop( image , points, size, tight ) 88 | if flip: 89 | image = cv2.flip(image, 1) 90 | groups = [(17,0,-1), (27,17,-1), (28,32,1), (36,31,-1), (46,42,-1), (48,46,-1),(40,36,-1),(42,40,-1),(55,48,-1),(60,55,-1),(65,60,-1),(68,65,-1)] 91 | pts_mirror = np.array(list(itertools.chain(*[range(k[0],k[1],k[2]) for k in groups]))) - 1 92 | points = (image.shape[1],0) + (-1,1)*points[pts_mirror,:] 93 | 94 | output['image'] = image 95 | output['points'] = np.floor(points) 96 | 97 | return output 98 | 99 | 100 | def crop( image, landmarks , size, tight=8): 101 | delta_x = np.max(landmarks[:,0]) - np.min(landmarks[:,0]) 102 | delta_y = np.max(landmarks[:,1]) - np.min(landmarks[:,1]) 103 | delta = 0.5*(delta_x + delta_y) 104 | if delta < 20: 105 | tight_aux = 8 106 | else: 107 | tight_aux = int(tight * delta/100) 108 | pts_ = landmarks.copy() 109 | w = image.shape[1] 110 | h = image.shape[0] 111 | min_x = int(np.maximum( np.round( np.min(landmarks[:,0]) ) - tight_aux , 0 )) 112 | min_y = int(np.maximum( np.round( np.min(landmarks[:,1]) ) - tight_aux , 0 )) 113 | max_x = int(np.minimum( np.round( np.max(landmarks[:,0]) ) + tight_aux , w-1 )) 114 | max_y = int(np.minimum( np.round( np.max(landmarks[:,1]) ) + tight_aux , h-1 )) 115 | image = image[min_y:max_y,min_x:max_x,:] 116 | pts_[:,0] = pts_[:,0] - min_x 117 | pts_[:,1] = pts_[:,1] - min_y 118 | sw = size/image.shape[1] 119 | sh = size/image.shape[0] 120 | im = cv2.resize(image, dsize=(size,size), 121 | interpolation=cv2.INTER_LINEAR) 122 | 123 | pts_[:,0] = pts_[:,0]*sw 124 | pts_[:,1] = pts_[:,1]*sh 125 | return im, pts_ 126 | 127 | 128 | 129 | def affine_trans(image,landmarks,angle=None,size=None): 130 | if angle is None: 131 | angle = 30*torch.randn(1) 132 | 133 | 134 | (h, w) = image.shape[:2] 135 | (cX, cY) = (w // 2, h // 2) 136 | 137 | M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0) 138 | cos = np.abs(M[0, 0]) 139 | sin = np.abs(M[0, 1]) 140 | 141 | # compute the new bounding dimensions of the image 142 | nW = int((h * sin) + (w * cos)) 143 | nH = int((h * cos) + (w * sin)) 144 | 145 | # adjust the rotation matrix to take into account translation 146 | M[0, 2] += (nW / 2) - cX 147 | M[1, 2] += (nH / 2) - cY 148 | dst = cv2.warpAffine(image, M, (nW,nH),borderMode=cv2.BORDER_REPLICATE) 149 | #print(landmarks.shape) 150 | new_landmarks = np.concatenate((landmarks,np.ones((landmarks.shape[0],1))),axis=1) 151 | if size is not None: 152 | sw = size/nW 153 | sh = size/nH 154 | dst = cv2.resize(dst, dsize=(size,size), 155 | interpolation=cv2.INTER_LINEAR) 156 | M = [[sw,0],[0,sh]] @ M 157 | 158 | new_landmarks = new_landmarks.dot(M.transpose()) 159 | return dst, new_landmarks, M 160 | 161 | 162 | 163 | def init_weights(net, init_type='normal', gain=0.02): 164 | def init_func(m): 165 | classname = m.__class__.__name__ 166 | if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1): 167 | if init_type == 'normal': 168 | torch.nn.init.normal_(m.weight.data, 0.0, gain) 169 | elif init_type == 'xavier': 170 | torch.nn.init.xavier_normal_(m.weight.data, gain=gain) 171 | elif init_type == 'kaiming': 172 | torch.nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') 173 | elif init_type == 'orthogonal': 174 | torch.nn.init.orthogonal_(m.weight.data, gain=gain) 175 | else: 176 | raise NotImplementedError('initialization method [%s] is not implemented' % init_type) 177 | if hasattr(m, 'bias') and m.bias is not None: 178 | torch.nn.init.constant_(m.bias.data, 0.0) 179 | elif classname.find('BatchNorm2d') != -1: 180 | torch.nn.init.normal_(m.weight.data, 1.0, gain) 181 | torch.nn.init.constant_(m.bias.data, 0.0) 182 | 183 | print('initialize network with %s' % init_type) 184 | net.apply(init_func) 185 | 186 | 187 | 188 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import time 4 | import torch 5 | import math 6 | import numpy as np 7 | import cv2 8 | 9 | def process_image(image,points,angle=0, flip=False, sigma=1,size=128, tight=16): 10 | if angle > 0: 11 | if np.random.rand(1) > 0.4: 12 | tmp_angle = np.random.randn(1) * angle 13 | image,points = affine_trans(image,points, tmp_angle) 14 | image, points = crop( image , points, size, tight ) 15 | if flip: 16 | if np.random.rand(1) > 0.5: 17 | image,points = flip_ImAndPts(image,points) 18 | 19 | image = image/255.0 20 | image = torch.from_numpy(image.swapaxes(2,1).swapaxes(1,0)) 21 | image = image.type_as(torch.FloatTensor()) 22 | 23 | source_maps = generate_maps(points, sigma, size) 24 | source_maps = source_maps.type_as(torch.FloatTensor()) 25 | 26 | return image, source_maps, points 27 | 28 | 29 | def _gaussian( 30 | size=3, sigma=0.25, amplitude=1, normalize=False, width=None, 31 | height=None, sigma_horz=None, sigma_vert=None, mean_horz=0.5, 32 | mean_vert=0.5): 33 | # handle some defaults 34 | if width is None: 35 | width = size 36 | if height is None: 37 | height = size 38 | if sigma_horz is None: 39 | sigma_horz = sigma 40 | if sigma_vert is None: 41 | sigma_vert = sigma 42 | center_x = mean_horz * width + 0.5 43 | center_y = mean_vert * height + 0.5 44 | gauss = np.empty((height, width), dtype=np.float32) 45 | # generate kernel 46 | for i in range(height): 47 | for j in range(width): 48 | gauss[i][j] = amplitude * math.exp(-(math.pow((j + 1 - center_x) / ( 49 | sigma_horz * width), 2) / 2.0 + math.pow((i + 1 - center_y) / (sigma_vert * height), 2) / 2.0)) 50 | if normalize: 51 | gauss = gauss / np.sum(gauss) 52 | return gauss 53 | 54 | 55 | def draw_gaussian(image, point, sigma): 56 | # Check if the gaussian is inside 57 | point[0] = round( point[0], 2) 58 | point[1] = round( point[1], 2) 59 | 60 | ul = [math.floor(point[0] - 3 * sigma), math.floor(point[1] - 3 * sigma)] 61 | br = [math.floor(point[0] + 3 * sigma), math.floor(point[1] + 3 * sigma)] 62 | if (ul[0] > image.shape[1] or ul[1] > 63 | image.shape[0] or br[0] < 1 or br[1] < 1): 64 | return image 65 | size = 6 * sigma + 1 66 | g = _gaussian(size) 67 | g_x = [int(max(1, -ul[0])), int(min(br[0], image.shape[1])) - int(max(1, ul[0])) + int(max(1, -ul[0]))] 68 | g_y = [int(max(1, -ul[1])), int(min(br[1], image.shape[0])) - int(max(1, ul[1])) + int(max(1, -ul[1]))] 69 | img_x = [int(max(1, ul[0])), int(min(br[0], image.shape[1]))] 70 | img_y = [int(max(1, ul[1])), int(min(br[1], image.shape[0]))] 71 | assert (g_x[0] > 0 and g_y[1] > 0) 72 | image[img_y[0] - 1:img_y[1], img_x[0] - 1:img_x[1] 73 | ] = image[img_y[0] - 1:img_y[1], img_x[0] - 1:img_x[1]] + g[g_y[0] - 1:g_y[1], g_x[0] - 1:g_x[1]] 74 | image[image > 1] = 1 75 | return image 76 | 77 | 78 | 79 | 80 | def generate_maps(points, sigma, size=256): 81 | maps = None 82 | for i in range(0,66): 83 | tpt = np.array([points[i,0],points[i,1]]) 84 | map = draw_gaussian(np.zeros((size,size)),tpt,sigma=sigma) 85 | if maps is None: 86 | maps = torch.from_numpy(map).unsqueeze(0) 87 | else: 88 | maps = torch.cat((maps, torch.from_numpy(map).unsqueeze(0)), 0) 89 | return maps 90 | 91 | def crop( image, landmarks , size, tight=8): 92 | delta_x = np.max(landmarks[:,0]) - np.min(landmarks[:,0]) 93 | delta_y = np.max(landmarks[:,1]) - np.min(landmarks[:,1]) 94 | delta = 0.5*(delta_x + delta_y) 95 | if delta < 20: 96 | tight_aux = 8 97 | else: 98 | tight_aux = int(tight * delta/100) 99 | pts_ = landmarks.copy() 100 | w = image.shape[1] 101 | h = image.shape[0] 102 | min_x = int(np.maximum( np.round( np.min(landmarks[:,0]) ) - tight_aux , 0 )) 103 | min_y = int(np.maximum( np.round( np.min(landmarks[:,1]) ) - tight_aux , 0 )) 104 | max_x = int(np.minimum( np.round( np.max(landmarks[:,0]) ) + tight_aux , w-1 )) 105 | max_y = int(np.minimum( np.round( np.max(landmarks[:,1]) ) + tight_aux , h-1 )) 106 | image = image[min_y:max_y,min_x:max_x,:] 107 | pts_[:,0] = pts_[:,0] - min_x 108 | pts_[:,1] = pts_[:,1] - min_y 109 | sw = size/image.shape[1] 110 | sh = size/image.shape[0] 111 | im = cv2.resize(image, dsize=(size,size), 112 | interpolation=cv2.INTER_LINEAR) 113 | 114 | pts_[:,0] = pts_[:,0]*sw 115 | pts_[:,1] = pts_[:,1]*sh 116 | return im, pts_ 117 | 118 | def generate_Ginput( img, target_pts , sigma , size=256 ): 119 | 120 | target_maps = generate_maps(target_pts, sigma, size) 121 | target_maps = target_maps.type_as(torch.FloatTensor()) 122 | A_to_B = torch.cat((img, target_maps),0) 123 | return A_to_B 124 | 125 | 126 | 127 | def flip_ImAndPts(image,landmarks): 128 | flipImg = cv2.flip(image, 1) 129 | pts_mirror = np.hstack(([range(17,0,-1), range(27,17,-1), range(28,32,1), range(36,31,-1), range(46,42,-1),48,47, range(40,36,-1),42,41,range(55,48,-1),range(60,55,-1),range(63,60,-1),range(66,63,-1)])) 130 | pts_mirror = pts_mirror - 1 131 | flipLnd = np.copy(landmarks) 132 | flipLnd[:,0] = image.shape[1] - landmarks[pts_mirror,0] 133 | flipLnd[:,1] = landmarks[pts_mirror,1] 134 | return flipImg,flipLnd 135 | 136 | def affine_trans(image,landmarks,angle=None): 137 | if angle is None: 138 | angle = 30*torch.randn(1) 139 | 140 | 141 | (h, w) = image.shape[:2] 142 | (cX, cY) = (w // 2, h // 2) 143 | 144 | M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0) 145 | cos = np.abs(M[0, 0]) 146 | sin = np.abs(M[0, 1]) 147 | 148 | # compute the new bounding dimensions of the image 149 | nW = int((h * sin) + (w * cos)) 150 | nH = int((h * cos) + (w * sin)) 151 | 152 | # adjust the rotation matrix to take into account translation 153 | M[0, 2] += (nW / 2) - cX 154 | M[1, 2] += (nH / 2) - cY 155 | dst = cv2.warpAffine(image, M, (nW,nH)) 156 | new_landmarks = np.concatenate((landmarks,np.ones((66,1))),axis=1) 157 | new_landmarks = new_landmarks.dot(M.transpose()) 158 | 159 | return dst, new_landmarks 160 | 161 | 162 | def gram_matrix(input): 163 | bsize, ch, r, c = input.size() 164 | features = input.view(bsize * ch, r * c) 165 | G = torch.mm(features, features.t()) 166 | return G.div(bsize*ch*r*c) 167 | 168 | --------------------------------------------------------------------------------