![](/img/trans.png)
[英]convert a 2D numpy array with positive and negative values, into an RGB images
[英]Convert images to numpy array with RGB values
我编写了以下代码来读取目录中的一组图像并将其转换为 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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.