简体   繁体   中英

“TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed.” when calling map function on dataset

I am trying to load and process images with an unique crop factor learned from each image. I keep getting an error stating I can't use a tensor as a Python boolean.

For each image, I want to threshold one row of pixels from the center of the image and calculate the percent of pixels over some threshold. I want to use that percentage as a crop factor.

def preprocess_image(image):
    image = tf.image.decode_png(image, channels=3)
    print(tf.shape(image))
    halfpix = tf.shape(image)[0]//2
    row = tf.cast(tf.math.greater(image[:, :, 0][halfpix, :], 3), tf.float32)
    hor_scale_factor = tf.math.reduce_mean(row)
    image = tf.image.central_crop(image, hor_scale_factor)

    return image

def load_and_preprocess_image(path):
    image = tf.io.read_file(path)
    return preprocess_image(image)

train_image_ds = train_path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)

I expect no error. I receive: "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."

Full trace:

TypeError                                 Traceback (most recent call last) <ipython-input-89-b7d7da47ff6e> in <module>
----> 1 train_image_ds = train_path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)
      2 test_image_ds = test_path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py in map(self, map_func, num_parallel_calls)    1144     else:    1145   return ParallelMapDataset(
-> 1146           self, map_func, num_parallel_calls, preserve_cardinality=True)    1147     1148   def flat_map(self, map_func):

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py in __init__(self, input_dataset, map_func, num_parallel_calls, use_inter_op_parallelism, preserve_cardinality, use_legacy_function)   3262         self._transformation_name(),    3263         dataset=input_dataset,
-> 3264         use_legacy_function=use_legacy_function)    3265     self._num_parallel_calls = ops.convert_to_tensor(    3266         num_parallel_calls, dtype=dtypes.int32, name="num_parallel_calls")

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py in __init__(self, func, transformation_name, dataset, input_classes, input_shapes, input_types, input_structure, add_to_graph, use_legacy_function, defun_kwargs)    2589       resource_tracker = tracking.ResourceTracker()    2590       with tracking.resource_tracker_scope(resource_tracker):
-> 2591         self._function = wrapper_fn._get_concrete_function_internal()    2592         if add_to_graph:    2593           self._function.add_to_graph(ops.get_default_graph())

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\eager\function.py in _get_concrete_function_internal(self, *args, **kwargs)    1364     """Bypasses error checking when getting a graph function."""    1365   graph_function = self._get_concrete_function_internal_garbage_collected(
-> 1366         *args, **kwargs)    1367     # We're returning this concrete function to someone, and they may keep a    1368     # reference to the FuncGraph without keeping a reference to the

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\eager\function.py in _get_concrete_function_internal_garbage_collected(self, *args,
**kwargs)    1358     if self.input_signature:    1359       args, kwargs = None, None
-> 1360     graph_function, _, _ = self._maybe_define_function(args, kwargs)    1361     return graph_function    1362 

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\eager\function.py in _maybe_define_function(self, args, kwargs)    1646       graph_function = self._function_cache.primary.get(cache_key, None)    1647       if graph_function is None:
-> 1648         graph_function = self._create_graph_function(args, kwargs)    1649         self._function_cache.primary[cache_key] = graph_function    1650       return graph_function, args, kwargs

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\eager\function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)    1539             arg_names=arg_names,    1540             override_flat_arg_shapes=override_flat_arg_shapes,
-> 1541             capture_by_value=self._capture_by_value),    1542         self._function_attributes)    1543 

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\framework\func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    714                                           converted_func)
    715 
--> 716       func_outputs = python_func(*func_args, **func_kwargs)
    717 
    718       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py in wrapper_fn(*args)    2583           attributes=defun_kwargs)    2584       def wrapper_fn(*args):  # pylint: disable=missing-docstring
-> 2585         ret = _wrapper_helper(*args)    2586         ret = self._output_structure._to_tensor_list(ret)    2587         return [ops.convert_to_tensor(t) for t in ret]

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py in _wrapper_helper(*args)    2528         nested_args = (nested_args,) 2529 
-> 2530       ret = func(*nested_args)    2531       # If `func` returns a list of tensors, `nest.flatten()` and    2532       # `ops.convert_to_tensor()` would conspire to attempt to stack

<ipython-input-86-61d7ec60892c> in load_and_preprocess_image(path)
      1 def load_and_preprocess_image(path):
      2     image = tf.io.read_file(path)
----> 3     return preprocess_image(image)

<ipython-input-85-4f3b9475e191> in preprocess_image(image)
     11     hor_scale_factor = tf.math.reduce_mean(row)
     12 #     print(hor_scale_factor)
---> 13     image = tf.image.central_crop(image, hor_scale_factor)
     14 #     print(type(hor_scale_factor))
     15     image = tf.image.resize(image, target_im_size, preserve_aspect_ratio=True) # Resize to final dimensions

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\ops\image_ops_impl.py in central_crop(image, central_fraction)
    641   with ops.name_scope(None, 'central_crop', [image]):
    642     image = ops.convert_to_tensor(image, name='image')
--> 643     if central_fraction <= 0.0 or central_fraction > 1.0:
    644       raise ValueError('central_fraction must be within (0, 1]')
    645     if central_fraction == 1.0:

c:\users\toby-pc\documents\code\blindness_kaggle\my_env\lib\site-packages\tensorflow\python\framework\ops.py in __bool__(self)
    696       `TypeError`.
    697     """
--> 698     raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
    699                     "Use `if t is not None:` instead of `if t:` to test if a "
    700                     "tensor is defined, and use TensorFlow ops such as "

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.

tf.image.central_crop requires the central_fraction parameter to be an actual float value, so TensorFlow tensors cannot be used. It is easy to replicate the functionality though, for example with tf.image.crop_to_bounding_box (or even just with slicing, which is what that function really does):

import tensorflow as tf

def central_crop_tf(image, central_fraction):
    s = tf.shape(image)
    h, w = s[-3], s[-2]
    h_box = tf.cast(tf.round(central_fraction * tf.cast(h, tf.float32)), tf.int32)
    w_box = tf.cast(tf.round(central_fraction * tf.cast(w, tf.float32)), tf.int32)
    h_off = (h - h_box) // 2
    w_off = (w - w_box) // 2
    return tf.image.crop_to_bounding_box(image, h_off, w_off, h_box, w_box)

# Test
with tf.Graph().as_default(), tf.Session() as sess:
    img = tf.reshape(tf.range(80), [1, 8, 10, 1])
    print(sess.run(img)[0, :, :, 0])
    # [[ 0  1  2  3  4  5  6  7  8  9]
    #  [10 11 12 13 14 15 16 17 18 19]
    #  [20 21 22 23 24 25 26 27 28 29]
    #  [30 31 32 33 34 35 36 37 38 39]
    #  [40 41 42 43 44 45 46 47 48 49]
    #  [50 51 52 53 54 55 56 57 58 59]
    #  [60 61 62 63 64 65 66 67 68 69]
    #  [70 71 72 73 74 75 76 77 78 79]]
    frac = tf.constant(0.4)
    res = central_crop_tf(img, frac)
    print(sess.run(res)[0, :, :, 0])
    # [[23 24 25 26]
    #  [33 34 35 36]
    #  [43 44 45 46]]

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