Reputation: 3677
I'm trying to combine a number of tf.write_file ops into single op to save a batch of images inside single Session.run() call, with no luck.
This code:
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)
results in:
TypeError: Can't convert Operation 'map/while/WriteFile' to Tensor (target dtype=None, name='value', as_ref=False)
tf.while_loop
gives similar results. Is there a way to map a tensor to a group of operations that can be executed in single tf.Session.run() call? Why this works for tensors, but not for operations with side effects?
Upvotes: 1
Views: 226
Reputation: 24581
You could return a dummy value.
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)
Not pretty, but gets the job done.
You could get something slightly more satisfying with tf.while_loop
(no dummy values), but it would be more verbose and probably not any more efficient.
Upvotes: 2