将图像列表重塑为正确的CNN格式

时间:2018-10-12 12:17:47

标签: python conv-neural-network reshape matrix-multiplication

我有一组np.array格式的图像,形状为(nb_examples,1),每个元素的形状为(128,128,3)。我在这里尝试做的是拥有形状为(nb_examples,128,128,3)的数组。我尝试了很多技术。.这是其中一种:

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)

我收到错误

ValueError: cannot reshape array of size 1510 into shape (1510,128,128,3)

最终的想法是将这些图像用于CNN模型。当我将图像作为CNN的输入而不重塑时,会出现以下错误:

ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (1510, 1)

1 个答案:

答案 0 :(得分:1)

感谢提示@madjaoue。答案是:

x_train = np.array([img for img in x_train])
x_valid = np.array([img for img in x_valid])