def reference(): opt = TestOptions().parse() # get test options # hard-code some parameters for test opt.num_threads = 0 # test code only supports num_threads = 1 opt.batch_size = 1 # test code only supports batch_size = 1 opt.serial_batches = True # disable data shuffling; comment this line if results on randomly chosen images are needed. opt.no_flip = True # no flip; comment this line if results on flipped images are needed. opt.display_id = -1 # no visdom display; the test code saves the results to a HTML file. dataset = create_dataset(opt) # create a dataset given opt.dataset_mode and other options model = create_model(opt) # create a model given opt.model and other options model.setup(opt) # regular setup: load and print networks; create schedulers # create a website web_dir = os.path.join(opt.results_dir, opt.name, '%s_%s' % (opt.phase, opt.epoch)) # define the website directory webpage = html.HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch)) # test with eval mode. This only affects layers like batchnorm and dropout. # For [pix2pix]: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode. # For [CycleGAN]: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout. if opt.eval: model.eval() for i, data in enumerate(dataset): if i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths if i % 5 == 0: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) webpage.save() # save the HTML
def executeCyclegan(): blockPrint() dataset = create_dataset( opt) # create a dataset given opt.dataset_mode and other options model = create_model( opt) # create a model given opt.model and other options model.setup( opt) # regular setup: load and print networks; create schedulers # test with eval mode. This only affects layers like batchnorm and dropout. # For [pix2pix]: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode. # For [CycleGAN]: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout. if opt.eval: model.eval() enablePrint() for i, data in enumerate(dataset): if i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths # if i % 5 == 0: # save images to an HTML file # print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) webpage.save() # save the HTML
def generate_img(self, data_folder): # test self.opt.dataroot = data_folder data_loader = CreateDataLoader(self.opt) dataset = data_loader.load_data() d_loss = [] g_loss = [] for i, data in enumerate(dataset): #if i >= self.opt.how_many: # break self.model.set_input(data) self.model.no_optimisation_run_through() d = self.model.get_D_loss() g = self.model.get_G_loss() d_loss.append(d) g_loss.append(g) #TODO get loss and return it visuals = self.model.get_current_visuals() img_path = self.model.get_image_paths() #if i % 5 == 0: # print('processing (%04d)-th image... %s' % (i, img_path)) save_images(self.webpage, visuals, img_path, aspect_ratio=self.opt.aspect_ratio, width=self.opt.display_winsize) self.webpage.save() return g_loss, d_loss
def test(cfg): dataset = create_dataset(cfg) # create a dataset given cfg.dataset_mode and other options model = create_model(cfg) # create a model given cfg.model and other options model.setup(cfg) # regular setup: load and print networks; create schedulers # create a website web_dir = os.path.join(cfg.results_dir, cfg.name, '%s_%s' % (cfg.phase, cfg.epoch)) # define the website directory webpage = html.HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (cfg.name, cfg.phase, cfg.epoch)) if cfg.eval: model.eval() ismaster = du.is_master_proc(cfg.NUM_GPUS) num_image = 0 for i, data in enumerate(dataset): model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths # Added by Mia if i % 5 == 0 and ismaster: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) visuals_ones = OrderedDict() for j in range(len(img_path)): img_path_one = [] for label, im_data in visuals.items(): visuals_ones[label] = im_data[j:j+1, :, :, :] img_path_one.append(img_path[j]) save_images(webpage, visuals_ones, img_path_one, aspect_ratio=cfg.aspect_ratio, width=cfg.display_winsize) num_image += 1 visuals_ones.clear() webpage.save() # save the HTML
def main(): opt = TestOptions().parse() opt.no_flip = True opt.batchSize = 1 data_loader = CreateDataLoader(opt) model = SingleGAN() model.initialize(opt) web_dir = os.path.join(opt.results_dir, 'test') webpage = html.HTML(web_dir, 'task {}'.format(opt.name)) for i, data in enumerate(islice(data_loader, opt.how_many)): print('process input image %3.3d/%3.3d' % (i, opt.how_many)) all_images, all_names = model.translation(data) img_path = 'image%3.3i' % i save_images(webpage, all_images, all_names, img_path, None, width=opt.fineSize) webpage.save()
def batchProcess(opt, model, dataset, webpage): for i, data in enumerate(dataset): if i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths if i % 5 == 0: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, name_set, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) webpage.save() # save the HTML
def test(cfg): dataset = create_dataset( cfg) # create a dataset given cfg.dataset_mode and other options model = create_model( cfg) # create a model given cfg.model and other options model.setup( cfg) # regular setup: load and print networks; create schedulers # create a website web_dir = os.path.join( cfg.results_dir, cfg.name, '%s_%s' % (cfg.phase, cfg.epoch)) # define the website directory webpage = html.HTML( web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (cfg.name, cfg.phase, cfg.epoch)) # test with eval mode. This only affects layers like batchnorm and dropout. # For [pix2pix]: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode. # For [CycleGAN]: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout. if cfg.eval: model.eval() ismaster = du.is_master_proc(cfg.NUM_GPUS) fmse_score_list = [] mse_scores = 0 fmse_scores = 0 num_image = 0 for i, data in enumerate(dataset): model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths # Added by Mia if i % 5 == 0 and ismaster: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) visuals_ones = OrderedDict() harmonized = None real = None for j in range(len(img_path)): img_path_one = [] for label, im_data in visuals.items(): visuals_ones[label] = im_data[j:j + 1, :, :, :] img_path_one.append(img_path[j]) save_images(webpage, visuals_ones, img_path_one, aspect_ratio=cfg.aspect_ratio, width=cfg.display_winsize) num_image += 1 visuals_ones.clear() webpage.save() # save the HTML
def processVideo(): # preprocess if (path.exists('results')): shutil.rmtree('results', ignore_errors=True) if (path.exists('datasets')): shutil.rmtree('datasets', ignore_errors=True) os.makedirs('datasets/test') opt = uploadFile() # extract video video = video2Images('datasets/' + fileName + '.mp4', 'datasets/test') centeringAndSave('datasets/test') resizeAllFile('datasets/test') duplicate('datasets/test') # process # opt.dataroot = 'datasets/test' dataset = create_dataset(opt) model = create_model(opt) model.setup(opt) # create a website web_dir = os.path.join(opt.results_dir, opt.name, '{}_{}'.format( opt.phase, opt.epoch)) # define the website directory if opt.load_iter > 0: # load_iter is 0 by default web_dir = '{:s}_iter{:d}'.format(web_dir, opt.load_iter) print('creating web directory', web_dir) webpage = html.HTML( web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch)) if opt.eval: model.eval() for i, data in enumerate(dataset): if i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) # concat each pair image concatPairImage('results/braces2teeth/test_latest/images/', 'results') images2Video('results/concat', 30, fileName) return "Hello"
def main(): opt = TestOptions().parse() opt.is_flip = False opt.batchSize = 1 data_loader = CreateDataLoader(opt) model = create_model(opt) web_dir = os.path.join(opt.results_dir, 'test') webpage = html.HTML(web_dir, 'task {}'.format(opt.exp_name)) for i, data in enumerate(islice(data_loader, opt.how_many)): print('process input image %3.3d/%3.3d' % (i, opt.how_many)) results = model.translation(data) img_path = 'image%3.3i' % i save_images(webpage, results, img_path, None, width=opt.fine_size) webpage.save()
def val(opt, model): opt = make_val_opt(opt) dataset = create_dataset( opt) # create a dataset given opt.dataset_mode and other options # model = create_model(opt) # create a model given opt.model and other options # model.setup(opt) # regular setup: load and print networks; create schedulers web_dir = os.path.join( opt.checkpoints_dir, opt.name, '%s_%s' % (opt.phase, opt.epoch)) # define the website directory webpage = html.HTML( web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch)) model.eval() # create a logging file to store training losses log_name = os.path.join(opt.checkpoints_dir, opt.name, 'val_log.txt') with open(log_name, "a") as log_file: now = time.strftime("%c") log_file.write('================ val acc (%s) ================\n' % now) running_metrics = AverageMeter() for i, data in enumerate(dataset): if i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader score = model.test(val=True) # run inference running_metrics.update(score) visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths if i % 5 == 0: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) if ifSaveImage: save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) score = running_metrics.get_scores() print_current_acc(log_name, epoch, score) if opt.display_id > 0: visualizer.plot_current_acc(epoch, float(epoch_iter) / dataset_size, score) webpage.save() # save the HTML return score[metric_name]
def val(opt, model): opt = make_val_opt(opt) dataset = create_dataset(opt) # 给定opt.dataset_mode和其他选项来创建数据集 # model = create_model(opt) # 给定opt.model和其他选项来创建模型 # model.setup(opt) # 常规设置:加载和打印网络;创建调度程序 web_dir = os.path.join(opt.checkpoints_dir, opt.name, '%s_%s' % (opt.phase, opt.epoch)) # 定义文件目录 webpage = html.HTML( web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch)) model.eval() # 在测试期间将模型设为评估模式 # 创建一个日志文件来存储训练损失 log_name = os.path.join(opt.checkpoints_dir, opt.name, 'val_log.txt') with open(log_name, "a") as log_file: now = time.strftime("%c") log_file.write('================ val acc (%s) ================\n' % now) running_metrics = AverageMeter() for i, data in enumerate(dataset): if i >= opt.num_test: # 仅将我们的模型应用于opt.num_test图片。 break model.set_input(data) # 从数据加载器解压缩数据 score = model.test(val=True) # 运行推断 running_metrics.update(score) visuals = model.get_current_visuals() # 获取图像结果 可视化 img_path = model.get_image_paths() # 获取图像路径 #if i % 5 == 0: # save images to an HTML file #print('processing (%04d)-th image... %s' % (i, img_path)) if ifSaveImage: save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) score = running_metrics.get_scores() print_current_acc(log_name, epoch, score) if opt.display_id > 0: visualizer.plot_current_acc(epoch, float(epoch_iter) / dataset_size, score) webpage.save() # save the HTML return score[metric_name]
def processImage(): # Pre-processing if (path.exists('results')): shutil.rmtree('results') if (path.exists('datasets')): shutil.rmtree('datasets') os.mkdir('datasets') opt = uploadFile() dataset = create_dataset(opt) model = create_model(opt) model.setup(opt) # create a website web_dir = os.path.join(opt.results_dir, opt.name, '{}_{}'.format( opt.phase, opt.epoch)) # define the website directory if opt.load_iter > 0: # load_iter is 0 by default web_dir = '{:s}_iter{:d}'.format(web_dir, opt.load_iter) print('creating web directory', web_dir) webpage = html.HTML( web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch)) if opt.eval: model.eval() for i, data in enumerate(dataset): if i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) with open( "results/braces2teeth/test_latest/images/" + fileName + "_fake.png", "rb") as img_file: my_string = base64.b64encode(img_file.read()) return my_string
def _run_test_loop(model, dataset, webpage=None, iteration_post_hook: Callable = None): """ Args: model: object that extends BaseModel dataset: object that extends BaseDataset webpage: webpage object for saving iteration_post_hook: a function to call at the end of every iteration Returns: """ total = min(len(dataset), opt.max_dataset_size) with tqdm(total=total, unit="img") as pbar: for i, data in enumerate(dataset): if i >= total: break model.set_input(data) # set input model.test() # forward pass image_paths = model.get_image_paths() # ids of the loaded images if webpage: visuals = model.get_current_visuals() save_images(webpage, visuals, image_paths, width=opt.display_winsize) if iteration_post_hook: iteration_post_hook(local=locals()) pbar.update() if webpage: webpage.save()
def run_iterative_gan(dataset, model, opt, web_dir, iterations): if opt.load_iter > 0: # load_iter is 0 by default web_dir = '{:s}_iter{:d}'.format(web_dir, opt.load_iter) print('creating web directory', web_dir) webpage = html.HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch)) # opt.num_test = 130 # For [CycleGAN]: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout. print("Num test", opt.num_test) if opt.eval: model.eval() for i, data in enumerate(dataset): if i >= opt.num_test: # only apply our model to opt.num_test images. break # print(data.keys()) # cur_data = data['A'].to(model.device) # print(cur_data.cpu().numpy().shape) # cur_data = cur_data.cpu().numpy()[0] # axes[0].imshow(np.moveaxis(cur_data, [0, 1, 2], [2, 0, 1])) cur_data = data print(cur_data['A_paths']) # Get the image name to keep things simple while saving cur_path = cur_data['A_paths'] for it in range(iterations): print("Iteration: ", it) model.set_input(cur_data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths # axes[i, it+1].imshow(visuals) cur_data = {'A': visuals['fake'], 'A_paths': cur_path} # Stick to the format it is expecting save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize, iterative=True, it_count=it) # if i % 5 == 0: # save images to an HTML file # print('processing (%04d)-th image... %s' % (i, img_path)) webpage.save() # save the HTML
def get_cycled_data(video_id,label_id): data_input_path = '../../../dataset/rendered_video/output_img/{}'.format(video_id) data_output_path = '../../../dataset/cycled_video/cycled_img' opt = TestOptions().parse() # get test options # hard-code some parameters for test opt.dataroot = data_input_path opt.results_dir = data_output_path opt.checkpoints_dir = '/scr1/system/alpha-robot/script/video_cycle/pytorch-CycleGAN-and-pix2pix/checkpoints/{}'.format(video_id) # opt.checkpoints_dir = '/scr1/system/alpha-robot/script/video_cycle/pytorch-CycleGAN-and-pix2pix/checkpoints/{}'.format('merge') opt.num_threads = 0 # test code only supports num_threads = 1 opt.batch_size = 1 # test code only supports batch_size = 1 opt.serial_batches = True # disable data shuffling; comment this line if results on randomly chosen images are needed. opt.no_flip = True # no flip; comment this line if results on flipped images are needed. opt.display_id = -1 # no visdom display; the test code saves the results to a HTML file. dataset = create_dataset(opt) # create a dataset given opt.dataset_mode and other options model = create_model(opt) # create a model given opt.model and other options model.setup(opt) # regular setup: load and print networks; create schedulers # create a website web_dir = os.path.join(opt.results_dir, opt.name, '%s_%s' % (opt.phase, opt.epoch)) # define the website directory webpage = html.HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch)) # test with eval mode. This only affects layers like batchnorm and dropout. # For [pix2pix]: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode. # For [CycleGAN]: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout. if opt.eval: model.eval() for i, data in enumerate(dataset): if i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths if i % 5 == 0: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) webpage.save() # save the HTML video_id,data_num = select_only_B(data_output_path) with open(os.path.join(data_output_path,'video_list.txt'),'w') as file: file.write('{} {} {}'.format(video_id,data_num,label_id))
def doTest(self): self.setModel() self.setWebpage() self.setDataSet() # test with eval mode. This only affects layers like batchnorm and dropout. # For [pix2pix]: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode. # For [CycleGAN]: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout. if self.opt.eval: self.model.eval() for i, data in enumerate(self.dataset): if i >= self.opt.num_test: # only apply our model to opt.num_test images. break self.model.set_input(data) # unpack data from data loader self.model.test() # run inference visuals = self.model.get_current_visuals() # get image results img_path = self.model.get_image_paths() # get image paths if i % 5 == 0: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) save_images(self.webpage, visuals, img_path, aspect_ratio=self.opt.aspect_ratio, width=self.opt.display_winsize) self.webpage.save() # save the HTML
# sample random z if opt.sync: z_samples = get_random_z(opt) # test stage for i, data in enumerate(islice(dataset, opt.how_many)): model.set_input(data) print('process input image %3.3d/%3.3d' % (i, opt.how_many)) if not opt.sync: z_samples = get_random_z(opt) for nn in range(opt.n_samples + 1): encode_B = nn == 0 and not opt.no_encode _, real_A, fake_B, real_B, _ = model.test_simple( z_samples[nn], encode_real_B=encode_B) if nn == 0: all_images = [real_A, real_B, fake_B] all_names = ['input', 'ground truth', 'encoded'] else: all_images.append(fake_B) all_names.append('random sample%2.2d' % nn) img_path = 'input image%3.3i' % i save_images(webpage, all_images, all_names, img_path, None, width=opt.fineSize) webpage.save()
# fake_A -> Z -> rec_B content_a_B, _ = encode_a2z(fake_A) rec_B = decode_z2b(content_a_B) basename = os.path.basename(name_A[1]) # make dict of output images to be saved to site visuals = OrderedDict() visuals['real_A'] = real_A.data visuals['fake_B'] = fake_B.data visuals['rec_A'] = rec_A.data visuals['real_B'] = real_B.data visuals['fake_A'] = fake_A.data visuals['rec_B'] = rec_B.data img_path = os.path.join(opts.output_folder, basename) save_images(webpage, visuals, img_path, aspect_ratio=1, width=256) webpage.save() # save output_b images #vutils.save_image(outputs_b.data, os.path.join(opts.output_folder, 'output_{}.jpg'.format(basename)), padding=0, normalize=True) # save input images #vutils.save_image(images.data, os.path.join(opts.output_folder, 'input_{}.jpg'.format(basename)), padding=0, normalize=True) # also save rec images #vutils.save_image(recs_a.data, os.path.join(opts.output_folder, 'rec_{}.jpg'.format(basename)), padding=0, normalize=True)
from util import html if __name__ == '__main__': opt = TestOptions().parse() opt.nThreads = 1 # test code only supports nThreads = 1 opt.batchSize = 1 # test code only supports batchSize = 1 opt.serial_batches = True # no shuffle opt.no_flip = True # no flip opt.display_id = -1 # no visdom display data_loader = CreateDataLoader(opt) dataset = data_loader.load_data() model = create_model(opt) model.setup(opt) # create website web_dir = os.path.join(opt.results_dir, opt.name, '%s_%s' % (opt.phase, opt.which_epoch)) webpage = html.HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.which_epoch)) # test for i, data in enumerate(dataset): if i >= opt.how_many: break model.set_input(data) model.test() visuals = model.get_current_visuals() img_path = model.get_image_paths() if i % 5 == 0: print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) webpage.save()
from options.test_options import TestOptions from data import CreateDataLoader from models import create_model from util.visualizer import save_images from util import html if __name__ == '__main__': opt = TestOptions().parse() opt.nThreads = 1 # test code only supports nThreads = 1 opt.batchSize = 1 # test code only supports batchSize = 1 opt.serial_batches = True # no shuffle opt.no_flip = True # no flip opt.display_id = -1 # no visdom display opt.loadSize = 256 opt.fineSize = 256 data_loader = CreateDataLoader(opt) dataset = data_loader.load_data() model = create_model(opt) model.setup(opt) # test for i, data in enumerate(dataset): if i >= opt.how_many: break model.set_input(data) model.test() visuals = model.get_current_visuals() img_path = model.get_image_paths() if i % 5 == 0: print('processing (%04d)-th image... %s' % (i, img_path)) save_images(visuals, img_path, opt.camA, opt.camB, opt.save_root)
def main(style): opt = TestOptions().parse() opt.dataroot = "datasets/own_data/testA" # four styles # opt.name = "style_ink_pretrained" # opt.name = "style_monet_pretrained" # opt.name = "style_cezanne_pretrained" # opt.name = "style_ukiyoe_pretrained" # opt.name = "style_vangogh_pretrained" # set original img size original_img = cv2.imread(opt.dataroot+"/temp.jpg") original_img_shape = tuple([item for item in original_img.shape[:-1]][::-1]) opt.name = "style_%s_pretrained" % style # 不可更改 opt.model = "test" cv2.imread("temp.jpg") opt.nThreads = 1 # test code only supports nThreads = 1 opt.batchSize = 1 # test code only supports batchSize = 1 opt.serial_batches = True # no shuffle opt.no_flip = True # no flip opt.display_id = -1 # no visdom display # need to overwrite 8-27 这边可以不要 data_loader = CreateDataLoader(opt) dataset = data_loader.load_data() # create model model = create_model(opt) model.setup(opt) # create website # website没什么用,但是作者把保存图片写到了web_dir里面了,我就没有修改。 web_dir = os.path.join(opt.results_dir, opt.name, '%s_%s' % (opt.phase, opt.which_epoch)) print("web_dir", web_dir) webpage = html.HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.which_epoch)) print("webpage", webpage) # exit() # test for i, data in enumerate(dataset): # i is index enumerate生成,很简单的 # type of data is dict # one key is A, A is a tensor which size is ([1, 3, 256, 256]), another is A_path which type is str. from the read path (include the name) # i. e. datasets/own_data/testA/2test.jpg # default how_many is 50 : 一个数据集中只能处理 50 张照片 # need to overwrite "data" # data 的形状和其一样,然后外面改写一个监听,应该就可以了 if i >= opt.how_many: break model.set_input(data) model.test() visuals = model.get_current_visuals() img_path = model.get_image_paths() if i % 5 == 0: print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) generate_img = cv2.imread("results/generate_images/" + "temp.png") reshape_generate_img = cv2.resize(generate_img, original_img_shape, interpolation=cv2.INTER_CUBIC) cv2.imwrite("results/generate_images/" + "temp.png", reshape_generate_img)
if not opt.sync: z_samples = get_random_z(opt) for nn in range(opt.n_samples + 1): encode_B = nn == 0 and not opt.no_encode _, real_A, fake_B, real_B = model.test_simple() if nn == 0: all_images = [real_A, real_B, fake_B] all_names = ['input', 'ground truth', 'encoded'] #from skimage import io #io.imshow(real_A) else: all_images.append(fake_B) all_names.append('random sample%2.2d' % nn) img_path = 'input image%3.3i' % i save_images(webpage, all_images, all_names, img_path, None, width=opt.fineSize, aspect_ratio=opt.aspect_ratio) webpage.save() ''' #save test result test_name_dataset = '1K_' if opt.GAN_loss_type == 'wGAN': test_name_GAN_type = 'wGAN_' test_name_loss_info = 'loss_clip_'+str(opt.clipping_value)+'_' elif opt.GAN_loss_type == 'criterionGAN': test_name_GAN_type = 'criterionGAN_' test_name_loss_info = '' # D condition if opt.conditional_D: test_name_cD = 'cD_' else:
for i, data in enumerate(dataset): model.set_input(data) model.forward() model.get_loss() epoch_iter += opt.batch_size gt = model.mask.cpu().int().numpy() _, pred = torch.max(model.output.data.cpu(), 1) pred = pred.float().detach().int().numpy() if dataset.dataset.name() == 'Scannetv2': gt = data["mask_fullsize"].cpu().int().numpy()[0] pred = cv2.resize(pred[0], (gt.shape[1], gt.shape[0]), interpolation=cv2.INTER_NEAREST) if opt.phase == "test": save_scannet_prediction(pred, data['scan'][0], data['path'][0], save_dir) save_images(webpage, model.get_current_visuals(), model.get_image_paths()) conf_mat += confusion_matrix( gt, pred, dataset.dataset.num_labels, ignore_label=dataset.dataset.ignore_label) test_loss_iter.append(model.loss_segmentation.cpu().numpy()) print('Epoch {0:}, iters: {1:}/{2:}, loss: {3:.3f} '.format( opt.epoch, epoch_iter, len(dataset) * opt.batch_size, test_loss_iter[-1]), end='\r') avg_test_loss = np.mean(test_loss_iter) print('Epoch {0:} test loss: {1:.3f} '.format(opt.epoch, avg_test_loss)) glob, mean, iou = getScores(conf_mat)
model.set_input(data) model.test() visuals = model.get_current_visuals() # remove reductant files when outputing if opt.out_all: remove_list = [] for item in visuals: if 'fake_B' not in item: remove_list.append(item) for rm_item in remove_list: del visuals[rm_item] img_path = model.get_image_paths() if i % 5 == 0: logging.info('processing (%04d)-th image...' % (i * opt.batchSize)) if 'mul' in opt.model: save_images(webpage.get_image_dir(), visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize, multi_flag=True) else: save_images(webpage.get_image_dir(), visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize)
# sample random z if opt.sync: z_samples = model.get_z_random(opt.n_samples + 1, opt.nz) # test stage for i, data in enumerate(islice(dataset, opt.how_many)): model.set_input(data) print('process input image %3.3d/%3.3d' % (i, opt.how_many)) if not opt.sync: z_samples = model.get_z_random(opt.n_samples + 1, opt.nz) for nn in range(opt.n_samples + 1): encode = nn == 0 and not opt.no_encode real_A, fake_B, real_B = model.test(z_samples[[nn]], encode=encode) if nn == 0: images = [real_A, real_B, fake_B] names = ['input', 'ground truth', 'encoded'] else: images.append(fake_B) names.append('random_sample%2.2d' % nn) img_path = 'input_%3.3d' % i save_images(webpage, images, names, img_path, aspect_ratio=opt.aspect_ratio, width=opt.fineSize) webpage.save()
if __name__ == '__main__': opt = TestOptions().parse() opt.num_threads = 1 # test code only supports num_threads = 1 opt.batch_size = 1 # test code only supports batch_size = 1 opt.serial_batches = True # no shuffle opt.no_flip = True # no flip opt.display_id = -1 # no visdom display data_loader = CreateDataLoader(opt) dataset = data_loader.load_data() model = create_model(opt) model.setup(opt) # create website web_dir = os.path.join(opt.results_dir, opt.name, '%s_%s' % (opt.phase, opt.epoch)) webpage = html.HTML( web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch)) # test for i, data in enumerate(dataset): if i >= opt.num_test: break model.set_input(data) model.test() visuals = model.get_current_visuals() img_path = model.get_image_paths() if i % 5 == 0: print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio) webpage.save()
if opt.eval: model.eval() for i, data in enumerate(dataset): if not opt.pose_mode and i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths if i % 5 == 0: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize, render=opt.render_pose, keypoints=model.keypoints, animal=opt.which_animal) # whether save the prediction annotation if opt.pose_mode and opt.transfer_anno: pickle.dump(model.target_anno, open(os.path.join(web_dir, 'pred_anno.pth'), 'wb')) else: pickle.dump(model.target_anno, open(os.path.join(web_dir, 'target_anno.pth'), 'wb')) # whether running evaluation (need annotations for test images) if opt.evaluate: test_anno = pickle.load(open(opt.target_anno_dir, 'rb'))
model.setup( opt) # regular setup: load and print networks; create schedulers # create a website web_dir = os.path.join( opt.results_dir, opt.name, '%s_%s' % (opt.phase, opt.epoch)) # define the website directory webpage = html.HTML( web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch)) # test with eval mode. This only affects layers like batchnorm and dropout. # For [pix2pix]: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode. # For [CycleGAN]: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout. if opt.eval: model.eval() for i, data in enumerate(dataset): if i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths if i % 5 == 0: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize, comet_exp=experiment) webpage.save() # save the HTML
train_dataset = create_dataset(util.copyconf(opt, phase="test")) model = create_model( opt) # create a model given opt.model and other options # create a webpage for viewing the results web_dir = os.path.join(opt.results_dir, '{}_{}'.format( opt.phase, opt.epoch)) # define the website directory print('creating web directory', web_dir) webpage = html.HTML( web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.results_dir, opt.phase, opt.epoch)) for i, data in enumerate(dataset): if i == 0: model.data_dependent_initialize(data) model.setup( opt ) # regular setup: load and print networks; create schedulers model.parallelize() if opt.eval: model.eval() if i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths if i % 5 == 0: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, width=opt.display_winsize) webpage.save() # save the HTML
# For [pix2pix]: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode. # For [CycleGAN]: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout. if opt.eval: model.eval() for i, data in enumerate(dataset): if i >= opt.num_test: # only apply our model to opt.num_test images. break model.set_input(data) # unpack data from data loader model.test() # run inference visuals = model.get_current_visuals() # get image results img_path = model.get_image_paths() # get image paths if i % 5 == 0: # save images to an HTML file print('processing (%04d)-th image... %s' % (i, img_path)) save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize) webpage.save() # save the HTML orig_dir = "./datasets/deblur/group_truth" blur_dir = "./datasets/deblur/testA" result_dir = "./datasets/deblur/deblur_out" orig_list = sorted(os.listdir(orig_dir)) deblur_list = sorted(os.listdir(result_dir)) blur_list = sorted(os.listdir(blur_dir)) psnr = [] ssim = [] percp = [] blur_psnr = [] blur_ssim = []
def convert(): if (chkGpuVar.get() == 0): opt.gpu_ids.clear() #opt.remove_images = chkDelVar.get() opt.resize_or_crop = drpResizeOp.get() try: opt.epoch = txtEpoch.get() except Exception as e: print(e) if (opt.resize_or_crop.__contains__('scale')): for i in range(len(validSizes) - 2): if (sclFineVar.get() < validSizes[i + 1] and sclFineVar.get() >= validSizes[i]): opt.fineSize = validSizes[i] print(testOptions.return_options(opt)) try: data_loader = CreateDataLoader(opt) dataset = data_loader.load_data() model = create_model(opt) model.setup(opt) # test with eval mode. This only affects layers like batchnorm and dropout. # pix2pix: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode. # CycleGAN: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout. progressbar.configure(maximum=len(dataset)) #progressbar.start(len(dataset)) for i, data in enumerate(dataset): while running: if i >= opt.num_test or running == False: break model.set_input(data) model.test() visuals = model.get_current_visuals() img_path = model.get_image_paths() mess = 'processing (%04d)-th of %04d image... %s' % ( i + 1, len(dataset), img_path[0]) print(mess) # Open a file with access mode 'a' file_object = open('conversion_progress.txt', 'a') # Append 'hello' at the end of file file_object.write(mess + '\n') # Close the file file_object.close() save_images(opt.results_dir, visuals, img_path, save_both=opt.save_both, aspect_ratio=opt.aspect_ratio) progress_var.set(i + 1) if (opt.remove_images): os.remove(img_path[0]) print('removed image', img_path[0]) except KeyboardInterrupt: progress_var.set(0) print("==============Cancelled==============") raise except Exception as e: print(e) raise