问题描述
我有一些用例,我在主循环上进行视频捕获,并在另一个线程上对捕获的帧进行视频记录。当我尝试在那之后运行视频时,出现错误: 这是我的代码。
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()
我在做什么错? 在此先感谢您的帮助。
解决方法
我想我解决了您的问题。 您只需要更改两行代码即可。
代替:
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',(int(cap.get(3)),int(cap.get(4))))
,
我正在尝试同一件事,记录我的相机流。我也实现了这种线程化方法,但是输出文件太生涩了(跳过了很多帧)。您是否也发生了同样的事情?有什么建议?谢谢!