简体   繁体   中英

tf2.0: tf.image.resize_with_pad fails with “using a `tf.Tensor` as a Python `bool” with tf.keras.Input

With tensorflow 2.0 , resize_with_pad does not seem to work when tf.keras.Input is given as an input, but resize works nicely. For example,

import tensorflow as tf

# with tensorflow constant
img_arr = tf.zeros([1,100,100,3])
tf.image.resize(img_arr, [224, 224]) # works
tf.image.resize_with_pad(img_arr, 224, 224) # works

# with keras input
img_arr = tf.keras.Input(shape = (100,100,3))
tf.image.resize(img_arr, [224, 224]) # works
tf.image.resize_with_pad(img_arr, 224, 224) # doesn't work

throws an error

---------------------------------------------------------------------------
OperatorNotAllowedInGraphError            Traceback (most recent call last)
<ipython-input-29-aee2cbd13944> in <module>
      9 img_arr = tf.keras.Input(shape = (100,100,3))
     10 tf.image.resize(img_arr, [224, 224]) # works
---> 11 tf.image.resize_with_pad(img_arr, 224, 224) # doesn't work

/anaconda3/envs/ml/lib/python3.6/site-packages/tensorflow_core/python/ops/image_ops_impl.py in resize_image_with_pad_v2(image, target_height, target_width, method, antialias)
   1472 
   1473   return _resize_image_with_pad_common(image, target_height, target_width,
-> 1474                                        _resize_fn)
   1475 
   1476 

/anaconda3/envs/ml/lib/python3.6/site-packages/tensorflow_core/python/ops/image_ops_impl.py in _resize_image_with_pad_common(image, target_height, target_width, resize_fn)
   1337       raise ValueError('\'image\' must have either 3 or 4 dimensions.')
   1338 
-> 1339     assert_ops = _CheckAtLeast3DImage(image, require_static=False)
   1340     assert_ops += _assert(target_width > 0, ValueError,
   1341                           'target_width must be > 0.')

/anaconda3/envs/ml/lib/python3.6/site-packages/tensorflow_core/python/ops/image_ops_impl.py in _CheckAtLeast3DImage(image, require_static)
    226         check_ops.assert_positive(
    227             array_ops.shape(image),
--> 228             ["all dims of 'image.shape' "
    229              'must be > 0.']),
    230         check_ops.assert_greater_equal(

/anaconda3/envs/ml/lib/python3.6/site-packages/tensorflow_core/python/ops/check_ops.py in assert_positive(x, data, summarize, message, name)
    266           'x (%s) = ' % name, x]
    267     zero = ops.convert_to_tensor(0, dtype=x.dtype)
--> 268     return assert_less(zero, x, data=data, summarize=summarize)
    269 
    270 

/anaconda3/envs/ml/lib/python3.6/site-packages/tensorflow_core/python/ops/check_ops.py in assert_less(x, y, data, summarize, message, name)
    865       ]
    866     condition = math_ops.reduce_all(math_ops.less(x, y))
--> 867     return control_flow_ops.Assert(condition, data, summarize=summarize)
    868 
    869 

/anaconda3/envs/ml/lib/python3.6/site-packages/tensorflow_core/python/util/tf_should_use.py in wrapped(*args, **kwargs)
    196   """
    197   def wrapped(*args, **kwargs):
--> 198     return _add_should_use_warning(fn(*args, **kwargs))
    199   return tf_decorator.make_decorator(
    200       fn, wrapped, 'should_use_result',

/anaconda3/envs/ml/lib/python3.6/site-packages/tensorflow_core/python/ops/control_flow_ops.py in Assert(condition, data, summarize, name)
    147   """
    148   if context.executing_eagerly():
--> 149     if not condition:
    150       xs = ops.convert_n_to_tensor(data)
    151       data_str = [_summarize_eager(x, summarize) for x in xs]

/anaconda3/envs/ml/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py in __bool__(self)
    763       `TypeError`.
    764     """
--> 765     self._disallow_bool_casting()
    766 
    767   def __nonzero__(self):

/anaconda3/envs/ml/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py in _disallow_bool_casting(self)
    532     else:
    533       # Default: V1-style Graph execution.
--> 534       self._disallow_in_graph_mode("using a `tf.Tensor` as a Python `bool`")
    535 
    536   def _disallow_iteration(self):

/anaconda3/envs/ml/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py in _disallow_in_graph_mode(self, task)
    521     raise errors.OperatorNotAllowedInGraphError(
    522         "{} is not allowed in Graph execution. Use Eager execution or decorate"
--> 523         " this function with @tf.function.".format(task))
    524 
    525   def _disallow_bool_casting(self):

OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.

This might be a bug in Tensorflow Version 2.0 but it is fixed in Tensorflow Version 2.1 .

So, please upgrade your Tensorflow Version to either 2.1 or 2.2 and the issue will be resolved.

Working code is mentioned below:

!pip install tensorflow==2.2

import tensorflow as tf
print(tf.__version__)

img_arr = tf.keras.Input(shape = (100,100,3))
tf.image.resize(img_arr, [224, 224]) # works
tf.image.resize_with_pad(img_arr, 224, 224) # # works now in TF >= 2.1

Output:

2.2.0

<tf.Tensor 'Pad_1:0' shape=(None, 224, 224, 3) dtype=float32>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM