简体   繁体   English

如何将一组图像转换为 numpy 数组?

[英]How to convert a set of images into a numpy array?

I'm building my first Neural Network taking as example those on the book "Deep Learning with Python - Francois Chollet" and I immediately found my first issue.我正在构建我的第一个神经网络,以“使用 Python 进行深度学习 - Francois Chollet”一书为例,我立即找到了我的第一个问题。 When the author imported the MNIST dataset he also printed the shape, obtaining that it is a 1D tensor.当作者导入 MNIST 数据集时,他还打印了形状,得到它是一维张量。 I'm trying to import a folder containing all caddies images to check whether the NN catalogs them correctly or not.我正在尝试导入一个包含所有球童图像的文件夹,以检查 NN 是否正确对它们进行编目。 The problem is that I can't obtain a 1D tensor from all these images.问题是我无法从所有这些图像中获得一维张量。 I've tried to convert each of them with numpy.asarray(my_image) .我尝试使用numpy.asarray(my_image)转换它们中的每一个。 I also tried to convert the whole list but turns out it became a tuple... any hint?我也尝试转换整个列表,但结果它变成了一个元组......有什么提示吗?

train_label = 'Caddies'
train_images = list()

for filename in listdir('/content/drive/MyDrive/Data set/Caddies/'):
    img_data = image.imread('/content/drive/MyDrive/Data set/Caddies/' +\
                       filename)
    img_data = np.asarray(img_data)
    #print(str(img_data.dtype) + str(img_data.shape))
    train_images.append(img_data)

    print('> loaded %s images' % (len(train_images)))

    train_images = np.array(train_images)

    print(train_images.shape())

If you want to feed your images to a neural network, I suggest you don't use a for-loop to load all your images in memory.如果您想将图像输入神经网络,我建议您不要使用 for 循环将所有图像加载到 memory 中。 Rather, you can use this function:相反,您可以使用这个 function:

import tensorflow as tf
import os
os.chdir('pictures')

files = tf.data.Dataset.list_files('*jpg')

def load_images(path):
    image = tf.io.read_file(path)
    image = tf.io.decode_jpeg(image)
    image = tf.image.convert_image_dtype(image, tf.float32) # optional
    image = tf.image.resize(image, (224, 224))              # optional
    return image 

ds = files.map(load_images).batch(1)

next(iter(ds)).shape
(1, 224, 224, 3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM