You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow 2中如何对符号张量调用crop_to_bounding_box?

报错原因

该问题由TensorFlow图模式(即你提到的符号张量执行场景)的静态参数校验逻辑导致:你虽然可以确认运行时last_white_pixel[0] - first_white_pixel[0]的结果始终大于0,但在图编译阶段,TensorFlow无法推导这个动态计算的差值张量的取值范围,只会按照通用规则校验tf.image.crop_to_bounding_box的输入合法性,因此会抛出target_height必须大于0的错误。

修复方案

方案1:高度取值兜底(推荐)

对计算得到的裁剪高度加一层最小值限制,保证静态校验阶段就能确认参数符合要求,由于你确认运行时差值始终大于0,这层限制不会改变实际运行结果:

white_pixels = tf.where(input_img >= 25)
first_white_pixel = tf.cast(white_pixels[:, 0], dtype=tf.int32)
last_white_pixel = tf.cast(white_pixels[:, -1], dtype=tf.int32)
# 强制目标高度最小为1,满足静态校验要求
target_height = tf.maximum(last_white_pixel[0] - first_white_pixel[0], 1)
cropped = tf.image.crop_to_bounding_box(input_img, first_white_pixel[0], 0, target_height, 299)

方案2:分支兼容边界场景

如果需要兼容极端情况(比如真的出现差值<=0的异常输入),可以用tf.cond做分支处理,避免裁剪逻辑出错:

white_pixels = tf.where(input_img >= 25)
first_white_pixel = tf.cast(white_pixels[:, 0], dtype=tf.int32)
last_white_pixel = tf.cast(white_pixels[:, -1], dtype=tf.int32)

def normal_crop():
    target_height = last_white_pixel[0] - first_white_pixel[0]
    return tf.image.crop_to_bounding_box(input_img, first_white_pixel[0], 0, target_height, 299)

def fallback_crop():
    # 可自定义兜底逻辑,例如返回原图、返回固定尺寸占位图等
    return input_img

cropped = tf.cond(last_white_pixel[0] > first_white_pixel[0], normal_crop, fallback_crop)

内容的提问来源于stack exchange,提问作者kelkka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 12:06:03