简体   繁体   English

如何将 NumPy 图像数组转换为 Tensorflow

[英]How to convert NumPy array of images to Tensorflow

I have two arrays of shape (600,) containing images and labels.我有两个包含图像和标签的形状 (600,) 的 arrays。 When I try to pass them to Keras/Tensorflow in any form I get the error:当我尝试以任何形式将它们传递给 Keras/Tensorflow 时,我收到错误消息:

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray). ValueError:无法将 NumPy 数组转换为张量(不支持的 object 类型 numpy.ndarray)。

As far as I understand the images are stored in an array of arrays.据我了解,图像存储在 arrays 数组中。 When observing the inner arrays (single images) they have the following properties:观察内部 arrays(单幅图像)时,它们具有以下属性:

Array of dtype=uint8 with shape: (x, 500, 3) where x is between 300 and 500. dtype=uint8 的数组,形状为:(x, 500, 3),其中 x 介于 300 和 500 之间。

I was able to apply tf layers on the array of images via pandas.apply in the hope the issue was in the inconsistent size of the images:我能够通过 pandas.apply 在图像数组上应用 tf 层,希望问题出在图像大小不一致:

resize_and_rescale = tf.keras.Sequential([
  tf.keras.layers.experimental.preprocessing.Resizing(IMG_SIZE, IMG_SIZE),
  tf.keras.layers.experimental.preprocessing.Rescaling(1./255)
])
train_df.image = train_df.image.apply(resize_and_rescale)

This code executed successful, but the resulting eager tensors are still not compatible with tensorflow:此代码执行成功,但生成的 Eager tensors 仍然与 tensorflow 不兼容:

train_dataset = tf.data.Dataset.from_tensor_slices((train_df.image.values, train_df.label.values))

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type tensorflow.python.framework.ops.EagerTensor). ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type tensorflow.python.framework.ops.EagerTensor).

How can I load the array of images into tf?如何将图像数组加载到 tf 中?

I already tried the following load functions unsuccessfully:我已经尝试了以下加载功能,但未成功:

NumpyArrayIterator NumpyArrayIterator

from_tensor_slices from_tensor_slices

ImageDataGenerator.flow ImageDataGenerator.flow

Firstly you should try converting the input of from_tensor_slices into a list of 600 arrays.首先,您应该尝试将 from_tensor_slices 的输入转换为 600 arrays 的列表。 The function is currently consider it as only 1 sample, an array with the first shape of 600, thus creating the error. function 目前仅将其视为 1 个样本,即第一个形状为 600 的数组,因此会产生错误。

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

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