【多图像展示】仿照StyleGAN1层次化展示不同大小图片

代码出处https://github.com/NVlabs/stylegan/blob/master/generate_figures.py
在这里插入图片描述

本文代码

参数含义

  • cx=0 , 图片展示的起始x坐标
  • cy=0 , 图片展示的起始y坐标
  • cw=512 原始图片的宽度,展示图片的最大宽度,后续以2的阶乘缩小
  • ch=1024 原始单张图片的高度,展示图片的最大高度,后续以2的阶乘缩小
  • rows=1 生成多少行图片,以原始的高度为1行
  • lods=[0,0,1,1,2,2,3,3],表示每列图片宽度大小在原始图片上缩小的2的阶乘倍数,计算公式,见 cw // 2**lod for lod in lods,计算结果为为(1024,1024,,512,512,256,256),可自由定制每一列的图片的宽度,以及多少列。
  • save_path, 多张图合成一张图的保存路径
  • single_img_input_dir: 需要展示单个文件夹输入路径
# -*- coding: utf-8 -*-
# @Time : 2022/9/26 12:21

import os

import PIL.Image


def get_dir_imgs_path(single_img_input_dir):
    IMAGES_FORMAT = ['.jpg', '.JPG', 'PNG', '.png', '.jpeg']  # 图片格式
    images_path = [os.path.join(single_img_input_dir,name) for name in (os.listdir(single_img_input_dir)) for item in IMAGES_FORMAT
                   if os.path.splitext(name)[1] == item]
    return images_path


'''
From : https://github.com/NVlabs/stylegan/blob/master/generate_figures.py
生成不同大小的图片::Multi-resolution grid of  result images.
原图: 1024(2^10)  512((2^9))  256(2^8)   128(2^7)  
'''
def draw_uncurated_result_figure(save_path, single_img_input_dir,cx, cy, cw, ch, rows, lods):
    print(save_path)
    # images = Gs.run(latents, None, **synthesis_kwargs) # [seed, y, x, rgb]
    '''
    API: https://pillow.readthedocs.io/en/stable/reference/Image.html#constructing-images
    PIL.Image.new(mode, size, color=0)[source]
    mode – The mode to use for the new image. See: Modes.
    size – A 2-tuple, containing (width, height) in pixels.
    color – What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes (one value per band). When creating RGB images, you can also use color strings as supported by the ImageColor module. If the color is None, the image is not initialised.
    '''
    # 实际,以1024为基础,lods表示要显示的列相对于原大小减少的路径
    canvas = PIL.Image.new('RGB', (sum(cw // 2**lod for lod in lods), ch * rows), 'white')
    print('canvas.size',canvas.size)
    canvas.save(save_path)
    images_path = get_dir_imgs_path(single_img_input_dir)

    # 列号,与每张图片相对大小 =( cw // 2**lod)
    # 逐列填充画布
    i=0
    for col, lod in enumerate(lods):
        #逐行填充同一分辨率的图片
        for row in range(rows * 2**lod):
            #读取一张图片

            image = PIL.Image.open(images_path[i])
            i+=1
            '''
            API:https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.crop
                (left, upper, right, lower) = (20, 20, 100, 100)
                # Here the image "im" is cropped and assigned to new variable im_crop
                im_crop = im.crop((left, upper, right, lower))
                crop (x1,y1,x2,y2)
            '''

            image = image.crop((cx, cy, cx + cw, cy + ch))
            # 将图片resize到基础图片的大小

            image = image.resize((cw // 2**lod, ch // 2**lod), PIL.Image.ANTIALIAS)

            '''
            粘贴图片到画布在指定位置
            Image.paste(im, box=None, mask=None)
            API:https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.paste
            2个参数:左上角坐标(没写的话,默认(0,0)), 4个参数:(左,上,右,下的坐标)
            # 此处
            '''
            canvas.paste(image, (sum(cw // 2**lod for lod in lods[:col]), row * ch // 2**lod))
    print(f' {i+1} images merge into one ')
    canvas.save(save_path)



if __name__ == '__main__':
	save_path='hello_merge_image.png',
	input_single_dir="your_img_dir"
    draw_uncurated_result_figure(save_path,
                                 input_single_dir,
                                ,  cx=0, cy=0, cw=512, ch=1024, rows=1, lods=[0,0,1,1,2,2,3,3])

附录

原参考代码 (无法直接运行)


# Figures 2, 3, 10, 11, 12: Multi-resolution grid of uncurated result images.
def draw_uncurated_result_figure(png, Gs, cx, cy, cw, ch, rows, lods, seed):
    print(png)
    latents = np.random.RandomState(seed).randn(sum(rows * 2**lod for lod in lods), Gs.input_shape[1])
    images = Gs.run(latents, None, **synthesis_kwargs) # [seed, y, x, rgb]

    canvas = PIL.Image.new('RGB', (sum(cw // 2**lod for lod in lods), ch * rows), 'white')
    image_iter = iter(list(images))
    for col, lod in enumerate(lods):
        for row in range(rows * 2**lod):
            image = PIL.Image.fromarray(next(image_iter), 'RGB')
            image = image.crop((cx, cy, cx + cw, cy + ch))
            image = image.resize((cw // 2**lod, ch // 2**lod), PIL.Image.ANTIALIAS)
            canvas.paste(image, (sum(cw // 2**lod for lod in lods[:col]), row * ch // 2**lod))
    canvas.save(png)

def main():
    tflib.init_tf()
    os.makedirs(config.result_dir, exist_ok=True)
    draw_uncurated_result_figure(os.path.join(config.result_dir, 'figure02-uncurated-ffhq.png'), load_Gs(url_ffhq), cx=0, cy=0, cw=1024, ch=1024, rows=3, lods=[0,1,2,2,3,3], seed=5)

原始程序效果图:

出处:StyleGANs:A Style-Based Generator Architecture for Generative Adversarial Networks(论文图2)
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曾小蛙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值