TensorFlow Resize image tensor to dynamic shape
<p>I am trying to read some image input for an image classification problem with TensorFlow.</p>

<p>Of course, I am doing this with <code>tf.image.decode_jpeg(...)</code>. My images have variable size and hence I am not able to specify a fixed shape for the image tensor.</p>

<p>But I need to scale the images depending on their actual size. Specifically, I want to scale the shorter side to a fixed value and the longer side in a way that the aspect ratio is preserved.</p>

<p>I can get the actual shape of a certain image by <code>shape = tf.shape(image)</code>. I am also able to do the computation for the new longer edge like </p>

<pre><code>shape = tf.shape(image)
height = shape[0]
width = shape[1]
new_shorter_edge = 400
if height &lt;= width:
    new_height = new_shorter_edge
    new_width = ((width / height) * new_shorter_edge)
else:
    new_width = new_shorter_edge
    new_height = ((height / width) * new_shorter_edge)
</code></pre>

<p>My problem now is that I cannot pass <code>new_height</code> and <code>new_width</code> to <code>tf.image.resize_images(...)</code> because one of them is a tensor and <code>resize_images</code> expects integers as height and width inputs.</p>

<p>Is there a way to "pull out" the integer of the tensor or is there any other way to do my task with TensorFlow?</p>

<p>Thanks in advance.</p>

<hr>

<p><strong>Edit</strong></p>

<p>Since I also had <a href="https://github.com/tensorflow/tensorflow/issues/1029" rel="noreferrer">some other issues</a> with <code>tf.image.resize_images</code>, here's the code that worked for me:</p>

<pre><code>shape = tf.shape(image)
height = shape[0]
width = shape[1]
new_shorter_edge = tf.constant(400, dtype=tf.int32)

height_smaller_than_width = tf.less_equal(height, width)
new_height_and_width = tf.cond(
    height_smaller_than_width,
    lambda: (new_shorter_edge, _compute_longer_edge(height, width, new_shorter_edge)),
    lambda: (_compute_longer_edge(width, height, new_shorter_edge), new_shorter_edge)
)

image = tf.expand_dims(image, 0)
image = tf.image.resize_bilinear(image, tf.pack(new_height_and_width))
image = tf.squeeze(image, [0])
</code></pre>