美文网首页
stylegan生成循环gif图片

stylegan生成循环gif图片

作者: 狼无雨雪 | 来源:发表于2019-06-11 17:54 被阅读0次

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()


相关文章

  • stylegan生成循环gif图片

    style参考地址:https://github.com/NVlabs/stylegan生成gif参考地址:htt...

  • GIF图片的播放和生成

    首先需要导入头文件 GIF图片的播放 GIF图片的生成

  • 使用pillow将文件夹内静态图合成gif

    首先采用循环读取文件夹内文件的方法,找到文件夹内所有图片文件。 后续生成gif的方法参考了python图片生成gi...

  • iOS Gif图片加载

    Gif图片如越来越受欢迎,移动端对它的支持也是有些知识点的,主要是加载图片性能优化 Gif图片的生成 Gif图片是...

  • 【python实战】生成个性二维码

    一、需求 根据现有的网址、图片或gif,生成二维码,其中,包括根据多张图片生成gif动图,简单易学,上手就会! 二...

  • Mac中的GIF

    为IOS模拟器生成GIF图片 安装GIF神器:GIF Brewery 3 安装成功后打开GIF Brewery 3...

  • GIF

    imageIO介绍image解压缩图片帧延迟设置bridge gif生成 gif解析

  • JAVA实现多张PNG生成GIF图片

    依赖下载 animated-gif-lib-1.4.jar 多张PNG图片生成GIF图片算法(可抽帧压缩) 把PN...

  • ImageMagick操作之动态图像生成

    ImageMagick操作之动态图像生成 1、简单gif图片制作(10_1.gif) 图片依次出现,不消失。指定每...

  • MAC制作GIF及设置GIF循环播放

    需求:在Mac电脑中录制操作,并生成GIF文件。GIF文件需要循环播放。 工具选择 Recordit,7.2M大小...

网友评论

      本文标题:stylegan生成循环gif图片

      本文链接:https://www.haomeiwen.com/subject/qlccfctx.html