2

我正在尝试训练神经网络在对象周围绘制边界框。我自己生成了数据,256x256 rgb 图像和每个图像五个标签(边界框的两个角 + 一个旋转组件)。为了在使用 python 3.7.6、tensorflow 2.0 和 keras 训练网络时不会耗尽内存,我一次只加载了少量图像。然后网络对这些进行了训练,然后加载了一组新图像。这一切都是按顺序发生的(我不是一个很好的程序员,可能不是以一种有效的方式),这给我留下了由于我加载图像和标签的方式而出现的一个非常严重的瓶颈。图像名称以数值形式给出,当前保存为 .jpg,我的标签存储在文本文件中,其中每一行对应一个图像名称。

为了减少/消除瓶颈,我已经阅读了 tf.data 并尝试按照https://www.tensorflow.org/tutorials/load_data/images#using_tfdata_for_finer_control中的示例进行操作。然而,这些示例处理分类,因此标签以不同的方式生成。我试图改变这样的代码

import numpy as np
import tensorflow as tf
import os

height=256
width=256

AUTOTUNE = tf.data.experimental.AUTOTUNE
image_count=len(os.listdir('images_train'))

list_ds = tf.data.Dataset.list_files(str('images_train/*'), shuffle=False)
list_ds = list_ds.shuffle(image_count, reshuffle_each_iteration=False)

print('\n')
for f in list_ds.take(5):
    
    print(f.numpy())
   
def decode_img(img):
    # convert the compressed string to a 3D uint8 tensor
    img = tf.image.decode_jpeg(img, channels=3)
    # resize the image to the desired size
    return tf.image.resize(img, [height, width])  

#This is the function I cannot figure out how to write
def get_label(file_path):
    labels=np.loadtxt('labels_train.txt', delimiter=',')
    # convert the path to a list of path components
    parts = tf.strings.split(file_path, os.path.sep)
    
    #somehow I would like to extract the name of the image file and then take the numerical part and 
    #return the corresponding row
    return labels[0,:]
   
def process_path(file_path):
    label = get_label(file_path)
    # load the raw data from the file as a string
    img = tf.io.read_file(file_path)
    img = decode_img(img)
    return img, label

train_ds = list_ds.map(process_path, num_parallel_calls=AUTOTUNE)

当我从文件中返回一行时,脚本的其余部分似乎运行良好,但我无法弄清楚如何制作它,以便每个图像都与其对应的标签配对。为了在get_label()函数中提取图像名称,我尝试使用parts.numpy()它只产生 this AttributeError: 'Tensor' object has no attribute 'numpy'

几天来,我一直试图弄清楚这一点,但找不到完全描述相同问题的帖子。

如果不是熟练的程序员,如何以有效的方式解决这个问题?任何指出我正确方向的东西都非常感谢。

编辑:我最终选择了一个不同的解决方案,该解决方案深受https://github.com/kalasuffar/tensorflow-data/blob/master/create_dataset.py示例的启发。它发现我更容易按照那里给出的示例进行操作。

4

0 回答 0