簡體   English   中英

使用使用時尚 mnist 數據集訓練的 model 預測來自谷歌圖像(包)的圖像的 class

[英]Predicting a class of a an image from google images(bag) using a model that is trained using fashion mnist dataset

我正在嘗試在 Python 中使用 TensorFlow 和 Keras 進行圖像識別。我只從 Z063009BB15C811627 開始學習。 我已經使用時尚 MNIST 數據集訓練了 model。 我現在正試圖通過使用來自谷歌圖像的外部圖像來預測這個 model。 我正在使用一個包的圖像。 請看下面

在此處輸入圖像描述

我知道我需要加載這個新圖像,強制它為灰度格式,並將大小強制為 28×28 像素,因為這是我在訓練 model 時訓練圖像的方式。 灰度和 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)

上述代碼的output如下

在此處輸入圖像描述

為什么背景是黃色的,圖像不是灰色的? 這個對嗎? 根據我的理解,背景應該是黑色的,圖像應該是灰色的。

當我嘗試使用以下代碼預測此圖像時,我得到 output 為零

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

提前致謝。

上述錯誤通過使用以下代碼起作用

從 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)

當你使用 pyplot.imshow() 繪圖時,如果你提到 cmap='gray' 那么你可以看到灰度圖像。 在上面的代碼中,黃色背景是 imshow function 的默認行為。

現在,如果您使用上述解決方案並且沒有得到正確的結果,那么請嘗試獲得與數據集相似的圖像。 Fashion MNIST 數據集具有圖像 - 28x28 像素,灰度,即黑色背景和前景為布料項目。 你讀到的圖像

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

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

img = ImageOps.invert(img)

現在嘗試使用 cmap='gray' 對 plot 進行預測並進行預測。 如果您的 model 以合理的准確度進行訓練,您將獲得正確的結果,幾乎適用於許多圖像。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM