如何检查并调整生成图像尺寸?解决shape为None类型报错
解决图像尺寸调整时的None类型错误
你的问题出在静态形状获取上:image.shape[0]是TensorFlow的静态形状属性,当数据集里的图像尺寸不固定时,静态形状会返回None,导致赋值给h、w后无法比较大小。
要解决这个问题,必须用动态形状获取,也就是tf.shape(image),它会在运行时获取图像的实际尺寸,适合tf.data管道里的动态张量处理。修改后的完整代码如下:
def preprocessing(image, label): # 动态获取图像实际尺寸(运行时) h, w = tf.shape(image)[0], tf.shape(image)[1] # 取宽高中的最大值作为padding后的目标尺寸 size = tf.maximum(h, w) # 计算上下左右的padding偏移量,转为整数张量 top_pad = tf.cast((size - h) / 2, tf.int32) left_pad = tf.cast((size - w) / 2, tf.int32) # 填充为正方形 dst = tf.image.pad_to_bounding_box(image, top_pad, left_pad, size, size) dst = tf.image.resize(dst, size=(2048, 2048)) # 图像增强部分保持不变 dst = tf.image.random_crop(dst, size=(1843, 1843, 3)) dst = tf.image.resize(dst, size=(2048, 2048)) dst = tf.image.random_flip_left_right(dst) dst = tf.cast(dst, tf.float32) dst = (dst / 127.5) - 1 return dst, label dt = dataset_train.map(preprocessing, num_parallel_calls=tf.data.experimental.AUTOTUNE) dt = dt.batch(32).prefetch(3) dv = dv.batch(32).prefetch(3)
关键改动说明:
- 用
tf.shape(image)替代image.shape:动态获取运行时的实际尺寸,避免静态形状为None的问题。 - 用
tf.maximum(h, w)替代三元表达式:更符合TensorFlow的张量操作风格,同时避免Python条件判断对张量的兼容性问题。 - 用
tf.cast转换偏移量类型:pad_to_bounding_box要求偏移量为整数类型张量,直接用Python的int()会报错,因为TensorFlow张量不能直接转为Python整数。
内容的提问来源于stack exchange,提问作者yeon
相关产品推荐
相关产品推荐

