“ TypeError:不允许将“ tf.Tensor”用作Python“ bool”。”在数据集上调用地图函数时

时间:2019-07-12 02:11:33

标签: python tensorflow image-processing keras

我正在尝试使用从每幅图像中学到的独特裁切因子加载和处理图像。我不断收到错误消息,指出我无法将张量用作Python布尔值。

对于每张图像,我想对从图像中心开始的一行像素进行阈值处理,并计算超出某个阈值的像素百分比。我想使用该百分比作为作物因子。

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)

我希望没有错误。我收到:“ TypeError:不允许将tf.Tensor作为Python bool使用。使用if t is not None:而不是if t:来测试是否定义了张量,并使用TensorFlow ops例如tf.cond来执行以张量的值为条件的子图。”

完整跟踪:

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.

1 个答案:

答案 0 :(得分:0)

tf.image.central_crop要求central_fraction参数为实际浮点值,因此无法使用TensorFlow张量。不过,例如使用tf.image.crop_to_bounding_box(甚至仅使用切片,该功能实际上就是这样做)来复制功能就很容易了:

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]]