0

Using OpenCV, I have been extracting the frames from a video and after working on the frames, I have been trying to save them to a new video file. But the new video file is not being saved properly. It gets saved as 0 KB in size and throws the following error when I try to open it. OpenCV Error

My code is as follows:

import cv2

cap = cv2.VideoCapture("Path to source video")

out = cv2.VideoWriter("Path to save video", cv2.VideoWriter_fourcc(*"VIDX"), 5, (1000, 1200))

print(cap.isOpened())
while True:

     # Capture frame-by-frame
     ret, frame = cap.read()

     # Write the video
     out.write(frame)

     # Display the resulting frame
     cv2.imshow('frame',frame)

     if cv2.waitKey(1) & 0xFF == ord('q'):
         break
cap.release()
out.release()
cv2.destroyAllWindows()

I tried to follow the solution Can't save a video in opencv but it did not help in my case.

  • `VIDX` is not a valid codec. `assert out.isOpened()` would have been False, right? and what's the size (width, height) of your source video? – Christoph Rackwitz Jun 07 '22 at 13:09
  • I used the answer given below ( took source video's height (1000) and width (1920)), but still didn't work. I also tried changing the codec to "XVID". – Maksudur Rahman Jun 09 '22 at 04:44

1 Answers1

0

when saving the file, your width and height should match with frame's width and height, so in order to get the width and height of the frame automatically, use

import cv2

cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # to get width of the frame
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # to get height of the frame

out = cv2.VideoWriter("dummy_video.mp4", cv2.VideoWriter_fourcc(*"VIDX"), 5, (width, height))

print(cap.isOpened())
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Write the video
    out.write(frame)

    # Display the resulting frame
    cv2.imshow('frame',frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
out.release()
cv2.destroyAllWindows()
Prashanth
  • 1
  • 1