我有一个预先训练好的模型。用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: error when checking input:要求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:我想,它正在工作。现在我会发送帧来预测,我会找到手势最好的。如果我能做的话我会分享的。谢谢。
_, 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)发布于 2020-07-27 23:01:24
在编辑后回答您的问题:您需要4个维度,而不是3个维度:(批量大小,通道,宽度,高度)。因此,请尝试以下操作:
img_array = np.array(gray)
img_array = img_array.reshape(1, 1, 360, 120)发布于 2020-07-27 22:33:01
im = Image.fromarray(frame, 'RGB')
im = im.resize((128, 128))
im = im.convert('RGB')这会将您的灰度图像转换为RGB。它只会将你当前拥有的一个维度的值复制到三个维度。如果抛出错误,请尝试执行以下操作
im = im.convert('L')
im = im.convert('RGB')'L'首先将其转换为黑白,以防您的输入有时不只是一维的
https://stackoverflow.com/questions/63116917
复制相似问题