当前位置: 首页>>代码示例>>Python>>正文


Python utils.save_image方法代码示例

本文整理汇总了Python中torchvision.utils.save_image方法的典型用法代码示例。如果您正苦于以下问题:Python utils.save_image方法的具体用法?Python utils.save_image怎么用?Python utils.save_image使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在torchvision.utils的用法示例。


在下文中一共展示了utils.save_image方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: save_image

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def save_image(self, images, save_dir, iname):
        
        img_name = '%s.png' % (iname)
        full_path = os.path.join(save_dir, img_name)
        
        if (iname.find('mask') == -1) or (iname.find('foreground') != -1):
            img = images.add(1).div(2).mul(255).clamp(0, 255).byte()
            ndarr = img.permute(1, 2, 0).data.cpu().numpy()
            im = Image.fromarray(ndarr)
            im.save(full_path)

        else:
            img = images.mul(255).clamp(0, 255).byte()
            ndarr = img.data.cpu().numpy()
            ndarr = np.reshape(ndarr, (ndarr.shape[-1], ndarr.shape[-1], 1))
            ndarr = np.repeat(ndarr, 3, axis=2)
            im = Image.fromarray(ndarr)
            im.save(full_path) 
开发者ID:kkanshul,项目名称:finegan,代码行数:20,代码来源:trainer.py

示例2: save_img_results

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def save_img_results(data_img, fake, epoch, image_dir):
    num = cfg.VIS_COUNT
    fake = fake[0:num]
    # data_img is changed to [0,1]
    if data_img is not None:
        data_img = data_img[0:num]
        vutils.save_image(
            data_img, '%s/real_samples.png' % image_dir,
            normalize=True)
        # fake.data is still [-1, 1]
        vutils.save_image(
            fake.data, '%s/fake_samples_epoch_%03d.png' %
            (image_dir, epoch), normalize=True)
    else:
        vutils.save_image(
            fake.data, '%s/lr_fake_samples_epoch_%03d.png' %
            (image_dir, epoch), normalize=True) 
开发者ID:hanzhanggit,项目名称:StackGAN-Pytorch,代码行数:19,代码来源:utils.py

示例3: generate

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def generate(G, file_name, tags):
  '''
  Generate fake image.
  :param G:
  :param file_name:
  :param tags:
  :return: img's tensor and file path.
  '''
  # g_noise = Variable(torch.FloatTensor(1, 128)).to(device).data.normal_(.0, 1)
  # g_tag = Variable(torch.FloatTensor([utils.get_one_hot(tags)])).to(device)
  g_noise, g_tag = utils.fake_generator(1, 128, device)

  img = G(torch.cat([g_noise, g_tag], dim=1))
  vutils.save_image(img.data.view(1, 3, 128, 128),
                    os.path.join(tmp_path, '{}.png'.format(file_name)))
  print('Saved file in {}'.format(os.path.join(tmp_path, '{}.png'.format(file_name))))
  return img.data.view(1, 3, 128, 128), os.path.join(tmp_path, '{}.png'.format(file_name)) 
开发者ID:VincentXWD,项目名称:create-girls-moe-pytorch,代码行数:19,代码来源:generate.py

示例4: visualize_inference

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def visualize_inference(opt, real_A, real_B, model, name='inf_test.png'):
    size = real_A.size()

    real_B = real_B[:opt.num_multi]
    # all samples in real_A share the same post_z_B
    multi_fake_B = model.inference_multi(real_A.detach(), real_B.detach())
    multi_fake_B = multi_fake_B.data.cpu().view(
        size[0], opt.num_multi, size[1], size[2], size[3])

    vis_multi_image = torch.cat([real_A.data.cpu().unsqueeze(1), multi_fake_B], dim=1) \
        .view(size[0]*(opt.num_multi+1),size[1],size[2],size[3])

    vis_multi_image = torch.cat([torch.ones(1, size[1], size[2], size[3]).cpu(), real_B.data.cpu(),
                                 vis_multi_image.cpu()], dim=0)

    save_path = os.path.join(opt.res_dir, name)
    vutils.save_image(vis_multi_image.cpu(), save_path,
        normalize=True, range=(-1,1), nrow=opt.num_multi+1) 
开发者ID:aalmah,项目名称:augmented_cyclegan,代码行数:20,代码来源:test.py

