【问题标题】:Can't display an image after calling tf.image.rgb_to_grayscale调用 tf.image.rgb_to_grayscale 后无法显示图像
【发布时间】:2020-02-01 18:42:23
【问题描述】:

我正在开发人脸识别应用程序并准备读取 jpg 图像然后训练我的神经网络的数据集。为了提高准确性,我决定将图像转换为灰度(内部映射功能)。 这是我将图像转换为张量的方式:

from PIL import Image

image_data = tf.io.decode_jpeg(
  image_bytes_string,
  channels=3
)

image_data = tf.reshape(image_data , (277, 370, 3))

label = parsed['label']
label = tf.reshape(label, (1,))

return image_data, label

我如何显示图像的代码:

image_data = dataset_item[0].numpy()
img = Image.fromarray(image_data)
img

更改代码转换为灰度后,显示图像的代码显示此错误:

KeyError: ((1, 1, 1), '|u1')
During handling of the above exception, another exception occurred:
Cannot handle this data type

灰度代码:

image_data = tf.io.decode_jpeg(
  image_bytes_string,
  channels=3
)

grayscale = tf.image.rgb_to_grayscale(
  image_data
)

image_data = tf.reshape(grayscale, (277, 370, 1))

label = parsed['label']
label = tf.reshape(label, (1,))

return image_data, label

我如何将图像转换为灰度或 PIL 库有问题吗?

更新: 这是带有示例的 colab:https://colab.research.google.com/drive/1v72_C5i8HZzSLEy_p6d45EWq1byoF3fe

【问题讨论】:

标签: python tensorflow python-imaging-library google-colaboratory


【解决方案1】:

我确实陷入了同样的错误,但以下代码可以帮助您显示 gray_scale 图像。

在下面的代码中,您可以看到指标 [...,0] 被称为 Ellipsis_object

grey_img = tf.image.rgb_to_grayscale(jpeg_image)
_ = plt.imshow(grey_img[...,0], cmap='gray')

【讨论】:

  • 欢迎堆栈溢出!请直接在答案中添加图片,因为链接可能会失效。虽然这段代码可能会回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,纯代码的答案没有用。 Reference
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 2013-03-22
  • 2019-12-17
  • 2013-12-31
相关资源
最近更新 更多