我想知道如何将以下代码(Tensorflow)转换为 Pytorch。
我想使用 DataLoader 但我不能。是否可以使用 DataLoader 进行转换?或者你能告诉我任何其他转换方法吗?
非常感谢 :)
from tensorflow.keras.preprocessing import image as image_utils
from tensorflow.keras.applications.vgg16 import preprocess_input
def load_and_process_image(image_path):
# Print image's original shape, for reference
print('Original image shape: ', mpimg.imread(image_path).shape)
# Load in the image with a target size of 224, 224
image = image_utils.load_img(image_path, target_size=(224, 224))
# Convert the image from a PIL format to a numpy array
image = image_utils.img_to_array(image)
# Add a dimension for number of images, in our case 1
image = image.reshape(1,224,224,3)
# Preprocess image to align with original ImageNet dataset
image = preprocess_input(image)
# Print image's shape after processing
print('Processed image shape: ', image.shape)
return image
最佳答案
import os
from PIL import Image
import torch
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
class MyData(Dataset):
def __init__(self, data_path):
#path of the folder where your images are located
self.data_path = data_path
#transforms to perform on image. In general, these are the default normalization used. you can change std, mean values about three channels according to your requirement
#when ToTensor() is used it automatically permutes the dimensions according to the torch layers
self.transforms = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
self.image_path_list = sorted(os.listdir(self.data_path))
def __len__(self):
#returns the length of your dataset
return len(self.image_path_list)
def __getitem__(self, idx):
#pytorch accepts PIL images, use PIL.Image to load images
image = Image.open(self.image_path_list[idx])
image = self.transform(image)
return image
以上是基于我对您帖子的假设的一个小片段。我假设您需要对给定的平均值进行调整大小、置换和归一化。 DataLoader 是可迭代的。它一次产生单个图像。例如,
#instantiate your loader, with the desired parameters. checkout the pytorch documentation for other arguments
myloader = DataLoader(MyData, batch_size = 32, num_workers = 10)
myloader = iter(myloader)
for i in range(0, 10):
#this yields first 10 batches of your dataset
img = next(myloader)
希望这就是您正在寻找的。请随时评论您的要求以获得任何进一步的说明。
关于python - 如何将以下 Tensorflow 代码转换为 Pytorch(迁移学习)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68632679/