python - 如何将 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) 的数组
编辑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)
解决方案
编辑后回答您的问题: 您需要 4 个维度而不是三个维度:(批量大小、通道、宽度、高度)。所以尝试以下方法:
img_array = np.array(gray)
img_array = img_array.reshape(1, 1, 360, 120)
推荐阅读
- android - 如何从包含异步功能的 firestore 数据库中正确获取结果?- Android - Kotlin - MVVM
- java - 盈透证券 Java API
- windows - 重新加载后如何查看 html 编辑(Firefox DevTools)?
- kubernetes - Kubernetes pod 无法 ping url 或 wget HTTPS 站点
- python - 从数据框中删除子字符串
- reactjs - React - 我输入时表单不断重新渲染组件
- encryption - OpenSSL中aes GCM模式加解密时如何打印key、iv、aad
- javascript - 如何使 d3 树形图节点可单击以选择整个节点?
- flutter - globals.platform.environment['LOCALAPPDATA'] / FVM / Flutter
- jhipster - 我们可以将 jhipster 应用程序部署到本地或自托管服务器吗?