make_pix2pix_dataset.py 7.4 KB
Newer Older
H
hypox64 已提交
1 2
import os
import sys
H
hypox64 已提交
3 4 5 6 7
sys.path.append("..")
from cores import Options
opt = Options()

import random
H
hypox64 已提交
8 9 10 11 12 13 14
import datetime
import time
import warnings
warnings.filterwarnings(action='ignore')

import numpy as np
import cv2
H
hypox64 已提交
15
import torch
H
hypox64 已提交
16 17 18

from models import runmodel,loadmodel
import util.image_processing as impro
H
hypox64 已提交
19
from util import degradater, util,mosaic,data
H
hypox64 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63


opt.parser.add_argument('--datadir',type=str,default='../datasets/draw/face', help='')
opt.parser.add_argument('--savedir',type=str,default='../datasets/pix2pix/face', help='')
opt.parser.add_argument('--name',type=str,default='', help='save name')
opt.parser.add_argument('--mod',type=str,default='drawn', help='drawn | network | irregular | drawn,irregular | network,irregular')
opt.parser.add_argument('--square', action='store_true', help='if specified, crop to square')
opt.parser.add_argument('--irrholedir',type=str,default='../datasets/Irregular_Holes_mask', help='')  
opt.parser.add_argument('--hd', action='store_true', help='if false make dataset for pix2pix, if Ture for pix2pix_HD')
opt.parser.add_argument('--savemask', action='store_true', help='if specified,save mask')
opt.parser.add_argument('--outsize', type=int ,default= 512,help='')
opt.parser.add_argument('--fold', type=int ,default= 1,help='')
opt.parser.add_argument('--start', type=int ,default= 0,help='')
opt.parser.add_argument('--minsize', type=int ,default= 128,help='when [square], minimal roi size')
opt.parser.add_argument('--quality', type=int ,default= 40,help='when [square], minimal quality')

opt = opt.getparse()

util.makedirs(opt.savedir)
util.writelog(os.path.join(opt.savedir,'opt.txt'), 
              str(time.asctime(time.localtime(time.time())))+'\n'+util.opt2str(opt))
opt.mod = (opt.mod).split(',')

#save dir
if opt.hd:
    train_A_path = os.path.join(opt.savedir,'train_A')
    train_B_path = os.path.join(opt.savedir,'train_B')
    util.makedirs(train_A_path)
    util.makedirs(train_B_path)
else:
    train_path = os.path.join(opt.savedir,'train')
    util.makedirs(train_path)
if opt.savemask:
    mask_save_path = os.path.join(opt.savedir,'mask')
    util.makedirs(mask_save_path)

#read dir
if 'drawn' in opt.mod:
    imgpaths = util.Traversal(os.path.join(opt.datadir,'origin_image'))
    imgpaths.sort()
    maskpaths = util.Traversal(os.path.join(opt.datadir,'mask'))
    maskpaths.sort()
if 'network' in opt.mod or 'irregular' in opt.mod:
    imgpaths = util.Traversal(opt.datadir)
H
hypox64 已提交
64
    imgpaths = util.is_imgs(imgpaths)
H
hypox64 已提交
65 66 67 68 69
    random.shuffle (imgpaths)
if 'irregular' in opt.mod:
    irrpaths = util.Traversal(opt.irrholedir)


H
hypox64 已提交
70
#def network                
H
hypox64 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
if 'network' in opt.mod:
    net = loadmodel.bisenet(opt,'roi')

print('Find images:',len(imgpaths))
starttime = datetime.datetime.now()
filecnt = 0
savecnt = opt.start
for fold in range(opt.fold):
    for i in range(len(imgpaths)):
        filecnt += 1
        try:
            # load image and get mask
            img = impro.imread(imgpaths[i])
            if 'drawn' in opt.mod:
                mask_drawn = impro.imread(maskpaths[i],'gray')
                mask_drawn = impro.resize_like(mask_drawn, img)
                mask = mask_drawn
            if 'irregular' in opt.mod:
                mask_irr = impro.imread(irrpaths[random.randint(0,12000-1)],'gray')
H
BVDNet  
hypox64 已提交
90
                mask_irr = data.random_transform_single_mask(mask_irr, (img.shape[0],img.shape[1]))
H
hypox64 已提交
91 92 93
                mask = mask_irr
            if 'network' in opt.mod:
                mask_net = runmodel.get_ROI_position(img,net,opt,keepsize=True)[0]
