tf.image.resize 后 Matplotlib 图变为空白

Matplotlib plot becomes blank after tf.image.resize

我有一些用于 tensorflow 数据集的代码。 它以前工作得很好,它可能仍然有效。但我不这么认为

img = parse_image(img_paths[0])
img = tf.image.resize(img, [224, 224])
plt.imshow(img)

只是输出一个空白224x224 canvas.

img = parse_image(img_paths[0])
plt.imshow(img)

正确输出图像。

img_paths 是带有路径名的字符串列表

我试过:

img = parse_image(img_paths[0])
img = tf.image.resize([img], [224, 224])
plt.imshow(img[0])

img = parse_image(img_paths[0])
img = tf.image.resize(img, [224, 224])
plt.imshow(img.numpy())

img = parse_image(img_paths[0])
img = tf.image.resize([img], [224, 224])
plt.imshow(img.numpy()[0])

形状正确,此代码以前有效。 并且可能仍然有效,我想我可能不会再正确使用它了(自从我写它以来已经有一段时间了)。

感谢您提供任何提示或想法?当然还有解决方案 ;-)

呵呵,

我在别处看到一些东西并添加了这一行:

img = tf.image.convert_image_dtype(img, tf.float32)

在调整大小之前它起作用了。

这非常奇怪,因为我以前不需要这一行。可能是因为版本更新?

无论哪种方式都有效:

img = parse_image(train_img_paths[0])
img = tf.image.convert_image_dtype(img, tf.float32)
img = tf.image.resize(img, [224, 224])
plt.imshow(img)

“问题”出在 Matplotlib 上。当您使用 Tensorflow 调整大小时,它会将您的输入变为浮动。 Matplotlib 接受两种图像格式,0-255 之间的整数和 0 到 1 之间的浮点数。如果您在大于 1 的浮点数上调用 plt.imshow(),它将裁剪所有值,您将看到一个白色图像。这就像你只给 Matplotlib 像素 1.0(或 255)。

tf.image.convert_image_dtype 有一个 saturate 参数,它的默认值使 0-255 整数范围变成 0-1 浮点数。这就是它“有效”的原因,因为 Matplotlib 理解这种格式。在此之后,Tensorflow 调整大小操作也将其保持在 0-1 之间,因此它起作用了。