【发布时间】: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 documentation,
grayscale已被弃用。尝试改用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