I have a set of images in an np.array
format with shape (nb_examples,1)
and each element has the shape (128,128,3)
. What I am trying to do here is to have an array of shape (nb_examples,128,128,3)
. I've tried many techniques.. this is one of them:
import cv2
import os
import glob
import re
img_size_target = (128,128)
img_dir = "train_set/" # Enter Directory of all images
data_path = os.path.join(img_dir,'*.bmp')
files = glob.glob(data_path)
data = []
indexes = []
files_names = []
for f1 in np.sort(files):
#reading images using OpenCV
img = cv2.imread(f1)
files_names.append(str(f1))
data.append(img)
#using filename number to get the index of the sample
result = re.search('/foie_(.*)\.bmp', str(f1))
indexes.append(np.int(result.group(1)))
#Create the dataframe
train_df = pd.DataFrame({"id":indexes,"file": files_names, "images": data})
train_df.sort_values(by="id",ascending=True,inplace=True)
#Split train/validation set
ids_train, ids_valid, x_train, x_valid, y_train, y_valid = train_test_split(
train_df.id.values,
#Here I resize the original images from (700,960,3) to (128,128,3)
np.array(train_df.images.apply(lambda x: cv2.resize(x,img_size_target).reshape(img_size_target[0],img_size_target[1],3))),
train_df.target,
test_size=0.2, stratify=train_df.target, random_state=1337)
print(x_train.shape) #result is (1510,1)
print(x_train[0].shape) #result is (128,128,3)
x_train.reshape(x_train.shape[0],128,128,3)
I get the error
ValueError: cannot reshape array of size 1510 into shape (1510,128,128,3)
The final idea is to use these images for a CNN model. When I give the images as inputs to the CNN without reshaping I get the following error:
ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (1510, 1)
Thanks for the hint @madjaoue. The answer was:
x_train = np.array([img for img in x_train])
x_valid = np.array([img for img in x_valid])