访问tf.keras.utils.image_dataset_from_directory之后的图像



我正在使用tf.keras.utils.image_dataset_from_directory将我的图像加载到tensorflow的数据集中。然而,我对它的工作原理感到困惑。我只是想能够imshow数据集中的每个图像。

data = tf.keras.utils.image_dataset_from_directory('/content/gdrive/MyDrive/Skyrmion Vision/testFiles/train/',batch_size=1,image_size=(171,256))
data_iterator = data.as_numpy_iterator()
batch = data_iterator.next()
batch[0].shape
for image in batch:
print(type(image))

这是我的尝试,但它只是显示2个numpy.ndarray作为类型,我希望它将所有12个图像显示为numpy数组(数据集中只有12个图像(。

在图像进入tensorflow数据集中后,我如何访问这些图像?

您通过设置batch_size=1创建了一批元素。

所以,如果你这样做:

data_iterator = data.as_numpy_iterator()
batch = data_iterator.next()

您只能访问一个图像,因为您的批处理中只有一个图像。若要获取下一个批处理,也就是下一个映像,您可以再次调用data_iterator.next()

然而,如果你只想迭代你的数据集并打印图像,你可以这样做:

data = tf.keras.utils.image_dataset_from_directory('img',batch_size=1,image_size=(171,256))
for x, y in data:
print("image: {}, label: {}".format(x,y))

当然,您也可以设置更高的batch_size值,以便一次访问更多图像。

如果你想一次访问一个图像,你可以:


方法1(建议(:迭代批次,并迭代批次中的图像:

import numpy as np
from google.colab.patches import cv2_imshow
data = tf.keras.utils.image_dataset_from_directory('img',batch_size=1,image_size=(171,256))
for batch_x, batch_y in data:
for i, x in enumerate(batch_x):
x = np.asarray(x)
cv2_imshow(x)

内部循环允许您单独访问批处理中的图像。使用for batch_x, batch_y in data可以获得两个数组,其中第一个维度是批次中的样本数。因此,如果添加一个内部循环,就可以遍历批处理的元素。在这种情况下,只有一个元素,但循环使方法更加通用。


方法2:使用索引访问批次中的图像。

设置batch_size=1后,每个批次只有一个图像。因此,循环的每个batch_x元素都是形状为(1, 171, 256, 3)的阵列。假设您设置了batch_size=2。这将为您提供batch_x形状的(2, 171, 256, 3)。在这一点上,如果你想显示每个批次的第二个(即索引1(图像,你可以通过直接索引图像来完成:

import numpy as np
from google.colab.patches import cv2_imshow
data = tf.keras.utils.image_dataset_from_directory('img', batch_size=2, image_size=(171,256))
for batch_x, batch_y in data:
x = np.asarray(batch_x[1])  # access second image of batch
cv2_imshow(x)

cv2_imshow方法用于在Google Colab中显示图像。

相关内容

最新更新