train.py 10.7 KB
Newer Older
H
hypox64 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import os
import numpy as np
import cv2
import random
import torch
import torch.nn as nn
import time

import sys
sys.path.append("..")
sys.path.append("../..")
from util import mosaic,util,ffmpeg,filt,data
from util import image_processing as impro
from cores import Options
H
hypox64 已提交
15
from models import pix2pix_model,pix2pixHD_model,video_model,unet_model,loadmodel
H
hypox64 已提交
16 17 18 19 20
from matplotlib import pyplot as plt
import torch.backends.cudnn as cudnn

N = 25
ITER = 10000000
H
hypox64 已提交
21
LR = 0.0002
H
hypox64 已提交
22 23
beta1 = 0.5
use_gpu = True
H
hypox64 已提交
24
use_gan = False
H
hypox64 已提交
25
use_L2 = False
H
hypox64 已提交
26
CONTINUE =  True
H
hypox64 已提交
27
lambda_L1 = 100.0
H
hypox64 已提交
28
lambda_gan = 0.5
H
hypox64 已提交
29 30 31

SAVE_FRE = 10000
start_iter = 0
H
hypox64 已提交
32 33
finesize = 256
loadsize = int(finesize*1.2)
H
hypox64 已提交
34
batchsize = 6
H
hypox64 已提交
35
perload_num = 16
H
hypox64 已提交
36 37
# savename = 'MosaicNet_instance_gan_256_hdD'
savename = 'MosaicNet_instance_test'
H
hypox64 已提交
38 39 40 41 42 43 44 45 46 47 48
dir_checkpoint = 'checkpoints/'+savename
util.makedirs(dir_checkpoint)

loss_sum = [0.,0.,0.,0.]
loss_plot = [[],[]]
item_plot = []

opt = Options().getparse()
videos = os.listdir('./dataset')
videos.sort()
lengths = []
H
hypox64 已提交
49
print('check dataset...')
H
hypox64 已提交
50 51 52 53 54 55
for video in videos:
    video_images = os.listdir('./dataset/'+video+'/ori')
    lengths.append(len(video_images))
#unet_128
#resnet_9blocks
#netG = pix2pix_model.define_G(3*N+1, 3, 128, 'resnet_6blocks', norm='instance',use_dropout=True, init_type='normal', gpu_ids=[])
H
hypox64 已提交
56
netG = video_model.MosaicNet(3*N+1, 3, norm='instance')
H
HypoX64 已提交
57
loadmodel.show_paramsnumber(netG,'netG')
H
hypox64 已提交
58 59
# netG = unet_model.UNet(3*N+1, 3)
if use_gan:
H
hypox64 已提交
60
    netD = pix2pixHD_model.define_D(6, 64, 3, norm='instance', use_sigmoid=False, num_D=2)
H
hypox64 已提交
61
    #netD = pix2pix_model.define_D(3*2+1, 64, 'pixel', norm='instance')
H
hypox64 已提交
62 63
    #netD = pix2pix_model.define_D(3*2, 64, 'basic', norm='instance')
    #netD = pix2pix_model.define_D(3*2+1, 64, 'n_layers', n_layers_D=5, norm='instance')
H
hypox64 已提交
64 65

if CONTINUE:
H
hypox64 已提交
66 67 68 69
    if not os.path.isfile(os.path.join(dir_checkpoint,'last_G.pth')):
        CONTINUE = False
        print('can not load last_G, training on init weight.')
if CONTINUE:     
H
hypox64 已提交
70 71 72 73 74 75 76 77 78 79 80 81
    netG.load_state_dict(torch.load(os.path.join(dir_checkpoint,'last_G.pth')))
    if use_gan:
        netD.load_state_dict(torch.load(os.path.join(dir_checkpoint,'last_D.pth')))
    f = open(os.path.join(dir_checkpoint,'iter'),'r')
    start_iter = int(f.read())
    f.close()

optimizer_G = torch.optim.Adam(netG.parameters(), lr=LR,betas=(beta1, 0.999))
criterion_L1 = nn.L1Loss()
criterion_L2 = nn.MSELoss()
if use_gan:
    optimizer_D = torch.optim.Adam(netG.parameters(), lr=LR,betas=(beta1, 0.999))
