- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用从每个图像中学习到的独特裁剪因子来加载和处理图像。我不断收到错误消息,指出我无法将张量用作 Python bool 值。
对于每个图像,我想对图像中心的一行像素进行阈值处理,并计算超过某个阈值的像素百分比。我想使用该百分比作为裁剪因子。
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:
测试是否定义了张量,并使用 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.
最佳答案
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]]
关于python - "TypeError: Using a ` tf.Tensor ` as a Python ` bool ` is not allowed."在数据集上调用map函数时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56999387/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!