我尝试设置一个图像管道,为 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/