H
hypox64 已提交
82 83 84
    # criterionGAN = pix2pix_model.GANLoss(gan_mode='lsgan').cuda()
    criterionGAN = pix2pixHD_model.GANLoss(tensor=torch.cuda.FloatTensor)
    netD.train()
H
hypox64 已提交
85

H
hypox64 已提交
86 87 88 89 90 91
if use_gpu:
    netG.cuda()
    if use_gan:
        netD.cuda()
        criterionGAN.cuda()
    cudnn.benchmark = True
H
hypox64 已提交
92 93 94 95 96

def loaddata():
    video_index = random.randint(0,len(videos)-1)
    video = videos[video_index]
    img_index = random.randint(N,lengths[video_index]- N)
H
hypox64 已提交
97
    input_img = np.zeros((loadsize,loadsize,3*N+1), dtype='uint8')
H
hypox64 已提交
98
    for i in range(0,N):
H
HypoX64 已提交
99
    
H
hypox64 已提交
100
        img = cv2.imread('./dataset/'+video+'/mosaic/output_'+'%05d'%(img_index+i-int(N/2))+'.png')
H
hypox64 已提交
101
        img = impro.resize(img,loadsize)
H
hypox64 已提交
102 103
        input_img[:,:,i*3:(i+1)*3] = img
    mask = cv2.imread('./dataset/'+video+'/mask/output_'+'%05d'%(img_index)+'.png',0)
H
hypox64 已提交
104
    mask = impro.resize(mask,loadsize)
H
hypox64 已提交
105 106 107 108
    mask = impro.mask_threshold(mask,15,128)
    input_img[:,:,-1] = mask

    ground_true = cv2.imread('./dataset/'+video+'/ori/output_'+'%05d'%(img_index)+'.png')
H
hypox64 已提交
109
    ground_true = impro.resize(ground_true,loadsize)
H
hypox64 已提交
110

H
HypoX64 已提交
111
    input_img,ground_true = data.random_transform_video(input_img,ground_true,finesize,N)
H
hypox64 已提交
112 113
    input_img = data.im2tensor(input_img,bgr2rgb=False,use_gpu=opt.use_gpu,use_transform = False,is0_1=False)
    ground_true = data.im2tensor(ground_true,bgr2rgb=False,use_gpu=opt.use_gpu,use_transform = False,is0_1=False)
H
hypox64 已提交
114 115 116 117
    
    return input_img,ground_true

print('preloading data, please wait 5s...')
H
hypox64 已提交
118 119 120 121 122

if perload_num <= batchsize:
    perload_num = batchsize*2
input_imgs = torch.rand(perload_num,N*3+1,finesize,finesize).cuda()
ground_trues = torch.rand(perload_num,3,finesize,finesize).cuda()
H
hypox64 已提交
123
load_cnt = 0
H
hypox64 已提交
124

H
hypox64 已提交
125
def preload():
H
hypox64 已提交
126
    global load_cnt   
H
hypox64 已提交
127 128
    while 1:
        try:
H
hypox64 已提交
129
            ran = random.randint(0, perload_num-1)
H
hypox64 已提交
130
            input_imgs[ran],ground_trues[ran] = loaddata()
H
hypox64 已提交
131
            load_cnt += 1
H
hypox64 已提交
132 133 134 135 136 137 138 139
            # time.sleep(0.1)
        except Exception as e:
            print("error:",e)

import threading
t = threading.Thread(target=preload,args=())  #t为新创建的线程
t.daemon = True
t.start()
H
hypox64 已提交
140 141 142

time_start=time.time()
while load_cnt < perload_num:
H
hypox64 已提交
143
    time.sleep(0.1)
H
hypox64 已提交
144 145 146
time_end=time.time()
print('load speed:',round((time_end-time_start)/perload_num,3),'s/it')

H
hypox64 已提交
147

H
hypox64 已提交
148 149
util.copyfile('./train.py', os.path.join(dir_checkpoint,'train.py'))
util.copyfile('../../models/video_model.py', os.path.join(dir_checkpoint,'model.py'))
H
hypox64 已提交
150 151 152 153 154
netG.train()
time_start=time.time()
print("Begin training...")
for iter in range(start_iter+1,ITER):

H
hypox64 已提交
155 156 157
    ran = random.randint(0, perload_num-batchsize-1)
    inputdata = input_imgs[ran:ran+batchsize].clone()
    target = ground_trues[ran:ran+batchsize].clone()
