DCGAN生成目標訓練圖片


前言:

GAN的原理很簡單,但是它有很多變體,如:DCGAN、CycleGAN、DeblurGAN等,它們也被用在不同地方,本文將用到DCGAN來生成頭像圖片,可以做到以假亂真的地步。

1.首先調用程序對圖片進行標准化

代碼如下:

from skimage import io,transform,color
import numpy as np
​
def convert_gray(f,**args):
    """
    將彩色圖片轉換為灰度圖片和調整大小,改變圖像分辨率
    :return:
    """
    rgb = io.imread(f)
    # gray = color.rgb2gray(rgb)  #
    dst = transform.resize(rgb, (96, 96))  # 由於在后期測試的時候用的圖片尺寸是96x96
    
    return dst
​
datapath='your train path'
str=datapath+'/*.jpg'   #識別.jpg的圖像
coll = io.ImageCollection(str,load_func=convert_gray)#批處理
for i in range(len(coll)):
    io.imsave(r'your save paths'+np.str(i)+'.jpg',coll[i])

 

2.調用程序

  • 訓練圖像 代碼只能引用DCGAN的github代碼:carpedm20/DCGAN-tensorflow

  • 調用命令:

    python main.py --input_height 96 --input_width 96 --output_height 48 --output_width 48 --dataset faces --crop --train --epoch 300 --input_fname_pattern "*.jpg"

     

     

3. 切割圖片

由於生成的圖片是由64張小尺寸圖片拼接成一整張的,故需要進行對圖片切割。

切割代碼如下:

# encoding:utf-8
from PIL import Image
import sys
import math
import os
​
def fill_image(image):
    """
    將圖片填充為正方形
    :param image:
    :return:
    """
    width, height = image.size
    #選取長和寬中較大值作為新圖片的
    new_image_length = width if width > height else height
    #生成新圖片[白底]
    new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white')
    #將之前的圖粘貼在新圖上,居中
    if width > height:#原圖寬大於高,則填充圖片的豎直維度
        #(x,y)二元組表示粘貼上圖相對下圖的起始位置
        new_image.paste(image, (0, int((new_image_length - height) / 2)))
    else:
        new_image.paste(image,(int((new_image_length - width) / 2),0))
​
    return new_image
​
​
def cut_image(image,cut_num):
    """
    切圖
    :param image:
    :return:
    """
    flag_value = int(math.sqrt(cut_num))
    width, height = image.size
    item_width = int(width / flag_value)
    box_list = []
    for i in range(0,flag_value):
        for j in range(0,flag_value):
            box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width)
            box_list.append(box)
    image_list = [image.crop(box) for box in box_list]
​
    return image_list
​
​
def save_images(image_list):
    """
    保存
    :param image_list:
    :return:
    """
    index = 1
    dirs = './img_add/'
    if not os.path.exists(dirs):
        os.makedirs(dirs)
    for image in image_list:
        image.save(dirs+str(index) + '.png', 'PNG')
        index += 1def main(file_path,batch_size):
​
    image = Image.open(file_path)
    image = fill_image(image)
    image_list = cut_image(image,batch_size)
    save_images(image_list)
​
if __name__ == '__main__':
    batch_size = 64
    file_path = "train.png"  # 圖片路徑
    main(file_path,batch_size)

 



參考鏈接:https://blog.csdn.net/qq_34739497/article/details/79902356


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM