【问题标题】:Predicting a class of a an image from google images(bag) using a model that is trained using fashion mnist dataset使用使用时尚 mnist 数据集训练的模型从谷歌图像(包)中预测图像的类别
【发布时间】:2021-08-07 17:57:26
【问题描述】:

我正在尝试使用 TensorFlow 和 Keras 在 Python 中进行图像识别。我只是从 keras 和机器学习开始。我已经使用时尚 MNIST 数据集训练了模型。我现在正试图通过使用来自谷歌图像的外部图像来预测这个模型。我正在使用一个包的图像。请看下面

我知道我需要加载这个新图像,将其强制为灰度格式,并将大小强制为 28×28 像素,因为这是我在训练模型时训练图像的样子。灰度和28 * 28。

因此,我关注了一些博客,并使用了以下代码。

from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator

img_path = 'data/bag2.jpg'

img = image.load_img(img_path,grayscale=True,target_size=(28, 28))
img_tensor = image.img_to_array(img)
img_tensor = numpy.expand_dims(img_tensor, axis=0)
img_tensor /= 255.
pyplot.imshow(img_tensor[0])
pyplot.show()
print(img_tensor.shape)

以上代码的输出如下

为什么背景是黄色的,图片不是灰色的?它是否正确?根据我的理解,背景应该是黑色的,图像应该是灰色的。

当我尝试使用以下代码预测此图像时,我得到的输出为零

pred = model.predict(img_tensor.reshape(-1,28, 28, 1))
print(pred.argmax())

提前致谢。

【问题讨论】:

  • 如果你从不使用gray_img 有什么意义?还有一些你的代码是多余的,请编辑你的问题
  • @RandomGuy,我最初尝试加载 gray_img 而不是直接加载 img。但是,它给了我一个 TypeError 错误:预期的 str、字节或 os.PathLike 对象,而不是 numpy.ndarray。我无法修复它,因此尝试了 img = image.load_img(img_path, grayscale=True,target_size=(28, 28)) 。没有注释掉删除了不起作用的代码。我现在已经在问题中编辑了我的代码。请让我知道如何获得灰色图像,因为这是我在预测时需要使用的。
  • 根据tensorflow documentationgrayscale 已被弃用。尝试改用img = image.load_img(img_path,color_mode='grayscale',target_size=(28, 28))。此外,pred = model.predict(img_tensor) 应该可以工作,无需重塑您的数组。
  • @RandomGuy,感谢您的快速回复。我查看了文档并尝试使用 img = image.load_img(img_path,color_mode='grayscale',target_size=(28, 28))。它给了我与我在问题中提供的相同的黄色背景图像。不知道出了什么问题。
  • 嗯,这可能是来自load_image 的错误...请您尝试img_tensor = cv2.imread(img_path , cv2.IMREAD_GRAYSCALE) 好吗?然后,img_tensor = numpy.expand_dims(img_tensor, axis=0) 等等

标签: python tensorflow image-processing keras tf.keras


【解决方案1】:

当你使用 pyplot.imshow() 绘图时,如果你提到 cmap='gray' 那么你可以看到灰度图像。在上面的代码中,黄色背景是 imshow 函数的默认行为。

现在,如果您使用上述解决方案并且没有得到正确的结果,那么请尝试获得与数据集相似的图像。时尚 MNIST 数据集有图像 - 28x28 像素,灰度,即黑色背景和前景为布料项目。你读到的图片

img = image.load_img(img_path,grayscale=True,target_size=(28, 28)) 

是灰度的,但有白色背景。所以你可以使用 -

img = ImageOps.invert(img)

现在尝试使用 cmap='gray' 绘制此图并进行预测。如果您的模型以合理的准确度进行训练,您将获得正确的结果,几乎适用于许多图像。

【讨论】:

    【解决方案2】:

    使用下面的代码可以解决上述错误

    从 keras.preprocessing 导入图像 从 keras.preprocessing.image 导入 ImageDataGenerator

    img_path = 'data/bag5.jpg'
    img = image.load_img(img_path,color_mode='grayscale',target_size=(28, 28))
    img_tensor = image.img_to_array(img)
    img_tensor = numpy.expand_dims(img_tensor, axis=0)
    img_tensor /= 255.
    
    pyplot.imshow(img_tensor[0], cmap='gray')
    pyplot.show()
    print(img_tensor.shape)
    

    【讨论】:

      猜你喜欢
      • 2016-06-14
      • 2022-10-24
      • 2018-05-28
      • 2023-03-10
      • 1970-01-01
      • 2018-09-25
      • 2020-09-22
      • 2016-06-03
      • 1970-01-01
      相关资源
      最近更新 更多