我正在尝试创建一个模型来对一些植物进行分类,以便我可以学习如何使用TensorFlow。问题是我可以用作参考的每个good example都在加载.csv
数据集,而我想加载.jpeg
数据集(可以是.png
或{{1} }。
这些示例甚至使用如下内置数据集:
.jpg
我的数据集被组织在包含花朵标签的文件夹中,并且内部有按数字组织的图像。
答案 0 :(得分:1)
让我假设您的文件夹结构如下:
├── testfiles
| ├── BougainvilleaGlabra
| | ├── BougainvilleaGlabra_001.jpeg
| | ├── *.jpeg
| ├── HandroanthusChrysotrichus
| | ├── HandroanthusChrysotrichus_001.jpeg
| | ├── *.jpeg
| ├── SpathodeaVenusta
| | ├── SpathodeaVenusta_001.jpeg
| | ├── *.jpeg
| ├──TibouchinaMutabilis
| | ├── TibouchinaMutabilis_001.jpeg
| | ├── *.jpeg
├── test.py
首先,您需要获取所有图像路径。
import glob,os
path = 'testfiles/'
files = [f for f in glob.glob(path + "*/*.jpeg", recursive=True)]
print(files)
['testfiles/HandroanthusChrysotrichus/HandroanthusChrysotrichus_002.jpeg', 'testfiles/HandroanthusChrysotrichus/HandroanthusChrysotrichus_001.jpeg', ...]
然后您需要将每个类编码为数字。
label_map = {'BougainvilleaGlabra':0,
'HandroanthusChrysotrichus':1,
'SpathodeaVenusta':2,
'TibouchinaMutabilis':3,}
label = [label_map[os.path.basename(file).split('_')[0]] for file in files]
print(label)
[1, 1, 1, 0, 0, 0, 2, 2, 2, 3, 3, 3]
然后您可以使用tf.data.Dataset
。您需要一个功能来读取图像并将其重新定型为相同形状。
import tensorflow as tf
def read_image(filename,label):
image_string = tf.read_file(filename)
image_decoded = tf.image.decode_jpeg(image_string)
image_resized = tf.image.resize_images(image_decoded, [28, 28])
return image_resized,label
dataset = tf.data.Dataset.from_tensor_slices((files,label))
# you can use batch() to set batch_size
dataset = dataset.map(read_image).shuffle(1000).batch(2)
print(dataset.output_shapes)
print(dataset.output_types)
(TensorShape([Dimension(None), Dimension(28), Dimension(28), Dimension(None)]), TensorShape([Dimension(None)]))
(tf.float32, tf.int32)
最后,您定义迭代器以获取批处理数据。
iterator = dataset.make_initializable_iterator()
next_element = iterator.get_next()
with tf.Session() as sess:
for _ in range(2):
sess.run(iterator.initializer)
batch_image,batch_label = sess.run(next_element)
print(batch_image.shape)
print(batch_label.shape)
(2, 28, 28, 4)
(2,)
(2, 28, 28, 4)
(2,)