How to convert the below Tensorflow code to Pytorch (transfer learning)?

Viewed 70

I want to know how to convert the below codes(Tensorflow) to Pytorch. I've wanted to use DataLoader but I couldn't. Is it possible to use DataLoader for converting? or Can you tell me any other ways to convert?

Thanks a lot :)


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
1 Answers
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

Above is a small snippet based on my assumptions from your post. I assumed you would need to resize, permute and normalize about the given mean values. DataLoader is iterate-able. It yields single image at a time.

For example,

#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)

Hopefully, this is what you are looking for. Please feel free to comment your quires for any further clarification.

Related