import numpy as np import torch from torchvision import transforms import torch.nn.functional as F from torch.autograd.variable import Variable NORMALIZE_IMAGENET = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") image_mean = torch.Tensor(NORMALIZE_IMAGENET.mean).view(-1, 1, 1).to(device) image_std = torch.Tensor(NORMALIZE_IMAGENET.std).view(-1, 1, 1).to(device) def normalize_img(x): return (x.to(device) - image_mean) / image_std def unnormalize_img(x): return (x.to(device) * image_std) + image_mean def round_pixel(x): x_pixel = 255 * unnormalize_img(x) y = torch.round(x_pixel).clamp(0, 255) y = normalize_img(y/255.0) return y def project_linf(x, y, radius): """ Clamp x-y so that Linf(x,y)<=radius """ delta = x - y delta = 255 * (delta * image_std) delta = torch.clamp(delta, -radius, radius) delta = (delta / 255.0) / image_std return y + delta def psnr_clip(x, y, target_psnr): """ Clip x-y so that PSNR(x,y)=target_psnr """ delta = x - y delta = 255 * (delta * image_std) psnr = 20*np.log10(255) - 10*torch.log10(torch.mean(delta**2)) if psnr