在另一个线程上编写视频(Python OpenCV)

2024-09-29 01:32:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些用例,我在主循环上做视频捕获,在另一个线程上做捕获帧的视频记录。之后尝试运行视频时,出现错误: 这是我的密码

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

from threading import Thread
import threading
import time

recordVideo = True
detected = True

def VideoWriting():
    global frame
    global writeVideo
    firstTime = True
    writeVideo = False
    out = cv2.VideoWriter()
    fourcc = cv2.VideoWriter_fourcc(*'XVID')

    while recordVideo:
        if(True == firstTime and True == detected and True == writeVideo):
            print("init")
            out = cv2.VideoWriter('output.avi',fourcc , 20.0, (frame.shape[0],frame.shape[1]) )
            firstTime = False
        if(True == writeVideo):
            out.write(frame)
            print("VideoWriting :: Frame")
            writeVideo = False
        if(False == detected):
            firstTime = True
            out.release()
    
    if(out.isOpened() ):
        print("Released")
        out.release()

th = []

th.append(Thread(target=VideoWriting) )
th[-1].daemon = True
th[-1].start()

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        writeVideo = True
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
cv2.destroyAllWindows()

recordVideo = False

for thd in th:
    thd.join()

我做错了什么? 提前谢谢你的帮助


Tags: importfalsetrue视频ifoutcv2frame
1条回答
网友
1楼 · 发布于 2024-09-29 01:32:24

我想我解决了你的问题。 您只需更改代码的两行

而不是:

fourcc = cv2.VideoWriter_fourcc(*'XVID')

使用:

fourcc = cv2.VideoWriter_fourcc('M','J','P','G')

而不是:

out = cv2.VideoWriter('output.avi',fourcc , 20.0, (frame.shape[0],frame.shape[1]) )

使用:

out = cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)), int(cap.get(4))))

相关问题 更多 >