TensorFlow中的图像转换会随着时间的推移而减慢

Bup*_*eth 4 python tensorflow

我有这种方法拍摄图像并将其转换为张量.我在一个循环中调用它,转换的执行时间开始很小并且不断增长.

def read_tensor_from_image_file(file_name, input_height=299, input_width=299, input_mean=0, input_std=255):
    input_name = "file_reader"
    output_name = "normalized"
    file_reader = tf.read_file(file_name, input_name)

    image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
        name='jpeg_reader')
    float_caster = tf.cast(image_reader, tf.float32)
    dims_expander = tf.expand_dims(float_caster, 0)
    resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
    normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
    sess = tf.Session()
    result = sess.run(normalized)

    return result
Run Code Online (Sandbox Code Playgroud)

我该如何优化?

mrr*_*rry 7

问题几乎可以肯定是由于tf.Graphread_tensor_from_image_file()函数的多次调用中使用了相同的默认值.解决此问题的最简单方法是with tf.Graph().as_default():在函数体周围添加一个块,如下所示:

def read_tensor_from_image_file(file_name, input_height=299, input_width=299, input_mean=0, input_std=255):
   with tf.Graph().as_default():
    input_name = "file_reader"
    output_name = "normalized"
    file_reader = tf.read_file(file_name, input_name)
    image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
        name='jpeg_reader')
    float_caster = tf.cast(image_reader, tf.float32)
    dims_expander = tf.expand_dims(float_caster, 0)
    resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
    normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
    sess = tf.Session()
    result = sess.run(normalized)
    return result
Run Code Online (Sandbox Code Playgroud)

通过此更改,对函数的每次调用都将创建一个新图形,而不是向节点添加默认图形(随后会随着时间的推移而增长,泄漏内存,并且每次使用它时需要更长时间才能启动).

更高效的版本将使用tf.placeholder()的文件名,构建一个图,并移动for循环的TensorFlow会议.像下面这样的东西会起作用:

def read_tensors_from_image_files(file_names, input_height=299, input_width=299, input_mean=0, input_std=255):
   with tf.Graph().as_default():
    input_name = "file_reader"
    output_name = "normalized"
    file_name_placeholder = tf.placeholder(tf.string, shape=[])
    file_reader = tf.read_file(file_name_placeholder, input_name)
    image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
        name='jpeg_reader')
    float_caster = tf.cast(image_reader, tf.float32)
    dims_expander = tf.expand_dims(float_caster, 0)
    resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
    normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])

    with tf.Session() as sess:
      for file_name in file_names:
        yield sess.run(normalized, {file_name_placeholder: file_name})
Run Code Online (Sandbox Code Playgroud)