Python技术迷

PyTorch 教程-在PyTorch中进行风格转移的图像加载和转换

整理:python架构师
在导入所有必要的库并将VGG-19添加到我们的设备之后,我们必须将要应用风格转移的图像加载到内存中。我们有一个内容图像和风格图像,目标图像将是这两个图像的组合。并非每个图像都需要具有相同的大小或像素。为了使图像相等,我们还将应用图像转换过程。

Image

图像加载

我们必须将内容图像和风格图像加载到内存中,以便我们可以对其进行操作。加载过程在风格转移过程中起着至关重要的作用。在加载过程之前,我们需要内存中的图像,否则风格转移过程将无法进行。

代码:
#defining a method with three parameters i.e. image location, maximum size and shape   def load_image(img_path,max_size=400,shape=None):  # Open the image, convert it into RGB and store in a variable       image=Image.open(img_path).convert('RGB')      # comparing image size with the maximum size       if max(image.size)>max_size:        size=max_size      else:        size=max(image.size)      # checking for the image shape      if shape is not None:         size=shape      #Applying appropriate transformation to our image such as Resize, ToTensor and Normalization      in_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 image       image=in_transform(image).unsqueeze(0) #unsqueeze(0) is used to add extra layer of dimensionality to the image      #Returning image       return image  #Calling load_image() with our image and add it to our device  content=load_image('ab.jpg').to(device)  style=load_image('abc.jpg',shape=content.shape[-2:]).to(device)

专属福利 

👉点击领取:最全Python资料合集

图像转换

在导入图像之前,我们需要将图像从张量转换为numpy图像,以确保与绘图包的兼容性。我们之前在图像识别中的图像转换中已经使用了熟悉的image_converts辅助函数。
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
如果我们运行此辅助方法,它将生成错误。我们必须从图像的形状和数组的形状中删除单维条目。因此,在转置方法之前,我们将挤压(squeeze)我们的图像。
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')
当我们在Google Colab Notebook上运行它时,它将给我们预期的输出:
Image
Image
 1
Image
热门推荐

Image