Python 如何将Keras与网络摄像头一起使用?

Python 如何将Keras与网络摄像头一起使用?,python,keras,deep-learning,Python,Keras,Deep Learning,我有一个经过训练的模特。用20000个“灰色”样本训练模型。İt正在处理“灰色”测试样本。但我想用网络摄像头测试这个模型。这是我的代码: #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.fromar

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

#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_输入具有形状(120320,1),但获取具有形状(128128,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_输入有4个维度,但得到了形状为(1,360,120)的数组

编辑2:此处为列车文章:

编辑3:我想,这是可行的。现在我将发送一个框架来预测,我将找到最合适的。如果可以的话,我会和大家分享。多谢各位

    _, 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)
这会将灰度图像转换为RGB。它只会将当前的一维值复制到三维。如果它抛出错误, 试试这个

    im = im.convert('L')
    im = im.convert('RGB')

'L'
首先将其转换为黑白,以防您的输入有时不仅仅是1D

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

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

在将输入形状馈送到网络之前,您需要将输入形状重塑为网络的输入形状。据我所知,我的输入形状是(1203201)。我可以调整大小为128128,但无法更改颜色比例。您的网络摄像头图像是
(128128,3)
。您需要将其转换为灰度,并将其调整大小/填充到正确的形状。我可以共享指向train文章的链接吗?它是禁止的吗?它不是禁止的,如果你认为它有助于理解你想做的事情,就把它添加到问题中。我已经试过“L”,但我仍然犯同样的错误。所有列车和试验样品的灰度。但我想用摄像机来测试这个模型。我添加了一个链接。也许会有帮助。
img_array = np.array(gray)
img_array = img_array.reshape(1, 1, 360, 120)