Search code examples
numpytypespytorchtorch

How do I convert data type of images from uint8 to torch.float


I have multiple folders which have PNG images in it. There datatype is of uint8. I ty to run a for loop but it loops only through the array values of 1st image.

I tried this code:

import torch
for i in range(NUMBER OF IMAGES):
    image = cv2.imread(f'DIR/FOLDER/{i}')
    image = torch.to_numpy(image[i]).to(dtype = torch)

Solution

  • According to my understanding it seems you want to get the images from a directory where the images are named like 1.png, 2.png and then change the type to torch.float, then:

    import cv2
    import numpy as np
    import torch
    
    directory = '/DIR/FOLDER/'
    total_imgs = 10
    
    # Initializing an empty list to store the images
    images = []
    
    # Iterating over the images
    for i in range(0, total_imgs):
        # I've used i+1 to start from 1 as the image would be 1.png
        file_path = directory + str(i+1) + '.png'
    
        # Reading the image
        image = cv2.imread(file_path)
    
        image_uint8 = np.array(image, dtype=np.uint8)
    
        # Converting the image to torch.float
        image_float = torch.from_numpy(image_uint8.astype(np.float32))
    
        # Appending the converted image to the list
        images.append(image_float)
    

    Hope that helps.