mic*_*ael 11 python tensorflow2.0
我正在尝试做tensorflow等效的torch.transforms.Resize(TRAIN_IMAGE_SIZE),它将最小的图像尺寸调整为TRAIN_IMAGE_SIZE. 像这样的东西
def transforms(filename):
parts = tf.strings.split(filename, '/')
label = parts[-2]
image = tf.io.read_file(filename)
image = tf.image.decode_jpeg(image)
image = tf.image.convert_image_dtype(image, tf.float32)
# this doesn't work with Dataset.map() because image.shape=(None,None,3) from Dataset.map()
image = largest_sq_crop(image)
image = tf.image.resize(image, (256,256))
return image, label
list_ds = tf.data.Dataset.list_files('{}/*/*'.format(DATASET_PATH))
images_ds = list_ds.map(transforms).batch(4)
Run Code Online (Sandbox Code Playgroud)
简单的答案在这里:Tensorflow:裁剪图像的最大中心正方形区域
但是当我使用 with 的方法时tf.data.Dataset.map(transforms),我shape=(None,None,3)从内部获取largest_sq_crop(image)。当我正常调用它时,该方法工作正常。
我找到了答案。这与我的调整大小方法在急切执行中工作良好的事实有关,例如,tf.executing_eagerly()==True但在dataset.map(). 显然,在那个执行环境中,tf.executing_eagerly()==False.
我的错误在于我解压图像的形状以获得缩放尺寸的方式。Tensorflow 图执行似乎不支持访问元tensor.shape组。
# wrong
b,h,w,c = img.shape
print("ERR> ", h,w,c)
# ERR> None None 3
# also wrong
b = img.shape[0]
h = img.shape[1]
w = img.shape[2]
c = img.shape[3]
print("ERR> ", h,w,c)
# ERR> None None 3
# but this works!!!
shape = tf.shape(img)
b = shape[0]
h = shape[1]
w = shape[2]
c = shape[3]
img = tf.reshape( img, (-1,h,w,c))
print("OK> ", h,w,c)
# OK> Tensor("strided_slice_2:0", shape=(), dtype=int32) Tensor("strided_slice_3:0", shape=(), dtype=int32) Tensor("strided_slice_4:0", shape=(), dtype=int32)
Run Code Online (Sandbox Code Playgroud)
我在函数下游使用形状尺寸dataset.map(),它引发了以下异常,因为它获取的是None而不是值。
TypeError: Failed to convert object of type <class 'tuple'> to Tensor. Contents: (-1, None, None, 3). Consider casting elements to a supported type.
Run Code Online (Sandbox Code Playgroud)
当我切换到手动解压形状时tf.shape(),一切正常。