[英]Classify images with tab containing path
我希望使用路径包含在表格中的图像来训练网络。
我在 TensorFlow 网站上搜索过,我找到了以下说明:
train_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size,
directory=train_dir,
shuffle=True,
target_size=(IMG_HEIGHT, IMG_WIDTH),
class_mode='binary')
问题是我的测试和验证数据没有单独的文件夹。 一个表包含测试图像的路径,另一个包含验证图像的路径。
但是,我的图像根据它们的类位于不同的文件夹中。 如何加载路径在一个表中的这些 PNG 测试图像,并与路径在另一个表中的其他图像进行验证?
您可以将路径列表传递给tf.data.Dataset.list_files()
,然后将它们传递给map()
函数以读取这些图像并执行您想做的所有预处理。 您可以在此处找到有关tf.data.Dataset
和支持的方法的更多信息。
这是一个示例,其中我在 3 个不同的文件夹中有鸟和狗的图像。 我将这些路径传递给tf.data.Dataset.list_files()
并且在map
函数中我正在做crop_central
来裁剪图像并稍后显示它们。 添加了打印语句来显示文件的路径。
代码 -
%tensorflow_version 2.x
import tensorflow as tf
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np
file_path = ['/content/bird.jpg','/content/sample_data/dog.jpg','/usr/bird1.jpg']
def load_file_and_process(path):
print("Loading image from path :",bytes.decode(path.numpy()))
image = load_img(bytes.decode(path.numpy()), target_size=(224, 224))
image = img_to_array(image)
image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00))
return image
train_dataset = tf.data.Dataset.list_files(file_path)
train_dataset = train_dataset.map(lambda x: tf.py_function(load_file_and_process, [x], [tf.float32]))
for f in train_dataset:
for l in f:
image = np.array(array_to_img(l))
print("Crop Image is of shape : ", image.shape)
plt.figure()
plt.imshow(image)
输出 -
Loading image from path : /content/bird.jpg
Crop Image is of shape : (124, 124, 3)
Loading image from path : /content/sample_data/dog.jpg
Crop Image is of shape : (220, 220, 3)
Loading image from path : /usr/bird1.jpg
Crop Image is of shape : (158, 158, 3)
希望这能回答你的问题。 快乐学习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.