当我尝试在 Tensorflow 中调整图像大小时如何修复“TypeError: x 和 y must have the same dtype, got tf.uint8 != tf.float32”

Ant*_*nt1 4 python tensorflow

我尝试设置一个图像管道,为 Tensorflow 构建一个图像数据集来裁剪图像,但我无法裁剪图片。我遵循了本教程,但我想将文件裁剪为正方形,而不是在不保留纵横比的情况下调整其大小。
这是我的代码:

#
import tensorflow as tf
#

img_raw = tf.io.read_file('./images/4c34476047bcbbfd10b1fd3342605659.jpeg/')

img_tensor = tf.image.decode_jpeg(img_raw, channels=3)

img_final = tf.image.crop_to_bounding_box(
    img_tensor,
    0,
    0,
    200,
    200
)

img_final /= 255.0  # normalize to [0,1] range

Run Code Online (Sandbox Code Playgroud)

当我在教程中使用简单的图像调整大小时,它可以工作:

#
import tensorflow as tf
#

img_raw = tf.io.read_file('./images/4c34476047bcbbfd10b1fd3342605659.jpeg/')

img_tensor = tf.image.decode_jpeg(img_raw, channels=3)

img_final = tf.image.resize(img_tensor, [192, 192])

img_final /= 255.0  #
Run Code Online (Sandbox Code Playgroud)

这是日志:

    img_final /= 255.0  # normalize to [0,1] range
  File ".../.local/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 876, in binary_op_wrapper
    return func(x, y, name=name)
  File ".../.local/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 964, in _truediv_python3
    (x_dtype, y_dtype))
TypeError: x and y must have the same dtype, got tf.uint8 != tf.float32
Run Code Online (Sandbox Code Playgroud)

Add*_*ddy 10

Tensorflow 不进行自动类型转换。解码后的图像似乎是一个带有 dtype 的张量tf.uint8,您必须将其转换tf.float32为才能按预期工作。

代替

img_final /= 255.0

img_final = tf.cast(img_final, tf.float32) / 255.0