&引用;TypeError:不允许将'tf.Tensor'用作Python'bool';在数据集上调用map函数时
我试图加载和处理图像,并从每个图像中学习一个独特的裁剪因子。我不断收到一个错误,说明我不能将张量用作Python布尔值 对于每个图像,我想从图像中心设置一行像素的阈值,并计算超过某个阈值的像素百分比。我想用这个百分比作为作物系数&引用;TypeError:不允许将'tf.Tensor'用作Python'bool';在数据集上调用map函数时,python,tensorflow,image-processing,keras,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
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)
我希望没有错误。我收到:“类型错误:不允许将tf.Tensor
用作Pythonbool
。如果t不是None,则使用而不是if t:
来测试是否定义了张量,并使用诸如tf.cond的TensorFlow操作来执行以张量值为条件的子图。”
完整跟踪:
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.
TypeError回溯(最近一次调用最后一次)
---->1列车图像\u ds=列车路径\u ds.map(加载和预处理图像,并行调用数=自动调谐)
2 test\u image\u ds=test\u path\u ds.map(加载和预处理\u image,num\u parallel\u calls=AUTOTUNE)
c:\users\toby pc\documents\code\blindness\u kaggle\my_env\lib\site packages\tensorflow\python\data\ops\dataset\ops.py in map(self,map\u func,num\u parallel\u calls)1144其他:1145返回ParallelMapDataset(
->1146 self,map_func,num_parallel_调用,preserve_cardinality=True)1147 1148 def flat_map(self,map_func):
c:\users\toby pc\documents\code\blindness\u kaggle\my_env\lib\site packages\tensorflow\python\data\ops\dataset\ops.py in uuuu init_uuuuuuuu(self,input_dataset,map_func,num_parallel_u调用,使用u inter o o o o o并行,保留基数,使用o遗留o函数)3262; 3262; 3262; self转换,
->3264使用旧函数=使用旧函数)3265 self.\u num\u parallel\u calls=ops.convert\u to\u tensor(3266 num\u parallel\u calls,dtype=dtypes.int32,name=“num\u parallel\u calls”)
c:\users\toby pc\documents\code\blindness\u kaggle\my_env\lib\site packages\tensorflow\python\data\ops\dataset\ops.py in\uuuuu init\uuuuuuuuuuu(self,func,transformation\u name,dataset,input\u类,input\u形状,input\u类型,input\u结构,添加到图中,使用遗留函数,defun\ukwargs)2589 resource\u tracker=tracker.ResourceTracker()2590带跟踪。资源跟踪者范围(资源跟踪者):
->2591 self.\u function=wrapper\u fn.\u get\u concrete\u function\u internal()2592如果将\u添加到图中:2593 self.\u function.将\u添加到图中(ops.get\u default\u graph())
c:\users\toby pc\documents\code\blindness\u kaggle\my\u env\lib\site packages\tensorflow\python\eager\function.py in\u get\u concrete\u function\u internal(self,*args,**kwargs)1364”““获取图形函数时绕过错误检查。”“1365 graph\u function=self.\u get\u concrete\u function\u internal\u垃圾收集”(
->1366*args,**kwargs)1367#我们将这个具体函数返回给某人,他们可能保留对FuncGraph的1368#引用,而不保留对
c:\users\toby pc\documents\code\blindness\u kaggle\my\u env\lib\site packages\tensorflow\python\eager\function.py in\u get\u concrete\u function\u internal\u garbage\u collected(self,*args,
**kwargs)1358如果self.input_签名:1359 args,kwargs=None,None
->1360图形函数,可能定义函数(args,kwargs)1361返回图形函数1362
c:\users\toby pc\documents\code\blindness\u kaggle\my\u env\lib\site packages\tensorflow\python\eager\function.py in\u mayby\u define\u function(self,args,kwargs)1646 graph\u function=self.\u function\u cache.primary.get(cache\u key,None)1647如果graph\u function为None:
->1648 graph_function=self.\u create_graph_function(args,kwargs)1649 self.\u function_cache.primary[cache_key]=graph_function 1650返回graph_function,args,kwargs
c:\users\toby pc\documents\code\blindness\u kaggle\my_env\lib\site packages\tensorflow\python\eager\function.py in\u create\u graph\u函数(self、args、kwargs、override\u flat\u arg\u shapes)1539 arg\u name=arg\u name,1540 override\u flat\u arg\u arg\u shapes=override\u flat\u arg\u arg\u shapes,
->1541按值捕获=自身。按值捕获),1542自身。功能属性)1543
c:\users\toby pc\documents\code\blindness\u kaggle\my\u env\lib\site packages\tensorflow\python\framework\func\u graph.py来自func\u py func(名称、python\u func、args、kwargs、签名、函数图、自动签名、自动签名、自动签名选项、添加控制依赖项、参数名、op\u返回值、集合、按值捕获、覆盖平面arg\u形状)
714(转换函数)
715
-->716 func_outputs=python_func(*func_args,**func_kwargs)
717
718#不变量:`func_outputs`只包含张量、复合传感器、,
c:\users\toby pc\documents\code\blindness\u kaggle\my_env\lib\site packages\tensorflow\python\data\ops\dataset\ops.py在wrapper\u fn(*args)2583 attributes=defun\u kwargs)2584 def wrapper\u fn(*args):\pylint:disable=缺少docstring
->2585 ret=_包装器_帮助器(*args)2586 ret=self._输出_结构._to_张量_列表(ret)2587返回[ops.convert_to_张量(t)for t in ret]
c:\users\toby pc\documents\code\blindness\u kaggle\my_env\lib\site packages\tensorflow\python\data\ops\dataset\ops.py in _wrapper\u helper(*args)2528嵌套的参数=(嵌套的参数,)2529
->2530 ret=func(*nested_args)2531#如果'func'返回一个张量列表,'nest.flatte()`和2532#'ops.convert_to_tensor()`将合谋尝试堆栈
在加载和预处理图像中(路径)
1 def加载和预处理图像(路径):
2 image=tf.io.read\u文件(路径)
---->3返回预处理图像(图像)
在预处理_图像(图像)中
11水平比例系数=tf.数学减少平均值(行)
1.
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]]