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

标签 python tensorflow

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

#
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

当我像教程中那样使用简单的图像调整大小时,它会起作用:

#
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  #

这是日志:

    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

最佳答案

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

替换

img_final/= 255.0

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

关于python - 当我尝试在 Tensorflow 中调整图像大小时如何修复 "TypeError: x and y must have the same dtype, got tf.uint8 != tf.float32",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56544619/

相关文章:

python - 矩阵乘法的向量化

tensorflow - ai平台云预测不起作用,但本地预测起作用

tensorflow - 多标签分类的不平衡数据集

python - 在Tensorflow中获取Tensor的原始值

python - selenium.common.exceptions.WebDriverException : Message: Error loading page for the Firefox SSL

python - 使用正则表达式捕获以下捕获组,然后在检测到模式时使用 re sub 方法对它们重新排序

python - 如何使用mechanize进入yelp主页,找到搜索栏,输入 'Dinner'返回结果?

python - 使用opencv进行人脸变形

python - 数据类型的 tensorflow 警告

python - Tensorflow - 时间卷积网络不学习