Skip to content

Instantly share code, notes, and snippets.

@132ikl
Created January 4, 2020 23:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 132ikl/72167cc915fc3b204f84b8bd29fb67ac to your computer and use it in GitHub Desktop.
Save 132ikl/72167cc915fc3b204f84b8bd29fb67ac to your computer and use it in GitHub Desktop.
Passing OpenCV Mats to GStreamer pipeline without VideoWriter
import cv2
import gi
gi.require_version("Gst", "1.0")
from gi.repository import Gst # isort:skip
WIDTH = 320
HEIGHT = 240
FPS = 30
def need_data(bus, msg):
try:
ret, frame = cap.read()
buf = Gst.Buffer.new_wrapped(frame.tostring())
appsrc.emit("push-buffer", buf)
except StopIteration:
appsrc.emit("end-of-stream")
Gst.init(None)
pipeline = Gst.Pipeline.new(None)
appsrc = Gst.ElementFactory.make("appsrc")
caps = Gst.Caps.from_string(
f"video/x-raw,format=BGR,width={WIDTH},height={HEIGHT},framerate={FPS}/1"
)
appsrc.set_property("caps", caps)
appsrc.connect("need-data", need_data)
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, WIDTH)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, HEIGHT)
cap.set(cv2.CAP_PROP_FPS, FPS)
videoparse = Gst.ElementFactory.make("videoconvert")
xvimagesink = Gst.ElementFactory.make("xvimagesink")
pipeline.add(appsrc)
pipeline.add(videoparse)
pipeline.add(xvimagesink)
appsrc.link(videoparse)
videoparse.link(xvimagesink)
pipeline.set_state(Gst.State.PLAYING)
bus = pipeline.get_bus()
bus.timed_pop_filtered(Gst.CLOCK_TIME_NONE, Gst.MessageType.ERROR | Gst.MessageType.EOS)
pipeline.set_state(Gst.State.NULL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment