用RGB值将图像转换为numpy数组



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

以上代码导致形状为(24312, 32, 32)的数据框。如何将其转换为形状(24312, 32, 32,3),使其存储RGB值也作为3通道?

正如Edwin Cheong在评论中所说,首先检查你的图像是否为3通道,如果不是,你可以使用转换函数将其转换为RGB

最新更新