将张量映射到张量流中的操作

时间:2018-07-23 17:45:55

标签: tensorflow

我正在尝试将多个tf.write_file操作合并到一个操作中,以在单个Session.run()调用中保存一批图像,但是没有运气。

此代码:

r = tf.range(tf.shape(images)[0])
crops = tf.image.crop_and_resize(images, boxes, r, [160, 160])
crops = tf.image.convert_image_dtype(crops, dtype=tf.uint8)

def write_ith_image(i):
    nonlocal out_file_tensor, crops
    encoded_image = tf.image.encode_jpeg(crops[i])
    return tf.write_file(out_file_tensor[i], encoded_image)

encode_all = tf.map_fn(write_ith_image, r)

导致:

TypeError: Can't convert Operation 'map/while/WriteFile' to Tensor (target dtype=None, name='value', as_ref=False)

tf.while_loop给出相似的结果。有没有办法将张量映射到可以在单个tf.Session.run()调用中执行的一组操作?为什么这适用于张量,但不适用于具有副作用的操作?

1 个答案:

答案 0 :(得分:2)

您可以返回一个虚拟值。

def write_ith_image(i):
    nonlocal out_file_tensor, crops
    encoded_image = tf.image.encode_jpeg(crops[i])
    with tf.control_dependencies([tf.write_file(out_file_tensor[i], encoded_image)]):
      dummy = tf.constant([0])
    return dummy

encode_all = tf.map_fn(write_ith_image, r)

不漂亮,但是可以完成工作。

使用tf.while_loop可以使您满意一些(没有伪值),但这会更冗长,而且效率可能更高。

相关问题