import cv2
import numpy as np
import tensorflow as tf
model = tf.keras.models.load_model("oneptwoside.model")
CATEGORIES = ["front", "back"]
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret, frame = cap.read()
else:
ret = False
while ret:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
IMG_SIZE = 200
img_array = cv2.imread(frame, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
prediction = model.predict([img_array])
print(prediction)
print(CATEGORIES[int(prediction[0][0])])
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
我无法通过网络摄像头做出预测。我在图像中尝试了相同的代码,但稍作调整后即可正常工作。但是,在视频中始终无法读取框架或某些调整大小的问题
答案 0 :(得分:0)
if cap.isOpened():
ret, frame = cap.read()
else:
ret = False
while ret:
curr_time = time.time()
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
curTime = time.time()
sec = curTime - prevTime
prevTime = curTime
fps = 1/(sec)
str = "FPS : %0.1f" % fps
cv2.putText(frame, str, (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 150, 0))
cv2.imshow('frame',gray)
cv2.imshow('color', frame)
if curr_time - last_recorded_time >= 0.0001:
last_recorded_time = curr_time
IMG_SIZE = 200
#img_array = cv2.imread('frame', cv2.IMREAD_GRAYSCALE)
frame = cv2.resize(frame, None, fx=0.5, fy=0.5)
frame = cv2.resize(frame, (IMG_SIZE, IMG_SIZE))
#frame = frame[np.newaxis, ...]
frame = frame.reshape((-1, 200, 200, 1))
cv2.rectangle(frame,(200,0),(150,128),(0,255,0),3)
prediction = model.predict([frame])
#prediction = model.predict([frame])
print(prediction)
print(CATEGORIES[int(prediction[0][0])])
if cv2.waitKey(1) & 0xFF == ord('q'):
break
这是一个不理想的解决方案,但是可以正常工作