Writing an mp4 video using python opencv

前端 未结 10 835
Happy的楠姐
Happy的楠姐 2021-01-31 07:44

I want to capture video from a webcam and save it to an mp4 file using opencv. I found example code on stackoverflow (below) that works great. The only hitch is that I\'m trying

10条回答
  •  没有蜡笔的小新
    2021-01-31 08:41

    Anyone who's looking for most convenient and robust way of writing MP4 files with OpenCV or FFmpeg, can see my state-of-the-art VidGear Video-Processing Python library's WriteGear API that works with both OpenCV backend and FFmpeg backend and even supports GPU encoders. Here's an example to encode with H264 encoder in WriteGear with FFmpeg backend:

    # import required libraries
    from vidgear.gears import WriteGear
    import cv2
    
    # define suitable (Codec,CRF,preset) FFmpeg parameters for writer
    output_params = {"-vcodec":"libx264", "-crf": 0, "-preset": "fast"}
    
    # Open suitable video stream, such as webcam on first index(i.e. 0)
    stream = cv2.VideoCapture(0) 
    
    # Define writer with defined parameters and suitable output filename for e.g. `Output.mp4`
    writer = WriteGear(output_filename = 'Output.mp4', logging = True, **output_params)
    
    # loop over
    while True:
    
        # read frames from stream
        (grabbed, frame) = stream.read()
    
        # check for frame if not grabbed
        if not grabbed:
          break
    
        # {do something with the frame here}
        # lets convert frame to gray for this example
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
        # write gray frame to writer
        writer.write(gray)
    
        # Show output window
        cv2.imshow("Output Gray Frame", gray)
    
        # check for 'q' key if pressed
        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
            break
    
    # close output window
    cv2.destroyAllWindows()
    
    # safely close video stream
    stream.release()
    
    # safely close writer
    writer.close() 
    
    • Source: https://github.com/abhiTronix/vidgear
    • Docs: https://abhitronix.github.io/vidgear/
    • More FFmpeg backend examples:https://abhitronix.github.io/vidgear/gears/writegear/compression/usage/
    • OpenCV backend examples: https://abhitronix.github.io/vidgear/gears/writegear/non_compression/usage/

提交回复
热议问题