原标题:教你如何用Python画出心目中的自己
引言:人脸图像的生成在各个行业有着重要应用,例如刑事调查、人物设计、教育培训等。然而一幅逼真的人脸肖像,对于职业画家也要至少数小时才能绘制出来;对于从未接触过绘画的新手,就更是难如登天了。新手绘制出来的人脸草图往往非常简陋抽象,甚至有不匀称、不完整。但如果使用智能人脸画板,无疑是有如神助。
本项目主要来源于中科院和香港城市大学的一项研究DeepFaceDrawing,论文标题是《DeepFaceDrawing: DeepGeneration of Face Images from Sketches》
具体效果如下图可见:
实验前的准备
首先我们使用的python版本是3.6.5所用到的模块如下:
Pyqt5模块:PyQt5是基于Digia公司强大的图形程式框架Qt5的python接口,由一组python模块构成。PyQt5本身拥有超过620个类和6000函数及方法。在可以运行于多个平台,包括:Unix, Windows, and Mac OS。
opencv是将用来进行图像处理和生成。
numpy模块用来处理矩阵运算。
Jittor模块国内清华大学开源的深度学习框架。
_thread是多线程库。
网络模型的定义和训练
首先这个图像合成模块采用了一种利用发生器和鉴别器的GAN结构。从融合的特征图生成真实的人脸图像。鉴别器采用多尺度鉴别方式:对输入进行尺度划分,特征图和生成的图像在三个不同的层次上,经过三个不同的过程。:
(1)权重网络层和损失定义:
def weights_init_normal(m):
classname = m.__class__.__name__
ifclassname.find("Conv") != -1:
jt.init.gauss_(m.weight,0.0, 0.02)
elifclassname.find("BatchNorm") != -1:
jt.init.gauss_(m.weight,1.0, 0.02)
jt.init.constant_(m.bias,0.0)
def get_norm_layer(norm_type='instance'):
if (norm_type == 'batch'):
norm_layer = nn.BatchNorm
elif (norm_type == 'instance'):
norm_layer =nn.InstanceNorm2d
else:
raiseNotImplementedError(('normalization layer [%s] is not found' % norm_type))
return norm_layer
class MSELoss:
def __init__(self):
pass
def __call__(self, output,target):
from jittor.nn importmse_loss
return mse_loss(output,target)
class BCELoss:
def __init__(self):
pass
def __call__(self, output,target):
from jittor.nn importbce_loss
return bce_loss(output,target)
(2)模型特征编解码:
特征匹配模块包含5个译码网络,以compact作为输入由分量流形得到的特征向量,并将其转换为对应的特征向量为后续生成的特征图的大小。
def define_part_encoder(model='mouth', norm='instance', input_nc=1,latent_dim=512):
norm_layer =get_norm_layer(norm_type=norm)
image_size = 512
if 'eye' in model:
image_size = 128
elif 'mouth' in model:
image_size = 192
elif 'nose' in model:
image_size = 160
elif 'face' in model:
image_size = 512
else:
print("Whole Image!!")
net_encoder =EncoderGenerator_Res(norm_layer,image_size,input_nc, latent_dim) # input longsize 256 to 512*4*4
print("net_encoder of part"+model+" is:",image_size)
return net_encoder
def define_part_decoder(model='mouth', norm='instance', output_nc=1,latent_dim=512):
norm_layer =get_norm_layer(norm_type=norm)
image_size = 512
if 'eye' in model:
image_size = 128
elif 'mouth' in model:
image_size = 192
elif 'nose' in model:
image_size = 160
else:
print("Whole Image!!")
net_decoder =DecoderGenerator_image_Res(norm_layer,image_size,output_nc, latent_dim) # input longsize 256 to 512*4*4
print(