【问题标题】:How to convert a 2D numpy array to an tensorflow array for image prediction如何将二维 numpy 数组转换为张量流数组以进行图像预测
【发布时间】:2023-02-10 15:56:28
【问题描述】:

有没有一种简单的方法可以将 2D numpy 数组转换为用于图像预测的 tf 数组?目前我有一个灰度图像,我必须使用另一个 API 将其导入到 python 中,该 API 为我提供了一个 2D numpy 像素值数组。然后我必须将这个数组保存为图像并在 tensorflow 中重新导入图像,所以我基本上得到以下结果:

npArray = np.random.rand(100,100)

plt.imsave('image.png', npArray, cmap='Greys')

imgTf = tf.keras.utils.load_img(
        'image.png', target_size=(100, 100)
    )

imgTfArray = tf.keras.utils.img_to_array(imgTf)
imgTfArrayBatch = tf.expand_dims(imgTfArray, 0)  # Create a batch

然后继续将图像提供给经过训练的模型并返回预测。

理想情况下,我只想能够输入 npArray 而不是必须保存文件并打开文件,但是 numpy 数组是 2D 而打开的图像是 3D 数组。有没有办法轻松转换?

【问题讨论】:

  • tf.keras.Model.predict 接受 numpy 数组作为输入,如您所见:tensorflow.org/api_docs/python/tf/keras/Model#predict
  • @delirium78 出于部署原因,我对这些位使用 tf-lite,这些位似乎没有使用 model.predict 而是使用 interpreter.get_signature_runner('serving_default') 并通过它传递图像。
  • npArray = np.random.rand(100, 100, 1) 突然间你有了三个通道……或者通过npArray[:, :, np.newaxis] 添加一个轴?

标签: arrays numpy tensorflow tensorflow2.0


【解决方案1】:

原来问题是 tensorflow 需要 RGB 图像,所以你必须在使用灰度时伪造它。解决方案是将数组堆叠 3 次以表示 3 个 RGB 通道。

npArray = np.stack([npArray, npArray, npArray], axis=2)

完成此操作后,您可以通过

imgArray = tf.expand_dims(npArray.astype(dtype='float32'), 0)  # Create a batch

然后将其输入 tf lite 分类,它应该一切正常。

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 2020-05-31
    相关资源
    最近更新 更多