一 图片融合较差的原因
我们通过github上提供的源码训练出的模型虽然学到了表情,但是融合出的质量并不高,这是因为github上源码图片融合未采用好的融合方式,而是直接采用了以下一种比较简单粗暴的方式:
其代码片段为:
def convert_one_image( autoencoder, image ):
assert image.shape == (256,256,3)
crop = slice(48,208)
face = image[crop,crop] #图片剪切,抠出中间部分
face = cv2.resize( face, (64,64) )#转换为decoder需要的格式
face = numpy.expand_dims( face, 0 )
new_face = autoencoder.predict( face / 255.0 )[0]#输入到解码器中
new_face = numpy.clip( new_face * 255, 0, 255 ).astype( image.dtype )
new_face = cv2.resize( new_face, (160,160) )
new_image = image.copy()
new_image[crop,crop] = new_face#将转换好的人俩在贴回抠除的图片中
return new_image
这种方式融合出的图片可以看到清晰的替换框。
二 更换融合方法
为了让替换框不明显,为此我们需要对融合方式进行替换,使其效果更好。
改进方式:融合方式更换为泊松融合。
更改后的script.py文件
import cv2
import numpy
from pathlib import Path
import numpy as np
from utils import get_image_paths
from model import autoencoder_A
from model import autoencoder_B
from model import encoder, decoder_A, decoder_B
encoder .load_weights( "models/encoder.h5" )
decoder_A.load_weights( "models/decoder_A.h5" )
decoder_B.load_weights( "models/decoder_B.h5" )
images_A = get_image_paths( "data/trump" )
images_B = get_image_paths( "data/cage" )
def convert_one_image( autoencoder, image ):
assert image.shape == (256,256,3)
crop = slice(48,208)
face = image[crop,crop]
face = cv2.resize( face, (64,64) )
face = numpy.expand_dims( face, 0 )
new_face = autoencoder.predict( face / 255.0 )[0]
new_face = numpy.clip( new_face * 255, 0, 255 ).astype( image.dtype )
new_face = cv2.resize( new_face, (160,160) )
new_image = image.copy()
###################
# Create an all white mask
mask = 255 * np.ones(new_face.shape,new_face.dtype)
width, height, channels = image.shape
center = (height // 2, width // 2)
normal_clone = cv2.seamlessClone(new_face, image, mask, center, cv2.NORMAL_CLONE)#泊松融合的NORMAL_CLONE方法
mixed_clone = cv2.seamlessClone(new_face, image, mask, center, cv2.MIXED_CLONE)#泊松融合的MIXED_CLONE方法
return normal_clone,mixed_clone
###################
output_dir1 = Path( 'output1' )
output_dir2 = Path( 'output2' )
output_dir1.mkdir( parents=True, exist_ok=True )
output_dir2.mkdir( parents=True, exist_ok=True )
for fn in images_A:
image = cv2.imread(fn)
new_image1,new_image2 = convert_one_image( autoencoder_B, image)
output_file1 = output_dir1 / Path(fn).name
output_file2 = output_dir2 / Path(fn).name
cv2.imwrite( str(output_file1), new_image1 )
cv2.imwrite(str(output_file2), new_image2)
更换为泊松融合的方式后,其效果如下:
虽然框框边缘二者差异降低,但是效果并不是很好,这和训练集图片清晰度不高有关系,可采用更高清晰度的图片去训练。