我正在开发CNN,通过使用基于张量流的TFlearn对图像进行分类,现在我使用scipy.misc.imread创建数据集,并将图像大小设置为150x150,channels = 3,现在我得到了一个列表中包含4063(我的图像数量)(150,150,3)数组,现在我想将其转换为nd-array(4063,150,150,3),我不知道如何解决它, 请帮我。提前谢谢!
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]
我获得了train_data,这是我要转换的列表
答案 0 :(得分:0)
如果您有一个带有形状(150,150,3)的图像列表(numpy数组),那么您可以通过constructor或调用np.asarray将外部列表转换为numpy数组。 function(隐式调用构造函数):
np.array([np.ones((150,150,3)), np.ones((150,150,3))]).shape
>>> (2, 150, 150, 3)
编辑:在您的情况下,将此添加到create_train_data
函数return。:
return np.array(train_data)
或者,如果要将多个numpy数组添加到新的numpy数组中,可以使用numpy.stack将它们添加到新维度。
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)
答案 1 :(得分:0)
您可以在列表中使用np.asarray。
>>> import numpy as np
>>> l = []
>>> for i in range(4063):
... l.append(np.zeros((150,150,3)))
...
>>> type(l)
<type 'list'>
>>> a = np.asarray(l)
>>> type(a)
<type 'numpy.ndarray'>
>>> a.shape
(4063, 150, 150, 3)