Tensorflow无法从"dataset.map(mapFn)"中的方法获取"image



我正在尝试执行torch.transforms.Resize(TRAIN_IMAGE_SIZE)tensorflow等效项,它将最小的图像尺寸调整为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)

简单的答案在这里:张量流:裁剪图像的最大中心正方形区域

但是当我将该方法与tf.data.Dataset.map(transforms)一起使用时,我从largest_sq_crop(image)内部得到shape=(None,None,3)。当我正常调用它时,该方法工作正常。

我找到了答案。这与我的调整大小方法在急切执行下工作正常有关,例如tf.executing_eagerly()==True,但在dataset.map()内使用时失败。 显然,在那个执行环境中,tf.executing_eagerly()==False.

我的错误在于我解压缩图像形状以获取缩放尺寸的方式。张量流图执行似乎不支持访问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)

我在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.

当我切换到手动从tf.shape()中解压缩形状时,一切正常。

最新更新