【问题标题】:How do I use my own image for a prediction in CNN?如何在 CNN 中使用自己的图像进行预测?
【发布时间】:2020-05-22 06:49:36
【问题描述】:

我正在尝试在我的 CNN 中使用我自己的 28x28 像素图像,但是当我尝试对其进行重塑时,我不断收到此错误:

x = x.reshape(1,28,28,1)

ValueError: cannot reshape array of size 2352 into shape (1,28,28,1)

我的图像是 28x28,但我无法将其更改为单个灰度通道。我一直在通过 anaconda 使用 spyder,每当我尝试将 opencv 安装到我的根环境中时,我都会收到“UnsatisfiableError”。 Pip安装也不起作用。 我想知道是否有人在不使用外部库而只使用 tensorflow 的情况下重塑我的图像。

我已经搜索了答案并尝试了建议的解决方案,但不幸的是它们都没有奏效。

提前致谢。


回复 AKX:

def Predict(imgPath):
    x = plt.imread(imgPath)
    x = x.reshape(1,28,28,1)


    with graph.as_default():
        out = model.predict(x)
        return out

回复 Skander HR:

(28,28,3)

回复 Matias Valdenegro:

我的问题是 openCV 不工作。它已安装,但我尝试检查是否有任何代理服务器,安装 python3.dll 并尝试安装 microsoft mediafeaturepack 以消除错误,但这些都不起作用。 当我编写这样的程序时:

import cv2 as cv
print("done")

我收到错误消息:

    import cv2 as cv
ImportError: DLL load failed: The specified module could not be found.

【问题讨论】:

  • 这里的x 是什么?请向我们展示更多代码(例如,如何加载图像)。
  • 您好,您能告诉我们您的图片是什么形状的吗? x.shape
  • RGB不能reshape为灰度图,需要进行颜色转换,可以使用OpenCV,具体问题请补充。
  • 我已经通过编辑原帖回答了 3 个问题。感谢您的提问。
  • 我建议尝试通过 anaconda 提示符使用 'pip' 卸载并重新安装 opencv。

标签: python tensorflow keras spyder


【解决方案1】:

只需使用Pillow 调整图像大小:

from PIL import Image
import numpy as np 
...
img = Image.fromarray(x)
img = img.resize((28,28))
x = np.asarray(img)
x = x.reshape(1,28,28,1)
...

使用 pip 安装 pip install pillow 要么 python3 -m pip install pillow 这样您就可以确定您使用的是正确的 python 版本。

【讨论】:

  • 嗨 Frederik,当我将它添加到我的代码中时,我收到此错误:raise TypeError("Cannot handle this data type") TypeError: Cannot handle this data type
【解决方案2】:

您主要使用大小为 28*28 的 RGB 图像,因此您的大小为 28*28*3=2352。您需要将其转换为灰度图像以匹配您的张量形状。

您可以使用以下命令使用 opencv 进行转换:-

gray_image = cv2.imread(path_to_image, cv2.IMREAD_GRAYSCALE) 

【讨论】:

【解决方案3】:

在对自己的图像进行预测和使用灰度图像时,需要考虑两个概念。

  1. 默认情况下,OpenCV 或 PIL 中的灰度模式会考虑没有最后一个轴(颜色轴)的灰度图像。这意味着,您必须使用np.expand_dims(image,axis=2)image = image[..., np.newaxis]。完成此步骤后,您的图片大小为(width,height,1)
  2. 您再次使用np.expand_dims(image, axis=0) 来添加batch_index 大小。这是必要的,因为默认情况下,在 Keras/TensorFlow 中,您只能对批次进行预测。在您的情况下,照片实际上意味着 batch_size 为 1。

如果您牢记这两点,您将成功且轻松地使用model.predict() 来获得您的预测。

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 2021-09-15
    • 2021-04-08
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多