How to create video thumbnails with Python and Gstreamer

前端 未结 4 691
没有蜡笔的小新
没有蜡笔的小新 2020-12-19 03:15

I\'d like to create thumbnails for MPEG-4 AVC videos using Gstreamer and Python. Essentially:

  1. Open the video file
  2. Seek to a certain point in time (e.g
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-19 03:58

    It's an old question but I still haven't found it documented anywhere.
    I found that the following worked on a playing video with Gstreamer 1.0

    import gi
    import time
    gi.require_version('Gst', '1.0')
    from gi.repository import Gst
    
    def get_frame():
        caps = Gst.Caps('image/png')
        pipeline = Gst.ElementFactory.make("playbin", "playbin")
        pipeline.set_property('uri','file:///home/rolf/GWPE.mp4')
        pipeline.set_state(Gst.State.PLAYING)
        #Allow time for it to start
        time.sleep(0.5)
        # jump 30 seconds
        seek_time = 30 * Gst.SECOND
        pipeline.seek(1.0, Gst.Format.TIME,(Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE),Gst.SeekType.SET, seek_time , Gst.SeekType.NONE, -1)
    
        #Allow video to run to prove it's working, then take snapshot
        time.sleep(1)
        buffer = pipeline.emit('convert-sample', caps)
        buff = buffer.get_buffer()
        result, map = buff.map(Gst.MapFlags.READ)
        if result:
            data = map.data
            pipeline.set_state(Gst.State.NULL)
            return data
        else:
            return
    
    if __name__ == '__main__':
        Gst.init(None)
        image = get_frame()
        with open('frame.png', 'wb') as snapshot:
            snapshot.write(image)
    

    The code should run with both Python2 and Python3, I hope it helps someone.

提交回复
热议问题