VideoWriter outputs only a 5.7kB File in OpenCV Python
Question: I was trying the following piece of code for storing the captured video into a
file. The Live Stream is getting displayed correctly , but for whatever length
I record the video, the target file is a 5.7kB file that doesn't contain any
video.

    
    
    import numpy as np
    import cv2
    
    cap = cv2.VideoCapture(0)
    
    fourcc= cv2.cv.FOURCC(*'DIVX')
    ret=cap.set(3,500)  
    ret=cap.set(4,500) 
    
    out= cv2.VideoWriter('out.avi',fourcc,20,(500,500))
    
    while(cap.isOpened()):  
        ret, frame = cap.read()
        if ret == True:     
            out.write(frame)
    
            cv2.imshow('out.avi',frame)
    
            if cv2.waitKey(1) &0xFF ==ord('q'):
                break
        else:
            break
    
    
    cap.release()
    out.release()
    cv2.destroyAllWindows()
    

Does anyone have any idea what I might be doing wrong here?

Please help to figure it out .


Answer: It might be because the encoding of fourcc is not supported/installed on your
machine, thus makes it impossible to export the frames to the video. It
happens to me all the time. What works for me is the mp4 codec (in opencv:
cv2.cv.CV_FOURCC('m', 'p', '4', 'v')). So, try this:

    
    
    import numpy as np
    import cv2
    
    cap = cv2.VideoCapture(0)
    
    fourcc= cv2.cv.CV_FOURCC('m', 'p', '4', 'v')
    ret=cap.set(3,500)  
    ret=cap.set(4,500) 
    
    out= cv2.VideoWriter('out.avi',fourcc,20,(500,500))
    
    while(cap.isOpened()):  
        ret, frame = cap.read()
        if ret == True:     
            out.write(frame)
    
            cv2.imshow('out.avi',frame)
    
            if cv2.waitKey(1) &0xFF ==ord('q'):
                break
        else:
            break
    
    
    cap.release()
    out.release()
    cv2.destroyAllWindows()
    

Otherwise, you can try to install all the codec compatible with ffmpeg (It
seems that opencv uses ffmpeg to export the frames to video file) and retry
your original code.

