我尝试设置一个图像管道,为裁剪图像的 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
当我使用教程中的简单图像大小调整时,它可以工作:
#
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