import tensorflow as tf
import os
#将所有数据存放在同一目录下,
#然后将不同类别的图片分别地存放在各自的类别子目录下
image_base_dir= r'../data/flower_photos'
flower_names = ['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips']
batch_size = 32
'''
所有图片路径,例如
['flower_photossunflowers4895721242_89014e723c_n.jpg',
'flower_photosdandelion4164845062_1fd9b3f3b4.jpg',
'flower_photosdandelion3476759348_a0d34a4b59_n.jpg',
'flower_photosdandelion6972675188_37f1f1d6f6.jpg',
'flower_photossunflowers8928658373_fdca5ff1b8.jpg']
'''
def read_and_process_image(image_full_path,image_label):
image = tf.io.read_file(image_full_path)
image = tf.image.decode_jpeg(image,channels=3)
image = tf.image.resize(image,[256,256]) # 原始图片大重设为(256, 256)
image = image/255.0 # 归一化到[0,1]范围
return image,image_label
def get_cat_dog_dataset():
all_flower_names = [] #花的全路径
all_flower_labels = [] #花的标签,0,1,2,3,4
for i, nm in enumerate(flower_names):
fullpath = os.path.join(image_base_dir ,nm)
for fname in os.listdir(fullpath):
all_flower_names.append(os.path.join(fullpath ,fname))
all_flower_labels.append(i) #对应标签 0,1,2,3,4
#读取花的图片
train_dataset = tf.data.Dataset.from_tensor_slices((all_flower_names,all_flower_labels))
train_dataset = train_dataset.map(map_func = read_and_process_image)
train_dataset = train_dataset.shuffle(buffer_size = 1000)
train_dataset = train_dataset.batch(batch_size)
train_dataset= train_dataset.prefetch(tf.data.experimental.AUTOTUNE)
return train_dataset
for img in get_cat_dog_dataset():
print(img)
![8945002ca820526a43946c27b0a0a96c.png](https://i-blog.csdnimg.cn/blog_migrate/5fa312e6d51484c8d218e02576c7083e.jpeg)
参考
TensorFlow2.0(10):加载自定义图片数据集到Dataset
https://www.cnblogs.com/chenhuabin/p/11863889.html