简体   繁体   English

将图像转换为具有 RGB 值的 numpy 数组

[英]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.我编写了以下代码来读取目录中的一组图像并将其转换为 NumPy 数组。

    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) .上面的代码导致形状为(24312, 32, 32)的数据框。 How to convert it into shape (24312, 32, 32,3) so that it stores RGB values also as 3 channel?如何将其转换为形状(24312, 32, 32,3)以便将 RGB 值也存储为 3 通道?

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.正如Edwin Cheong评论中所说,首先检查您的图像是否为 3 通道,如果不是,您可以使用转换功能将其设为 RGB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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