H
hypox64 已提交
158 159

    if use_gan:
H
hypox64 已提交
160 161 162 163 164 165 166
        # compute fake images: G(A)
        pred = netG(inputdata)
        # update D
        pix2pix_model.set_requires_grad(netD,True)
        optimizer_D.zero_grad()
        # Fake
        real_A = inputdata[:,int((N-1)/2)*3:(int((N-1)/2)+1)*3,:,:]
H
hypox64 已提交
167 168 169
        fake_AB = torch.cat((real_A, pred), 1)
        pred_fake = netD(fake_AB.detach())
        loss_D_fake = criterionGAN(pred_fake, False)
H
hypox64 已提交
170
        # Real
H
hypox64 已提交
171
        real_AB = torch.cat((real_A, target), 1)
H
hypox64 已提交
172 173
        pred_real = netD(real_AB)
        loss_D_real = criterionGAN(pred_real, True)
H
hypox64 已提交
174
        # combine loss and calculate gradients
H
hypox64 已提交
175 176 177
        loss_D = (loss_D_fake + loss_D_real) * 0.5
        loss_sum[2] += loss_D_fake.item()
        loss_sum[3] += loss_D_real.item()
H
hypox64 已提交
178
        # udpate D's weights
H
hypox64 已提交
179 180 181
        loss_D.backward()
        optimizer_D.step()

H
hypox64 已提交
182 183 184 185 186
        # update G
        pix2pix_model.set_requires_grad(netD,False)
        optimizer_G.zero_grad()
        # First, G(A) should fake the discriminator
        real_A = inputdata[:,int((N-1)/2)*3:(int((N-1)/2)+1)*3,:,:]
H
hypox64 已提交
187 188 189 190 191
        fake_AB = torch.cat((real_A, pred), 1)
        pred_fake = netD(fake_AB)
        loss_G_GAN = criterionGAN(pred_fake, True)*lambda_gan
        # Second, G(A) = B
        if use_L2:
H
hypox64 已提交
192
            loss_G_L1 = (criterion_L1(pred, target)+criterion_L2(pred, target)) * lambda_L1
H
hypox64 已提交
193
        else:
H
hypox64 已提交
194
            loss_G_L1 = criterion_L1(pred, target) * lambda_L1
H
hypox64 已提交
195 196 197 198
        # combine loss and calculate gradients
        loss_G = loss_G_GAN + loss_G_L1
        loss_sum[0] += loss_G_L1.item()
        loss_sum[1] += loss_G_GAN.item()
H
hypox64 已提交
199
        # udpate G's weights
H
hypox64 已提交
200 201 202 203
        loss_G.backward()
        optimizer_G.step()

    else:
H
hypox64 已提交
204
        pred = netG(inputdata)
H
hypox64 已提交
205
        if use_L2:
H
hypox64 已提交
206
            loss_G_L1 = (criterion_L1(pred, target)+criterion_L2(pred, target)) * lambda_L1
H
hypox64 已提交
207
        else:
H
hypox64 已提交
208
            loss_G_L1 = criterion_L1(pred, target) * lambda_L1
H
hypox64 已提交
209 210 211 212 213 214 215 216
        loss_sum[0] += loss_G_L1.item()

        optimizer_G.zero_grad()
        loss_G_L1.backward()
        optimizer_G.step()

    if (iter+1)%100 == 0:
        try:
H
hypox64 已提交
217 218
            data.showresult(inputdata[:,int((N-1)/2)*3:(int((N-1)/2)+1)*3,:,:],
             target, pred,os.path.join(dir_checkpoint,'result_train.png'))
H
hypox64 已提交
219 220 221 222 223 224
        except Exception as e:
            print(e)
     
    if (iter+1)%1000 == 0:
        time_end = time.time()
        if use_gan:
H
hypox64 已提交
225 226
            print('iter:',iter+1,' L1_loss:', round(loss_sum[0]/1000,4),' G_loss:', round(loss_sum[1]/1000,4),
                ' D_f:',round(loss_sum[2]/1000,4),' D_r:',round(loss_sum[3]/1000,4),' time:',round((time_end-time_start)/1000,2))
H
hypox64 已提交
227 228 229 230 231 232 233 234 235 236 237 238
            if (iter+1)/1000 >= 10:
                loss_plot[0].append(loss_sum[0]/1000)
                loss_plot[1].append(loss_sum[1]/1000)
                item_plot.append(iter+1)
                try:
                    plt.plot(item_plot,loss_plot[0])
                    plt.plot(item_plot,loss_plot[1])
                    plt.savefig(os.path.join(dir_checkpoint,'loss.png'))
                    plt.close()
                except Exception as e:
                    print("error:",e)
        else:
H
hypox64 已提交
239
            print('iter:',iter+1,' L1_loss:',round(loss_sum[0]/1000,4),' time:',round((time_end-time_start)/1000,2))
H
hypox64 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
            if (iter+1)/1000 >= 10:
                loss_plot[0].append(loss_sum[0]/1000)
                item_plot.append(iter+1)
                try:
                    plt.plot(item_plot,loss_plot[0])
                    plt.savefig(os.path.join(dir_checkpoint,'loss.png'))
                    plt.close()
                except Exception as e:
                    print("error:",e)
        loss_sum = [0.,0.,0.,0.]
        time_start=time.time()


    if (iter+1)%SAVE_FRE == 0:
        if iter+1 != SAVE_FRE:
            os.rename(os.path.join(dir_checkpoint,'last_G.pth'),os.path.join(dir_checkpoint,str(iter+1-SAVE_FRE)+'G.pth'))
        torch.save(netG.cpu().state_dict(),os.path.join(dir_checkpoint,'last_G.pth'))
        if use_gan:
            if iter+1 != SAVE_FRE:
                os.rename(os.path.join(dir_checkpoint,'last_D.pth'),os.path.join(dir_checkpoint,str(iter+1-SAVE_FRE)+'D.pth'))
            torch.save(netD.cpu().state_dict(),os.path.join(dir_checkpoint,'last_D.pth'))
        if use_gpu:
            netG.cuda()
            if use_gan:
                netD.cuda()
        f = open(os.path.join(dir_checkpoint,'iter'),'w+')
        f.write(str(iter+1))
        f.close()
        print('network saved.')

        #test
        netG.eval()
H
hypox64 已提交
272
        
H
hypox64 已提交
273
        test_names = os.listdir('./test')
H
hypox64 已提交
274
        test_names.sort()
H
hypox64 已提交
275
        result = np.zeros((finesize*2,finesize*len(test_names),3), dtype='uint8')
H
hypox64 已提交
276 277 278

        for cnt,test_name in enumerate(test_names,0):
            img_names = os.listdir(os.path.join('./test',test_name,'image'))
H
HypoX64 已提交
279
            img_names.sort()
H
hypox64 已提交
280
            inputdata = np.zeros((finesize,finesize,3*N+1), dtype='uint8')
H
hypox64 已提交
281 282
            for i in range(0,N):
                img = impro.imread(os.path.join('./test',test_name,'image',img_names[i]))
H
hypox64 已提交
283
                img = impro.resize(img,finesize)
H
hypox64 已提交
284
                inputdata[:,:,i*3:(i+1)*3] = img
H
hypox64 已提交
285 286

            mask = impro.imread(os.path.join('./test',test_name,'mask.png'),'gray')
H
hypox64 已提交
287
            mask = impro.resize(mask,finesize)
H
hypox64 已提交
288
            mask = impro.mask_threshold(mask,15,128)
H
hypox64 已提交
289 290 291 292
            inputdata[:,:,-1] = mask
            result[0:finesize,finesize*cnt:finesize*(cnt+1),:] = inputdata[:,:,int((N-1)/2)*3:(int((N-1)/2)+1)*3]
            inputdata = data.im2tensor(inputdata,bgr2rgb=False,use_gpu=opt.use_gpu,use_transform = False,is0_1 = False)
            pred = netG(inputdata)
H
hypox64 已提交
293
 
H
hypox64 已提交
294
            pred = data.tensor2im(pred,rgb2bgr = False, is0_1 = False)
H
hypox64 已提交
295
            result[finesize:finesize*2,finesize*cnt:finesize*(cnt+1),:] = pred
H
hypox64 已提交
296 297

        cv2.imwrite(os.path.join(dir_checkpoint,str(iter+1)+'_test.png'), result)
H
hypox64 已提交
298
        netG.train()