示例5: visualize_inference

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def visualize_inference(opt, real_A, real_B, model, eidx, uidx):
    size = real_A.size()

    real_B = real_B[:opt.num_multi]
    # all samples in real_A share the same post_z_B
    multi_fake_B = model.inference_multi(real_A.detach(), real_B.detach())
    multi_fake_B = multi_fake_B.data.cpu().view(
        size[0], opt.num_multi, size[1], size[2], size[3])

    vis_multi_image = torch.cat([real_A.data.cpu().unsqueeze(1), multi_fake_B], dim=1) \
        .view(size[0]*(opt.num_multi+1),size[1],size[2],size[3])

    vis_multi_image = torch.cat([torch.ones(1, size[1], size[2], size[3]).cpu(), real_B.data.cpu(),
                                 vis_multi_image.cpu()], dim=0)

    save_path = os.path.join(opt.vis_inf, 'inf_%02d_%04d.png' % (eidx, uidx))
    vutils.save_image(vis_multi_image.cpu(), save_path,
        normalize=True, range=(-1,1), nrow=opt.num_multi+1)
    copyfile(save_path, os.path.join(opt.vis_latest, 'inf.png')) 
开发者ID:aalmah,项目名称:augmented_cyclegan,代码行数:21,代码来源:train.py

示例6: save_superimages

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def save_superimages(self, images_list, filenames,
                         save_dir, split_dir, imsize):
        batch_size = images_list[0].size(0)
        num_sentences = len(images_list)
        for i in range(batch_size):
            s_tmp = '%s/super/%s/%s' %\
                (save_dir, split_dir, filenames[i])
            folder = s_tmp[:s_tmp.rfind('/')]
            if not os.path.isdir(folder):
                print('Make a new folder: ', folder)
                mkdir_p(folder)
            #
            savename = '%s_%d.png' % (s_tmp, imsize)
            super_img = []
            for j in range(num_sentences):
                img = images_list[j][i]
                # print(img.size())
                img = img.view(1, 3, imsize, imsize)
                # print(img.size())
                super_img.append(img)
                # break
            super_img = torch.cat(super_img, 0)
            vutils.save_image(super_img, savename, nrow=10, normalize=True) 
开发者ID:netanelyo,项目名称:Recipe2ImageGAN,代码行数:25,代码来源:blah.py

示例7: ExtractMask

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def ExtractMask(Seg):
    # Given segmentation for content and style, we get a list of segmentation for each color
    '''
    Test Code:
        content_masks,style_masks = ExtractMask(contentSegImg,styleSegImg)
        for i,mask in enumerate(content_masks):
            vutils.save_image(mask,'samples/content_%d.png' % (i),normalize=True)
        for i,mask in enumerate(style_masks):
            vutils.save_image(mask,'samples/style_%d.png' % (i),normalize=True)
    '''
    color_codes = ['blue', 'green', 'black', 'white', 'red', 'yellow', 'grey', 'lightblue', 'purple']
    masks = []
    for color in color_codes:
        mask = MaskHelper(Seg,color)
        masks.append(mask)
    return masks 
开发者ID:sunshineatnoon,项目名称:LinearStyleTransfer,代码行数:18,代码来源:LoaderPhotoReal.py

示例8: visualize

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def visualize(self, iteration):
        netG = self.netG
        netG.eval()

        with torch.no_grad():
            y = torch.arange(self.num_columns).repeat(self.num_samples).to(
                self.device)
            if y.size(0) < self.batch_size:
                x = netG(self.fixed_z, y)
            else:
                xs = []
                for i in range(0, y.size(0), self.batch_size):
                    x = netG(self.fixed_z[i:i + self.batch_size],
                             y[i:i + self.batch_size])
                    xs.append(x)
                x = torch.cat(xs, dim=0)
            utils.save_image(x.detach(),
                             os.path.join(self.out,
                                          'samples_iter_%d.png' % iteration),
                             self.num_columns,
                             0,
                             normalize=True,
                             range=self.range) 
开发者ID:takuhirok,项目名称:rGAN,代码行数:25,代码来源:visualizer.py

示例9: test

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def test(dataloader, epoch):
    real_cpu_first, _ = iter(dataloader).next()
    real_cpu_first = real_cpu_first.mul(0.5).add(0.5)  # denormalize

    if opt.cuda:
        real_cpu_first = real_cpu_first.cuda()

    netGx.eval(), netGz.eval()  # switch to test mode
    latent = netGz(Variable(real_cpu_first, volatile=True))

    # removes last sigmoid activation to visualize reconstruction correctly
    mu, sigma = latent[:, :opt.nz], latent[:, opt.nz:].exp()
    recon = netGx(mu + sigma)

    vutils.save_image(recon.data, '{0}/reconstruction.png'.format(opt.experiment))
    vutils.save_image(real_cpu_first, '{0}/real_samples.png'.format(opt.experiment))


# MAIN LOOP 
开发者ID:edgarriba,项目名称:ali-pytorch,代码行数:21,代码来源:main.py

示例10: getTemplates

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def getTemplates(opt,N,vis=True,path=str(bMirror)):
    x=getImage(opt.contentPath + os.listdir(opt.contentPath)[0], True)
    if N ==0:
        return x

    flow=getCanonic(x)
    nTex = len(os.listdir(opt.texturePath))
    out = torch.FloatTensor(N,3,x.shape[2],x.shape[3]).half()
    files=os.listdir(opt.texturePath)
    for n in range(N):
        z=getImage(opt.texturePath + files[n % nTex])
        out[n:n+1] = randomTile(flow,z)
    if vis:
        vutils.save_image(out[:8].float(),path+'templates.jpg', normalize=True,nrow=4,padding=10)##limit to 25 the shown templates
    return torch.cat([x,flow.permute(0,3,1,2)],1),out

