# TensorFlow: Resizing Image by Keeping Aspect Ratio

It is very common to resize image by keeping aspect ratio in vision community. The python relevant code is intuitive and simple, which looks like:

The if conditional statement naturally navigates us to do what we expect to do. As a result, when it comes to TensorFlow, we are prone to achieve the same goal to write the following code:

Before it runs as you expected, the following bug would be thrown out:

raise TypeError(“Using a tf.Tensor as a Python bool is not allowed. “. TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if t is not None: instead of if t: to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

It seems TensorFlow does not support python-like if numeric comparison. Instead, we must turn to tf.cond function to solve this problem. First, let’s take a look at part of the tf.cond official doc:

With is in mind, tf.cond leaves us three things to do:

• pred, a boolean function determining which side of image to resize. Usually tf.greater(), tf.less() are the choices. If the combination of several unary predictors together is necessary, we might need to use tf.logical_and()
• true_fn, please note that the parameter true_fn is a callable function, not the return value of a function.
• false_fn, the same as true_fn

We naturally want true_fn() returns the resized image tensor while false_fn() returns the original image. Thus, the following conversion is just what we want:

Similarily, the other if conditional statement can be rewritten as:

Please pay careful attention to lambda, which guarantees the return of resize_img_tensor_accod_x() is a function. Otherwise extra errors will come out.

## Farewell Word

It seems TensorFlow holds large difference with Python language. Spending more time to read the official doc and sample code becomes necessary!