Home > Mobile >  Opencv saving empty video Python
Opencv saving empty video Python

Time:01-19

I am facing a problem in recording a video from camera. I am using python and opencv to do so. I have my images in QImage format, I convert them to numpy array in order to display to stream it when video capturing of the cam (using VideoCapture of opencv), everything works fine. When I try to record a video and save it in the folder (using VideoWriter_fourcc of opencv), I get no errors but I get an empty video. I did a lot of searching to find the problem but I couldn't. Here's the code that I use to record a video:

import cv2

fourcc = cv2.VideoWriter_fourcc('M','J','P','G')  
#img is a numpy array  
videoWriter = cv2.VideoWriter('video.avi', fourcc, 20,  (img.shape[0],img.shape[1]))
while True:
    videoWriter.write(img)
videoWriter.release()

I tried to change the Framerate, the frameSize, the extension of the video and the code of codec but nothing worked. I am so desperate. I appreciate all and every help and suggestion I can get. Thank you

CodePudding user response:

The issue is that you mixed up width and height as you passed them to VideoWriter.

VideoWriter wants (width, height) for the frameSize argument.

Note that width = img.shape[1] and height = img.shape[0]

Giving VideoWriter a, say, 1920x1080 frame to write, while having promised 1080x1920 frames in the constructor, will fail, but silently.

CodePudding user response:

Possible cause:

In your code, you are only writing a single frame to the video, which is why the video is empty. You need to continuously write frames to the video until you are done recording. You can do this by moving the videoWriter.write(img) and videoWriter.release() lines inside a loop that captures frames from the camera, and only release the video writer when you are done recording.

Solution:

import cv2

fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
cap = cv2.VideoCapture(0)
videoWriter = cv2.VideoWriter('video.avi', fourcc, 20, (int(cap.get(3)), int(cap.get(4))))

while True:
    ret, frame = cap.read()
    if ret:
        videoWriter.write(frame)
    else:
        break

cap.release()
videoWriter.release()

CodePudding user response:

There are so many ways to workaround.

fshape = img.shape
fheight = fshape[0]
fwidth = fshape[1]

videoWriter = cv2.VideoWriter('video.avi', fourcc, 20.0, (fwidth, fheight))
  • Related