如何将 TensorFlow 2 中的 crop_to_bounding_box 应用于符号张量?

How to apply crop_to_bounding_box in TensorFlow 2 to a symbolic tensor?

我有以下代码,旨在找到像素强度 >= 25 的第一个和最后一个像素,然后裁剪到该边界框:

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

但是,我一直收到错误提示 tf.image.crop_to_bounding_box 中的 target_height 必须大于 0。在我所有的图像中,last_white_pixel[0] - first_white_pixel[0] 绝对高于 0。代码在 TensorFlow 2.3 中作为符号张量执行,并且在非符号设置中运行良好(因为缺少更好的术语)。

我的错误似乎是切片错误。而不是写

first_white_pixel = white_pixels[:, 0]
last_white_pixel = white_pixels[:, -1]

我应该写

first_white_pixel = white_pixels[0, :]
last_white_pixel = white_pixels[-1, :]