【发布时间】:2021-08-07 14:25:32
【问题描述】:
我正在处理计算机视觉项目,我的图像是 webp 和 jpeg 的组合。我正在使用 tensorflow '2.3.2'
你可以这样想我的目录:
IMAGES
|-img1.jpeg
|-img2.webp
对于阅读 webp,我使用 tfio.image.decode_webp,在阅读 jpeg 时,我使用 tf.image.decode_jpeg(img, channels=3)。这是代码:
def load(file_path):
img = tf.io.read_file(file_path)
extension = tf.strings.split(file_path,sep=".")
if extension[-1] == "webp" :
img = tfio.image.decode_webp(img)
else :
img = tf.image.decode_jpeg(img, channels=3)
#img preprocess here
return img
def create_dataset(df,batch_size):
image = df["image_path"]
# I'm working on MultiTaskLearning so I have multiple targets
target1 = df["target1"].to_numpy()
target2 = df["target2"].to_numpy()
ds = tf.data.Dataset.from_tensor_slices((image,target1,target2))
ds = ds.map(lambda image, target1,target2: (load(image), {"target1":target1, "target2":target2}), num_parallel_calls=tf.data.experimental.AUTOTUNE)
ds = ds.batch(batch_size)
ds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
return ds
dataset = create_dataset(df,100)
问题是,webp 被转换为 4 通道(RGBA)张量,其中解码 jpeg 位于 3 通道(RGB)中。这会在我的数据集中造成不一致,因为该模型仅包含 3 通道图像。
我能想到的一个解决方案是通过this 将我所有的 webp 转换为 jpeg。但是有没有更好的解决方案呢?比如在 TensorFlow 中将 4 通道转换为 3 通道,或者在 TensorFlow 中将 webp 读取为 3 通道,或者我可以将解决方案放入我的 python 脚本中的其他任何东西?
【问题讨论】:
-
如果你想用
jpeg和webp训练一个模型,那么你需要为两者创建相同的输入层布局。无需转换图像,只需在load之后转换img张量即可。已经有一个很好的答案解释了如何在 SO:stackoverflow.com/a/58748986/1622937 上对 numpy 数组进行 RGBA>RGB 转换(提示:img.numpy()) -
感谢您的建议。您提出的解决方案似乎非常好。但是当我尝试应用它时,它会提高
AttributeError: 'Tensor' object has no attribute 'numpy'。我认为这与 tensorflow 急切执行无法正常工作有关。即使没有 numpy,在图像解码步骤后打印 tensor.shape (None,None,None) -
我已经用我使用的更多代码更新了问题
-
您可以使用
tfio.experimental.color.rgba_to_rgb。它应该在图形模式下工作。您应该注意,此方法仅获取 RGBA 图像的 RGB 部分。如果您的图像没有透明度,那就足够了。 -
@Lescurel 将其调整为从 rgba 到 rgb 的正确转换应该相当简单。我去试试……
标签: python tensorflow