##@param target is always (B,3,H,W). RGB image. The canonical coordinates of the used templates will  be added to last 2 channels
##@param template is always (N,3,H,W) 
开发者ID:zalandoresearch,项目名称:famos,代码行数:20,代码来源:prepareTemplates.py

示例11: eval

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def eval(self,
             batch_size=None):
        self.netG_AB.eval()
        self.netG_BA.eval()
        self.netD_A.eval()
        self.netD_B.eval()
        if batch_size is None:
            batch_size = self.test_data_loader.batch_size

        with torch.no_grad():
            for batch_idx, data in enumerate(self.test_data_loader):
                _real_A = data['testA'].to(self.device)
                _fake_B = self.netG_AB(_real_A)
                _real_B = data['testB'].to(self.device)
                _fake_A = self.netG_BA(_real_B)
                viz_sample = torch.cat((_real_A, _fake_B, _real_B, _fake_A), 0)
                vutils.save_image(viz_sample,
                                  'img_{}.png'.format(batch_idx),
                                  nrow=batch_size,
                                  normalize=True) 
开发者ID:PacktPublishing,项目名称:Hands-On-Generative-Adversarial-Networks-with-PyTorch-1.x,代码行数:22,代码来源:build_gan.py

示例12: eval

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def eval(self,
             batch_size=None):
        self.netG.eval()
        self.netD.eval()
        if batch_size is None:
            batch_size = self.data_loader.batch_size

        with torch.no_grad():
            for batch_idx, data in enumerate(self.data_loader):
                image = data['right_images'].to(self.device)[:batch_size]
                embed = data['right_embed'].to(self.device)[:batch_size]
                text = data['txt'][:batch_size]
                noise = torch.randn((image.shape[0], 100, 1, 1), device=self.device)
                viz_sample = self.netG(noise, embed)
                vutils.save_image(viz_sample,
                                  'img_{}.png'.format(batch_idx),
                                  nrow=batch_size//8,
                                  normalize=True)
                for t in text:
                    print(t)
                break 
开发者ID:PacktPublishing,项目名称:Hands-On-Generative-Adversarial-Networks-with-PyTorch-1.x,代码行数:23,代码来源:build_gan.py

示例13: plot_samples_per_epoch

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def plot_samples_per_epoch(self, batch, epoch):
        """
        Plotting the batch images
        :param batch: Tensor of shape (B,C,H,W)
        :param epoch: the number of current epoch
        :return: img_epoch: which will contain the image of this epoch
        """
        img_epoch = '{}samples_epoch_{:d}.png'.format(self.config.out_dir, epoch)
        v_utils.save_image(batch,
                           img_epoch,
                           nrow=4,
                           padding=2,
                           normalize=True)
        return imageio.imread(img_epoch) 
开发者ID:moemen95,项目名称:Pytorch-Project-Template,代码行数:16,代码来源:example.py

示例14: plot_samples_per_epoch

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def plot_samples_per_epoch(self, fake_batch, epoch):
        """
        Plotting the fake batch
        :param fake_batch: Tensor of shape (B,C,H,W)
        :param epoch: the number of current epoch
        :return: img_epoch: which will contain the image of this epoch
        """
        img_epoch = '{}samples_epoch_{:d}.png'.format(self.config.out_dir, epoch)
        v_utils.save_image(fake_batch,
                           img_epoch,
                           nrow=4,
                           padding=2,
                           normalize=True)
        return imageio.imread(img_epoch) 
开发者ID:moemen95,项目名称:Pytorch-Project-Template,代码行数:16,代码来源:celebA.py

示例15: save_current_images

# 需要导入模块: from torchvision import utils [as 别名]
# 或者: from torchvision.utils import save_image [as 别名]
def save_current_images(self, epoch, reals, fakes, fixed):
        """ Save images for epoch i.

        Args:
            epoch ([int])        : Current epoch
            reals ([FloatTensor]): Real Image
            fakes ([FloatTensor]): Fake Image
            fixed ([FloatTensor]): Fixed Fake Image
        """
        vutils.save_image(reals, '%s/reals.png' % self.img_dir, normalize=True)
        vutils.save_image(fakes, '%s/fakes.png' % self.img_dir, normalize=True)
        vutils.save_image(fixed, '%s/fixed_fakes_%03d.png' %(self.img_dir, epoch+1), normalize=True) 
开发者ID:samet-akcay,项目名称:ganomaly,代码行数:14,代码来源:visualizer.py


注:本文中的torchvision.utils.save_image方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。