I am developing a CNN to classify images by using TFlearn based on tensorflow, and now I create data sets by using scipy.misc.imread, and I set the image size to 150x150, channels = 3, and now I get a list which contains 4063(the number of my images) (150, 150, 3) array, and now I want to convert it to n-d-array (4063, 150, 150, 3), I don't know how to solve it, please help me. Thank you in advance!
import numpy as np
import os
import tensorflow as tf
from scipy import misc
from PIL import Image
IMAGE_SIZE = 150
image_path = "dragonfly"
labels = np.zeros((4063, 1))
labels [0:2363] = 1
labels [2364:4062] = 0
test_labels = np.zeros((200, 1))
test_labels [0:99] = 1
test_labels [100:199] = 0
fset = []
fns=[os.path.join(root,fn) for root,dirs,files in os.walk(image_path) for fn in files]
for f in fns:
fset.append(f)
def create_train_data():
train_data = []
fns=[os.path.join(root,fn) for root,dirs,files in os.walk(image_path) for fn in files]
for f in fns:
image = misc.imread(f)
image = misc.imresize(image, (IMAGE_SIZE, IMAGE_SIZE, 3))
train_data.append(np.array(image))
return train_data
train_data = create_train_data()
print (len(train_data))
training_data = train_data[0:2264] + train_data[2364:3963]
train_labels = np.concatenate((labels[0:2264], labels[2364:3963]))
test_data = train_data[2264:2364] + train_data[3963:4063]
The train_data is what I got, and it's the list which I want to convert
If you have a list of images (numpy arrays) with shapes (150, 150, 3) then you can simply convert the outer list to a numpy array by the constructor or calling the np.asarray function (which implicitly calls the constructor):
np.array([np.ones((150,150,3)), np.ones((150,150,3))]).shape
>>> (2, 150, 150, 3)
Edit: in your case add this to create_train_data
functions return.:
return np.array(train_data)
Alternatively if you want to add multiple numpy arrays into a new numpy array, you can use numpy.stack to add them over a new dimension.
import numpy as np
img_1 = np.ones((150, 150, 3))
img_2 = np.ones((150, 150, 3))
stacked_img = np.stack((img_1, img_2))
stacked_img.shape
>>> (2, 150, 150, 3)