微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 OpenCV 编写视频进行视频分类时出错

如何解决使用 OpenCV 编写视频进行视频分类时出错

我正在构建与此视频中相同的视频分类模型: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),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',True)

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

有人可以帮忙吗? 谢谢!

解决方法

你混合了 WidthHeight...

应该是:

而不是 (Width,Height) = frame.shape[:2]
(Height,Width) = frame.shape[:2]

在我的系统中,我收到以下警告:

OpenCV: FFMPEG: tag 0x47504a4d/'MJPG' 不支持编解码器 ID 7 和格式 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV:FFMPEG:回退使用标签 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',True)
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。