我正在构建一个与此视频中相同的视频分类模型:https://www.youtube.com/watch?v=l8XQsxlGxiY&list=PLxefhmF0pcPl_v-lLsqF3drP6NOoSYJR0&index=9
该模型预测视频中展示的是哪项运动:网球、游泳或拳击。
我已经构建了我的模型,准确率达到了96%。现在,我有一个样本视频来测试我的模型。
from keras.models import load_modelfrom collections import dequeimport numpy as npimport pickleimport cv2
model = load_model(r"C:\Users\yudishteer.c\Desktop\VideoClassification\video_classification_model\videoclassificationModel")lb = pickle.loads(open(r"C:\Users\yudishteer.c\Desktop\VideoClassification\video_classification_model\videoclassificationBinarizer.pickle", "rb").read())outputvideo = r"C:\Users\yudishteer.c\Desktop\VideoClassification\video_classification_model\outputvideo\demo_output.avi"mean = np.array([123.68, 116.779, 103.939], dtype = "float32")Queue = deque(maxlen=128)
capture_video=cv2.VideoCapture(r"C:\Users\yudishteer.c\Desktop\VideoClassification\video_classification_model\demo_video.mp4")writer = None(Width, Height) = (None, None)while True: (taken, frame) = capture_video.read() if not taken: break if Width is None or Height is None: (Width, Height) = frame.shape[:2] output = frame.copy() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = cv2.resize(frame, (224,224)).astype("float32") frame -= mean preds = model.predict(np.expand_dims(frame, axis=0))[0] Queue.append(preds) results = np.array(Queue).mean(axis = 0) i = np.argmax(results) label = lb.classes_[i] text = "The game is {}".format(label) cv2.putText(output, text, (45,60), cv2.FONT_HERSHEY_SIMPLEX, 1.25, (255,0,0),5) if writer is None: fourcc = cv2.VideoWriter_fourcc(*'MJPG') writer = cv2.VideoWriter('demo_output.mp4', fourcc, 10, (Width, Height), True) writer.write(output) cv2.imshow("In progress", output) key = cv2.waitKey(1) & 0xFF if key == ord("q"): break print("Finalizing.......")writer.release()capture_video.release()# Closes all the framescv2.destroyAllWindows()
当我运行上述代码时,我可以看到它被正确分类。也就是说,演示视频(demo_video.mp4)被打开,我可以看到根据展示的运动,视频顶部显示的是游泳、网球或拳击。
然而,由于我有以下代码:writer = cv2.VideoWriter('demo_output.mp4', fourcc, 10, (Width, Height), True)
当我打开demo_output.mp4
(甚至是avi
)时,我得到了以下错误:
有人能帮我找出问题所在吗?谢谢!
回答:
你混淆了Width
和Height
…
不是(Width, Height) = frame.shape[:2]
,应该是:
(Height, Width) = frame.shape[:2]
在我的系统中,我收到了以下警告:
OpenCV: FFMPEG: tag 0x47504a4d/’MJPG’ is not supported with codec id 7 and format ‘mp4 / MP4 (MPEG-4 Part 14)’OpenCV: FFMPEG: fallback to use tag 0x7634706d/’mp4v’
结果是一个黑屏视频。
以下编码器/容器组合之一可以工作:
-
'MJPG'
FOURCC 和 AVI 容器:fourcc = cv2.VideoWriter_fourcc(*'MJPG') writer = cv2.VideoWriter('demo_output.avi', fourcc, 10, (Width, Height), True)
-
'mp4v'
FOURCC 和 MP4 容器:fourcc = cv2.VideoWriter_fourcc(*'mp4v') writer = cv2.VideoWriter('demo_output.mp4', fourcc, 10, (Width, Height), True)