PyTorch 教程-在PyTorch中进行风格转移的图像加载和转换
图像加载
我们必须将内容图像和风格图像加载到内存中,以便我们可以对其进行操作。加载过程在风格转移过程中起着至关重要的作用。在加载过程之前,我们需要内存中的图像,否则风格转移过程将无法进行。
#defining a method with three parameters i.e. image location, maximum size and shapedef load_image(img_path,max_size=400,shape=None):# Open the image, convert it into RGB and store in a variableimage=Image.open(img_path).convert('RGB')# comparing image size with the maximum sizeif max(image.size)>max_size:size=max_sizeelse:size=max(image.size)# checking for the image shapeif shape is not None:size=shape#Applying appropriate transformation to our image such as Resize, ToTensor and Normalizationin_transform=transforms.Compose([transforms.Resize(size),transforms.ToTensor(),transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))])#Calling in_transform with our imageimage=in_transform(image).unsqueeze(0) #unsqueeze(0) is used to add extra layer of dimensionality to the image#Returning imagereturn image#Calling load_image() with our image and add it to our devicecontent=load_image('ab.jpg').to(device)style=load_image('abc.jpg',shape=content.shape[-2:]).to(device)
👉点击领取:最全Python资料合集
图像转换
def im_convert(tensor):image=tensor.cpu().clone().detach().numpy()image=image.transpose(1,2,0)image=image*np.array((0.5,0.5,0.5))+np.array((0.5,0.5,0.5))image=image.clip(0,1)return image
image=image.squeeze()
绘制图像
fig, (ax1,ax2)=plt.subplots(1,2,figsize=(20,10))ax1.imshow(im_convert(content))ax1.axis('off')ax2.imshow(im_convert(style))ax2.axis('off')
热门推荐