gpt4 book ai didi

python - 将列表转换为 n 维数组以馈送到 TFlearn

转载 作者:行者123 更新时间:2023-11-30 09:19:25 27 4
gpt4 key购买 nike

我正在开发一个CNN,使用基于tensorflow的TFlearn对图像进行分类,现在我使用scipy.misc.imread创建数据集,并将图像大小设置为150x150, channel = 3,现在我得到了list 包含 4063(我的图像的数量) (150, 150, 3) 数组,现在我想将其转换为 n 维数组 (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是我得到的,它是我要转换的列表

最佳答案

如果您有形状为 (150, 150, 3) 的图像(numpy 数组)列表,那么您可以简单地通过 constructor 将外部列表转换为 numpy 数组。或调用np.asarray函数(隐式调用构造函数):

np.array([np.ones((150,150,3)), np.ones((150,150,3))]).shape
>>> (2, 150, 150, 3)

编辑:根据您的情况,将其添加到 create_train_data 函数返回中。:

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)

关于python - 将列表转换为 n 维数组以馈送到 TFlearn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45607481/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com