[英]How possibly can I use the frames generated from my webcam to be the input of my Keras model?
[英]How can I use Keras with webcam?
我有一個預訓練的 model。 Model 使用 20000 個“灰色”樣本進行訓練。 它正在處理“灰色”測試樣本。 但我想用網絡攝像頭測試這個 model。 這是我的代碼:
#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)。
Model 訓練:
# 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)
im = Image.fromarray(frame, 'RGB')
im = im.resize((128, 128))
im = im.convert('RGB')
這會將您的灰度圖像轉換為 RGB。 它只會將您當前擁有的一維的值復制到 3 維。 如果它拋出一個錯誤,試試這個
im = im.convert('L')
im = im.convert('RGB')
'L'
首先將其轉換為黑白,以防您的輸入有時不僅僅是 1D
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.