Opencv2: Python: cv2.VideoWriter

14,116

Solution 1

I suspect you're using the libv4l version of OpenCV for video I/O. There's a bug in OpenCV's libv4l API that prevents VideoCapture::set method from changing the video resolution. See links 1, 2 and 3. If you do the following:

...
frame = cv2.flip(frame,180)
print(frame.shape[:2] # check to see frame size
out.write(frame)
...

You'll notice that the frame size has not been modified to match the resolution provided in the function arguments. One way to overcome this limitation is to manually resize the frame to match resolution arguments.

...
frame = cv2.flip(frame,180)
frame = cv2.resize(frame,(video_wdth,video_hight)) # manually resize frame
print(frame.shape[:2] # check to see frame size
out.write(frame)
...

Solution 2

output-frame & input-frame sizes must be same for writing...

Share:
14,116
user8495738
Author by

user8495738

List item

Updated on June 14, 2022

Comments

  • user8495738
    user8495738 almost 2 years

    Why does the following code not save the video? Also is it mandatory that the frame rate of the webcam matches exactly with the VideoWriter frame size?

    import numpy as np
    import cv2
    import time
    
    def videoaufzeichnung(video_wdth, video_hight, video_fps, seconds):
        cap = cv2.VideoCapture(6)
        cap.set(3, video_wdth) # wdth
        cap.set(4, video_hight) #hight 
        cap.set(5, video_fps) #hight 
        
        # Define the codec and create VideoWriter object
        fps = cap.get(5)
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        out = cv2.VideoWriter('output.avi', fourcc, video_fps, (video_wdth, video_hight))
        #out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
        
        start = time.time()
        zeitdauer = 0
        while(zeitdauer < seconds):
            end = time.time()
            zeitdauer = end - start
            ret, frame = cap.read()
            if ret == True:
                frame = cv2.flip(frame, 180)
                # write the flipped frame
                out.write(frame)
        
                cv2.imshow('frame', frame)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
            else:
                break
        
        # Release everything if job is finished
        cap.release()
        out.release()
        cv2.destroyAllWindows()
    
    videoaufzeichnung.videoaufzeichnung(1024, 720, 10, 30)
    
    • zindarod
      zindarod over 6 years
      Do you have Xvid codec installed on your system?
    • user8495738
      user8495738 over 6 years
      Yes but I have still the same problem