简体   繁体   中英

Convert images to numpy array with RGB values

I have written following code to read set of images in a directory and convert it into NumPy array.

    import PIL
    import torch
    from torch.utils.data import DataLoader
    import numpy as np
    import os
    import PIL.Image
    
    # Directory containing the images
    image_dir = "dir1/"
    
    # Read and preprocess images
    images = []
    for filename in os.listdir(image_dir):
        # Check if the file is an image
        if not (filename.endswith(".png") or filename.endswith(".jpg")):
            continue
    
        # Read and resize the image
        filepath = os.path.join(image_dir, filename)
        image = PIL.Image.open(file path)
        image = image.resize((32, 32))  # resize images to (32, 32)
        #print(f"Image shape: {image.shape}")
        # Convert images to NumPy arrays
        image = np.array(image)
        images.append(image)
    
    # Convert images to PyTorch tensors 
    images1 = torch.tensor(np.array(images))
    np.save('trial1.npy', np.array(images),allow_pickle=True)

The above code leads to a dataframe of shape (24312, 32, 32) . How to convert it into shape (24312, 32, 32,3) so that it stores RGB values also as 3 channel?

As Edwin Cheong said in a comment , first check your image if its 3 channel, if not you can use the convert function to make it RGB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM