简体   繁体   中英

Saving video from frames in with fourcc codec h264 and h265 with opencv

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.

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()  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM