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 ?
CodePudding user response:
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.