cv2.videowriter writes 0 bytes file (python) (opencv)

Apl*_*lin 3 python opencv video-recording

I am currently doing a motion detection project that records down video when motion is detected. Right now there is no error when recording the video but when i check on the video, it is 0 bytes. Any help would be very much appreciated.

This is my code:

camera = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640, 480))
Run Code Online (Sandbox Code Playgroud)

小智 5

当您的输入帧大小与输出视频不匹配时,就会出现问题。

out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640, 480))
Run Code Online (Sandbox Code Playgroud)

在这里,您不允许输出的视频为640,480,并且取决于您的输入源(如果不调整其大小)

您可以对其进行硬编码(检查输入视频或流源的帧大小),也可以使用以下代码:

w = cap.get(cv2.CAP_PROP_FRAME_WIDTH);
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT); 
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter('output.mp4',fourcc, 15.0, (int(w),int(h)))
Run Code Online (Sandbox Code Playgroud)

我的建议是在while循环外抓取一个框架,并在其中声明VideoWritter的框架宽度和高度。另外,尝试将编解码器从XVID更改为DIVX或MJPG(如果不起作用)。