style参考地址:https://github.com/NVlabs/stylegan
生成gif参考地址:https://github.com/parameter-pollution/stylegan_paintings
paper地址:https://arxiv.org/abs/1812.04948
"""generating cycle gif images"""
import os
import pickle
import numpy as np
import PIL.Image
#import Image
import dnnlib
import dnnlib.tflib as tflib
import config
import argparse
import pandas as pd
import time
def get_latent_input(data):
filter_data = data.replace("\n"," ").replace("\t"," ").replace("\r"," ").replace("[","").replace("]","")
filter_data = ' '.join(filter_data.split())
filter_data = filter_data.replace(" ", ",")
filter_data = [float(value) for value in filter_data.split(",")]
latent_input = np.array([filter_data])
return latent_input
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-pth", "--pth_path", help="the path of pth module", default="network-snapshot-004650.pkl")
parser.add_argument("-range", "--range_value", help="range of random state", default=2019, type=int )
parser.add_argument("-csv", "--csv_file", help="csv file used for storing vector and imagename", default="map.csv", type=str)
parser.add_argument("-map", "--map_file", help="csv file used for getting vector and imagename", default="map1.csv", type=str)
parser.add_argument("-pair", "--pair_file", help="csv file used for getting two vectors", default="pair.csv", type=str)
parser.add_argument("-dir", "--results_dir", help="results dir used for storing animation gif", default="results_dir", type=str)
parser.add_argument("-append", "--append_value", help="value for additional path of pair csv", default="", type=str)
parser.add_argument("-num","--number", help="how many images should be generated", default=100, type=int)
parser.add_argument("--generate", action="store_true")
args = parser.parse_args()
map_data = pd.read_csv(args.map_file,header=None,index_col=False)
pair_data = pd.read_csv(args.pair_file,header=None,index_col=False)
animation_results = args.results_dir
os.makedirs(animation_results, exist_ok=True)
csv_list = []
tflib.init_tf()
model_path = args.pth_path
with open(model_path,"rb") as f:
_G, _D, Gs = pickle.load(f)
Gs.print_layers()
fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True)
for index, pair in enumerate(pair_data.values):
dir_name = os.path.join(args.results_dir, "animation" + "_" + str(index))
if not os.path.exists(dir_name):
os.makedirs(dir_name)
length = len(pair)
picture_index = 1
print(index, pair)
for position, t_value in enumerate(pair):
if position != length - 1 and pd.isnull(pair[position + 1]) == False:
print(args.append_value, position, t_value, pair[position + 1])
latent_vector1 = get_latent_input(map_data[map_data[0] == args.append_value + t_value][1].values[0])
latent_vector2 = get_latent_input(map_data[map_data[0] == args.append_value + pair[position + 1]][1].values[0])
number_of_frames = 240
frame_step = 1.0/number_of_frames
x = 0
for frame_count in range(1,number_of_frames):
x = x + frame_step
latent_input = latent_vector1.copy()
for i in range(512):
f1 = latent_vector1[0][i]
f2 = latent_vector2[0][i]
# if f1 > f2:
# tmp = f2
# f2 = f1
# f1 = tmp
fnew = f1 + (f2-f1)*x
latent_input[0][i] = fnew
images = Gs.run(latent_input, None, truncation_psi=1, randomize_noise=False, output_transform=fmt)
png_filename = os.path.join(dir_name, str("%05d"%picture_index)+'.png')
picture_index += 1
PIL.Image.fromarray(images[0], 'RGB').save(png_filename)
elif pd.isnull(pair[position]) == False:
print(args.append_value, position, t_value, pair[0])
latent_vector1 = get_latent_input(map_data[map_data[0] == args.append_value + t_value][1].values[0])
latent_vector2 = get_latent_input(map_data[map_data[0] == args.append_value + pair[0]][1].values[0])
number_of_frames = 100
frame_step = 1.0/number_of_frames
x = 0
for frame_count in range(1,number_of_frames):
x = x + frame_step
latent_input = latent_vector1.copy()
for i in range(512):
f1 = latent_vector1[0][i]
f2 = latent_vector2[0][i]
# if f1 > f2:
# tmp = f2
# f2 = f1
# f1 = tmp
fnew = f1 + (f2-f1)*x
latent_input[0][i] = fnew
images = Gs.run(latent_input, None, truncation_psi=1, randomize_noise=False, output_transform=fmt)
png_filename = os.path.join(dir_name, str("%05d"%picture_index)+'.png')
picture_index += 1
PIL.Image.fromarray(images[0], 'RGB').save(png_filename)
pair = [value.replace(".png","") for value in pair if not pd.isnull(value)]
os.system("convert " + dir_name + "/*.png " + animation_results + "/" + str(index) + "#" + "-".join(pair) + ".gif")
if __name__ == "__main__":
main()
import os
import pickle
import numpy as np
import PIL.Image
#import Image
import dnnlib
import dnnlib.tflib as tflib
import config
import argparse
import pandas as pd
import time
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-pth", "--pth_path", help="the path of pth module", default="network-snapshot-004650.pkl")
parser.add_argument("-range", "--range_value", help="range of random state", default=2019, type=int )
parser.add_argument("-csv", "--csv_file", help="csv file used for storing vector and imagename", default="map.csv", type=str)
parser.add_argument("-dir", "--results_dir", help="results dir used for storing animation gif", default="results_dir", type=str)
parser.add_argument("-num","--number", help="how many images should be generated", default=100, type=int)
parser.add_argument("--generate", action="store_true")
args = parser.parse_args()
if args.generate:
csv_list = []
# Initialize TensorFlow.
tflib.init_tf()
images_dir = args.results_dir
os.makedirs(images_dir, exist_ok=True)
rnd = np.random.RandomState(int(time.time()))
model_path = args.pth_path
with open(model_path,"rb") as f:
_G, _D, Gs = pickle.load(f)
Gs.print_layers()
fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True)
for index in range(1, args.number):
latent_input = rnd.randn(1, Gs.input_shape[1])
image = Gs.run(latent_input, None, truncation_psi=1, randomize_noise=False, output_transform=fmt)
png_filename = os.path.join(images_dir, str("%05d"%(index))+'.png')
PIL.Image.fromarray(image[0], 'RGB').save(png_filename)
csv_list.append([png_filename, latent_input])
pd.DataFrame(csv_list).to_csv(os.path.join(args.results_dir, args.csv_file), header=None, index=False)
else:
animation_results = args.results_dir
os.makedirs(animation_results, exist_ok=True)
csv_list = []
tflib.init_tf()
model_path = args.pth_path
with open(model_path,"rb") as f:
_G, _D, Gs = pickle.load(f)
Gs.print_layers()
fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True)
for r_value in range(1, args.range_value + 1):
dir_name = os.path.join(args.results_dir, "animation" + "_" + str(r_value))
if not os.path.exists(dir_name):
os.makedirs(dir_name)
rnd = np.random.RandomState(int(time.time()))
latent_vector1 = rnd.randn(1, Gs.input_shape[1])
latent_vector2 = rnd.randn(1, Gs.input_shape[1])
number_of_frames = 240
frame_step = 1.0/number_of_frames
x = 0
for frame_count in range(1,number_of_frames):
x = x + frame_step
latent_input = latent_vector1.copy()
for i in range(512):
f1 = latent_vector1[0][i]
f2 = latent_vector2[0][i]
if f1 > f2:
tmp = f2
f2 = f1
f1 = tmp
fnew = f1 + (f2-f1)*x
latent_input[0][i] = fnew
images = Gs.run(latent_input, None, truncation_psi=1, randomize_noise=False, output_transform=fmt)
# Save image.
# os.makedirs(config.result_dir, exist_ok=True)
png_filename = os.path.join(dir_name, str("%05d"%frame_count)+'.png')
PIL.Image.fromarray(images[0], 'RGB').save(png_filename)
csv_list.append([png_filename, latent_input])
os.system("convert " + dir_name + "/*.png " + animation_results + "/" + str(r_value) + ".gif")
pd.DataFrame(csv_list).to_csv(os.path.join(args.results_dir, args.csv_file), header=None, index=False)
if __name__ == "__main__":
main()