Pipe opencv images to ffmpeg using python

后端 未结 2 557
深忆病人
深忆病人 2021-02-04 14:22

How can I pipe openCV images to ffmpeg (running ffmpeg as a subprocess)? (I am using spyder/anaconda)

I am reading frames from a video file and do some processing on eac

2条回答
  •  时光说笑
    2021-02-04 14:46

    I'm Kind of late, But my powerful VidGear Python Library automates the process of pipelining OpenCV frames into FFmpeg on any platform with its WriteGear API's Compression Mode. OP, You can implement your answer as follows:

    # import libraries
    from vidgear.gears import WriteGear
    import cv2
    
    output_params = {"-s":"2048x2048", "-r":30} #define FFmpeg tweak parameters for writer
    
    stream = cv2.VideoCapture(0) #Open live webcam video stream on first index(i.e. 0) device
    
    writer = WriteGear(output_filename = 'Output.mp4', compression_mode = True, logging = True, **output_params) #Define writer with output filename 'Output.mp4' 
    
    # infinite loop
    while True:
        
        (grabbed, frame) = stream.read()
        # read frames
    
        # check if frame empty
        if not is grabbed:
            #if True break the infinite loop
            break
        
    
        # {do something with frame here}
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
        # write a modified frame to writer
        writer.write(gray) 
           
        # Show output window
        cv2.imshow("Output Frame", frame)
    
        key = cv2.waitKey(1) & 0xFF
        # check for 'q' key-press
        if key == ord("q"):
            #if 'q' key-pressed break out
            break
    
    cv2.destroyAllWindows()
    # close output window
    
    stream.release()
    # safely close video stream
    writer.close()
    # safely close writer
    

    Source: https://abhitronix.github.io/vidgear/gears/writegear/compression/usage/#using-compression-mode-with-opencv

    You can check out VidGear Docs for more advanced applications and features.

    Hope that helps!

提交回复
热议问题