<filename>biggan_discovery/aaa.py
import cv2
import stylegan
import os
import numpy as np
import torch
def postprocess(images):
    """Post-processes images from `torch.Tensor` to `numpy.ndarray`."""
    images = images.detach().cpu().numpy()
    images = (images + 1) * 255 / 2
    images = np.clip(images + 0.5, 0, 255).astype(np.uint8)
    images = images.transpose(0, 2, 3, 1)
    return images

def save_image(path, image):
    """Saves an image to disk.

    NOTE: The input image (if colorful) is assumed to be with `RGB` channel
    order and pixel range [0, 255].

    Args:
        path: Path to save the image to.
        image: Image to save.
    """
    if image is None:
        return

    assert image.ndim == 3 and image.shape[2] in [1, 3]
    cv2.imwrite(path, image[:, :, ::-1])
    print('ojkb')

# code = torch.randn(8, 512).cuda()
# g_kw = {'trunc_psi': 0.7, 'trunc_layers': 8, 'randomize_noise': False}
# gm = stylegan.Generator(256).cuda()
# gm.eval()
# device = torch.cuda.current_device()
# filepath = 'checkpoints/stylegan/G_ema_stylegan_ffhq256.pth'
# map_location = lambda storage, location: storage.cuda(device)
# checkpoint = torch.load(filepath, map_location=map_location)

# if 'models' not in checkpoint:
#     checkpoint = {'models': checkpoint}
def _strip_state_dict_prefix(state_dict, prefix='module.'):
    """Removes the name prefix in checkpoint.

    Basically, when the model is deployed in parallel, the prefix `module.` will
    be added to the saved checkpoint. This function is used to remove the
    prefix, which is friendly to checkpoint loading.

    Args:
        state_dict: The state dict where the variable names are processed.
        prefix: The prefix to remove. (default: `module.`)
    """
    if not all(key.startswith(prefix) for key in state_dict.keys()):
        return state_dict

    stripped_state_dict = dict()
    for key in state_dict:
        stripped_state_dict[key.replace(prefix, '')] = state_dict[key]
    return stripped_state_dict

# state_dict = _strip_state_dict_prefix(
#     checkpoint['models']['generator_smooth'])
#
# gm.load_state_dict(state_dict)
# images = gm(code,None, **g_kw)
#
# images = postprocess(images)
#
# for sub_idx, image in zip([1,2,3,4,5,6,7,8], images):
#     print(sub_idx)
#     save_image(os.path.join('/home/syp/workplace/hessian_penalty/biggan_discovery/', f'{sub_idx:06d}.jpg'), image)
# exit(0)
<filename>biggan_discovery/aaa.py
import cv2
import stylegan
import os
import numpy as np
import torch
def postprocess(images):
    """Post-processes images from `torch.Tensor` to `numpy.ndarray`."""
    images = images.detach().cpu().numpy()
    images = (images + 1) * 255 / 2
    images = np.clip(images + 0.5, 0, 255).astype(np.uint8)
    images = images.transpose(0, 2, 3, 1)
    return images

def save_image(path, image):
    """Saves an image to disk.

    NOTE: The input image (if colorful) is assumed to be with `RGB` channel
    order and pixel range [0, 255].

    Args:
        path: Path to save the image to.
        image: Image to save.
    """
    if image is None:
        return

    assert image.ndim == 3 and image.shape[2] in [1, 3]
    cv2.imwrite(path, image[:, :, ::-1])
    print('ojkb')

# code = torch.randn(8, 512).cuda()
# g_kw = {'trunc_psi': 0.7, 'trunc_layers': 8, 'randomize_noise': False}
# gm = stylegan.Generator(256).cuda()
# gm.eval()
# device = torch.cuda.current_device()
# filepath = 'checkpoints/stylegan/G_ema_stylegan_ffhq256.pth'
# map_location = lambda storage, location: storage.cuda(device)
# checkpoint = torch.load(filepath, map_location=map_location)

# if 'models' not in checkpoint:
#     checkpoint = {'models': checkpoint}
def _strip_state_dict_prefix(state_dict, prefix='module.'):
    """Removes the name prefix in checkpoint.

    Basically, when the model is deployed in parallel, the prefix `module.` will
    be added to the saved checkpoint. This function is used to remove the
    prefix, which is friendly to checkpoint loading.

    Args:
        state_dict: The state dict where the variable names are processed.
        prefix: The prefix to remove. (default: `module.`)
    """
    if not all(key.startswith(prefix) for key in state_dict.keys()):
        return state_dict

    stripped_state_dict = dict()
    for key in state_dict:
        stripped_state_dict[key.replace(prefix, '')] = state_dict[key]
    return stripped_state_dict

# state_dict = _strip_state_dict_prefix(
#     checkpoint['models']['generator_smooth'])
#
# gm.load_state_dict(state_dict)
# images = gm(code,None, **g_kw)
#
# images = postprocess(images)
#
# for sub_idx, image in zip([1,2,3,4,5,6,7,8], images):
#     print(sub_idx)
#     save_image(os.path.join('/home/syp/workplace/hessian_penalty/biggan_discovery/', f'{sub_idx:06d}.jpg'), image)
# exit(0)
Post-processes images from `torch.Tensor` to `numpy.ndarray`. Saves an image to disk.      NOTE: The input image (if colorful) is assumed to be with `RGB` channel     order and pixel range [0, 255].      Args:         path: Path to save the image to.         image: Image to save. # code = torch.randn(8, 512).cuda() # g_kw = {'trunc_psi': 0.7, 'trunc_layers': 8, 'randomize_noise': False} # gm = stylegan.Generator(256).cuda() # gm.eval() # device = torch.cuda.current_device() # filepath = 'checkpoints/stylegan/G_ema_stylegan_ffhq256.pth' # map_location = lambda storage, location: storage.cuda(device) # checkpoint = torch.load(filepath, map_location=map_location) # if 'models' not in checkpoint: #     checkpoint = {'models': checkpoint} Removes the name prefix in checkpoint.      Basically, when the model is deployed in parallel, the prefix `module.` will     be added to the saved checkpoint. This function is used to remove the     prefix, which is friendly to checkpoint loading.      Args:         state_dict: The state dict where the variable names are processed.         prefix: The prefix to remove. (default: `module.`) # state_dict = _strip_state_dict_prefix( #     checkpoint['models']['generator_smooth']) # # gm.load_state_dict(state_dict) # images = gm(code,None, **g_kw) # # images = postprocess(images) # # for sub_idx, image in zip([1,2,3,4,5,6,7,8], images): #     print(sub_idx) #     save_image(os.path.join('/home/syp/workplace/hessian_penalty/biggan_discovery/', f'{sub_idx:06d}.jpg'), image) # exit(0)