首页 > 解决方案 > 如何将 Keras 与网络摄像头一起使用?

问题描述

我有一个预训练模型。使用 20000 个“灰色”样本训练的模型。它正在处理“灰色”测试样本。但我想用网络摄像头测试这个模型。这是我的代码:

#Load the saved model
model = keras.models.load_model('C:\keras\handrecognition_model.h5')
video = cv2.VideoCapture(0)

while True:
    _, frame = video.read()
    im = Image.fromarray(frame, 'RGB')
    im = im.resize((128, 128))
    img_array = np.array(im)

    img_array = np.expand_dims(img_array, axis=0)

    prediction = int(model.predict(img_array)[0][0])

    # if prediction is 0, which means I am missing on the image, then show the frame in gray color.
    if prediction == 0:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    cv2.imshow("Capturing", frame)
    key = cv2.waitKey(1)
    if key == ord('q'):
            break

video.release()
cv2.destroyAllWindows()

有一个错误:ValueError:检查输入时出错:预期 conv2d_1_input 的形状为 (120, 320, 1),但得到的数组的形状为 (128, 128, 3)。

这里输出灰度测试图像: 在此处输入图像描述

模型训练:

# Construction of model
model = Sequential()
model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(120, 320, 1))) 
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu')) 
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(10, activation='softmax'))

编辑:我更新这样的代码:

_, frame = video.read()
frame = cv2.resize(frame, (120, 360))
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
img_array = np.array(gray)

ValueError:检查输入时出错:预期 conv2d_1_input 有 4 个维度,但得到了形状为 (1, 360, 120) 的数组

编辑2:这里训练文章: https ://towardsdatascience.com/tutorial-using-deep-learning-and-cnns-to-make-a-hand-gesture-recognition-model-371770b63a51

编辑3:我想,它正在工作。现在我将发送帧进行预测,我将找到手部 gest。如果我能做到,我会分享。谢谢你。

    _, frame = video.read()
    frameCopy=frame.copy()
    frameCopy = cv2.resize(frameCopy, (120, 320))
    gray = cv2.cvtColor(frameCopy, cv2.COLOR_BGR2GRAY)
    img_array = np.array(gray)
    img_array = img_array.reshape(120, 320, 1)
    img_array = np.expand_dims(img_array, axis=0)

标签: pythonkerasdeep-learning

解决方案


编辑后回答您的问题: 您需要 4 个维度而不是三个维度:(批量大小、通道、宽度、高度)。所以尝试以下方法:

img_array = np.array(gray)
img_array = img_array.reshape(1, 1, 360, 120)

推荐阅读