首页 > 解决方案 > 当我通过网络摄像头运行模型时,为什么我的模型只预测一个类?

问题描述

我使用 MNIST 数据集制作了一个模型,当我使用自己的图像对其进行测试时,它可以正确地预测类。

完成模型制作后,我将其保存为 .h5 文件,并编写了一个程序来使用我的网络摄像头预测模型的输出。

import numpy as np
import cv2
from PIL import Image
import tensorflow as tf
import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
cam = cv2.VideoCapture(0)
model = tf.keras.models.load_model("model.h5")
class_names = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def predict_number(prediction_image):
    global model, class_names
    predictions = model.predict(prediction_image)
    #print(predictions)
    prediction_final = np.argmax(predictions)
    #print(prediction_final)
    #print(f"Prediction: {class_names[prediction_final]}")
    return class_names[prediction_final]

while True:
    ret, win = cam.read()
    window_resized = win[0:450, 0:350]
    cv2.rectangle(win, (100, 100), (250, 250), (255, 0, 0), 0)
    img = win[100:250, 100:250]
    im_resized = cv2.resize(img, (28, 28), Image.ANTIALIAS)
    im_resized_array = np.asarray(im_resized)
    im_resized_array = im_resized_array[:,:,0]
    im_resized_array = im_resized_array / 255
    final_image = np.reshape(im_resized_array, (1, 28, 28, 1))
    prediction = predict_number(final_image)
    image = cv2.putText(window_resized, str(prediction), (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA) 
    cv2.imshow("Camera", window_resized)
    if cv2.waitKey(1) == ord(' '):
        break
cam.release()
cv2.destroyAllWindows()

每当我运行此代码时,无论出于某种原因,无论我显示什么,模型都会一直预测“8”,但我确信我的模型可以正常运行,就像我使用自己在 . ipynb 形式它正确地预测它。

我觉得我保存/加载模型的方式有错误,或者我处理图像的方式有错误。

我正在保存我的模型:

model.save("model.h5")

标签: pythontensorflow

解决方案


我这个问题可能与数据集和我处理图像的方式有关。我最终使用了来自tfds而不是的数据集keras.datasets

dataset = 'mnist'
(img_train, label_train), (img_test, label_test) = tfds.as_numpy(tfds.load(dataset, split = ['train', 'test'], shuffle_files=True, batch_size=-1, as_supervised=True))

builder = tfds.builder(dataset)
info = builder.info

print(info.features["label"].names)
labels = info.features["label"].names

img_train = img_train / 255.0
img_test = img_test / 255.0

然后我改变了在运行图像之前处理图像的方式model.predict()

image = cv2.imread(#image)
image = np.resize(image, (28,28,1))
image = np.array(image).astype('float32')
image = image.reshape(1,28,28,1)
image = image / 255
print(np.shape(image))
tf.convert_to_tensor(image)
pred = model.predict(image)
print(pred)
pred_index = np.argmax(pred)
print("Prediction: ", labels[pred_index])

这解决了这个问题,现在模型至少试图预测我给它的任何图像cv2

我认为我处理图像的方式是image一个空的 numpy 数组,因此无论我使用什么图像,它每次都预测为 8,因为它没有任何其他选项。


推荐阅读