2

I am saving frames from live stream to a video with h264 codec. I tried this with openCV (versions 3.4 and 4.4) in python but I am not able to save it. I can save video in XVID and many other codecs but I am not successful in h264 and h265.

I am using windows opencv 4.4 in Python.

My sample code is as follow

cap = cv2.VideoCapture(0)

while(cap.isOpened()):
    
        ret,frame = cap.read()
        if ret == True:

        width  = int(cap.get(3)) # float
        height = int(cap.get(4)) # float
        # fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
        
        fourcc = cv2.VideoWriter_fourcc(*'H264')
        out = cv2.VideoWriter(filename, fourcc, 30, (width,height)) 
        out.write(frame)
out.release()  

Can anyone help me how can I save video in h264 and h265.

Imran
  • 775
  • 7
  • 19

1 Answers1

1

You are recreating the VideoWriter at each frame which in the end only stores a single frame. You need to create the writer first, write the frames to it in the loop then terminate it after you're finished with the video. As a precaution you'll also want to break out of the loop if we detect any problems in the video when you read a frame. To make sure you do this right, let's read in the first frame, set up the VideoWriter then only write to it once we've established its creation:

cap = cv2.VideoCapture(0)
out = None

while cap.isOpened():
    ret, frame = cap.read()
    if ret == True:
        if out is None:
            width  = int(cap.get(3)) # float
            height = int(cap.get(4)) # float

            fourcc = cv2.VideoWriter_fourcc(*'H264')
            out = cv2.VideoWriter(filename, fourcc, 30, (width, height))
        else:
            out.write(frame)
    else:
        break

if out is not None:
    out.release()  
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • Ok this was a bug. But the main problem is writing with h264. Even creating it only once outside the loop the it can not write with codec h264 and h265 – Imran Oct 27 '20 at 05:22
  • Which operating system are you using? – rayryeng Oct 27 '20 at 06:11
  • I am using windows 10 with opencv 4.4 – Imran Oct 27 '20 at 06:15
  • 1
    You need to make sure you're using OpenH264, which is the only framework compatible with OpenCV and writing H264 files in Windows: https://answers.opencv.org/question/103267/h264-with-videowriter-windows/ – rayryeng Oct 27 '20 at 07:15
  • Dear, I used the procedure told by you. I downloaded and put openh264.dll file in the same directory where my script is and also the directory where I am saving file as I am changing the directory. but it is still not saving the video. It saves it with 0 bytes. Is there anything else to do? Am I missing something? – Imran Oct 27 '20 at 12:51