视频分类用OpenCV写视频出错

Error in Writing Video with OpenCV for Video Classification

我正在构建与此视频相同的视频分类模型:https://www.youtube.com/watch?v=l8XQsxlGxiY&list=PLxefhmF0pcPl_v-lLsqF3drP6NOoSYJR0&index=9

该模型预测视频中显示的是哪种运动:网球、游泳或拳击。

我已经建立了我的模型并且准确率达到了 96%。 现在,我有一个示例视频来测试我的模型。

from keras.models import load_model
from collections import deque
import numpy as np
import pickle
import 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 frames
cv2.destroyAllWindows()

当我 运行 上面的代码时,我可以看到它被正确分类了。 这是演示视频 (demo_video.mp4) 打开后,我可以看到视频顶部显示的是游泳、网球或拳击,具体取决于所显示的运动项目。

但是,因为我有一个:writer = cv2.VideoWriter('demo_output.mp4', fourcc, 10, (Width, Height), True)

当我打开 demo_output.mp4 甚至 avi 时,我得到: error

有人可以帮忙解决问题吗? 谢谢!

您混合了 WidthHeight...

而不是(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'

结果是黑色视频。

codec/container 作品的以下组合之一:

  • '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)