94
                if opt.gpu_id != -1:
H
hypox64 已提交
95
                    torch.cuda.empty_cache()
H
hypox64 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108
                if not opt.all_mosaic_area:
                    mask_net = impro.find_mostlikely_ROI(mask_net)
                mask = mask_net
            if opt.mod == ['drawn','irregular']:
                mask = cv2.bitwise_and(mask_irr, mask_drawn)
            if opt.mod == ['network','irregular']:
                mask = cv2.bitwise_and(mask_irr, mask_net)

                #checkandsave
                # t=threading.Thread(target=checksaveimage,args=(opt,img,mask,))
                # t.start()

                saveflag = True
H
HypoX64 已提交
109
                if opt.mod == ['drawn','irregular']:
H
hypox64 已提交
110
                    x,y,size,area = impro.boundingSquare(mask_drawn, random.uniform(1.1,1.6))
H
HypoX64 已提交
111
                elif opt.mod == ['network','irregular']:
H
hypox64 已提交
112
                    x,y,size,area = impro.boundingSquare(mask_net, random.uniform(1.1,1.6))
H
HypoX64 已提交
113
                else:
H
hypox64 已提交
114
                    x,y,size,area = impro.boundingSquare(mask, random.uniform(1.1,1.6))
H
HypoX64 已提交
115

H
hypox64 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
                if area < 1000:
                    saveflag = False
                else:
                    if opt.square:
                        if size < opt.minsize:
                            saveflag = False
                        else:
                            img = impro.resize(img[y-size:y+size,x-size:x+size],opt.outsize,interpolation=cv2.INTER_CUBIC)
                            mask =  impro.resize(mask[y-size:y+size,x-size:x+size],opt.outsize,interpolation=cv2.INTER_CUBIC)
                            if impro.Q_lapulase(img)<opt.quality:
                                saveflag = False         
                    else:
                        img = impro.resize(img,opt.outsize,interpolation=cv2.INTER_CUBIC)
                
                if saveflag:
                    # add mosaic
                    img_mosaic = mosaic.addmosaic_random(img, mask)
H
hypox64 已提交
133
                    # random degradater
H
hypox64 已提交
134
                    if random.random()>0.5:
H
hypox64 已提交
135 136 137 138 139 140 141
                        degradate_params = degradater.get_random_degenerate_params(mod='weaker_2')
                        img = degradater.degradate(img,degradate_params)
                        img_mosaic = degradater.degradate(img_mosaic,degradate_params)
                    # if random.random()>0.5:
                    #     Q = random.randint(1,15)
                    #     img = impro.dctblur(img,Q)
                    #     img_mosaic = impro.dctblur(img_mosaic,Q)
H
hypox64 已提交
142

H
hypox64 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
                    savecnt += 1

                    if opt.hd:
                        cv2.imwrite(os.path.join(train_A_path,opt.name+'%06d' % savecnt+'.jpg'), img_mosaic)
                        cv2.imwrite(os.path.join(train_B_path,opt.name+'%06d' % savecnt+'.jpg'), img)
                    else:
                        merge_img = impro.makedataset(img_mosaic, img)
                        cv2.imwrite(os.path.join(train_path,opt.name+'%06d' % savecnt+'.jpg'), merge_img)
                    if opt.savemask:
                        cv2.imwrite(os.path.join(mask_save_path,opt.name+'%06d' % savecnt+'.png'), mask)
                
                # print("Processing:",imgpaths[i]," ","Remain:",len(imgpaths)*opt.fold-filecnt)
                # cv2.namedWindow('image', cv2.WINDOW_NORMAL)
                # cv2.imshow('image',img_mosaic)
                # cv2.waitKey(0)
                # cv2.destroyAllWindows()   
        except Exception as e:
            print(imgpaths[i],e)
        if filecnt%10==0:
            endtime = datetime.datetime.now()
            # used_time = (endtime-starttime).seconds
            used_time = (endtime-starttime).seconds
            all_length = len(imgpaths)*opt.fold 
            percent = round(100*filecnt/all_length,1)
            all_time = used_time/filecnt*all_length

            print('\r','',str(filecnt)+'/'+str(all_length)+' ',
H
hypox64 已提交
170
                util.get_bar(percent,25),'',
H
hypox64 已提交
171 172
                util.second2stamp(used_time)+'/'+util.second2stamp(all_time),
                'f:'+str(savecnt),end= " ")