I'm trying to get a numpy array out of an gstreamer appsink buffer. But the buffer is to small for numpy to fit it in an array. I picked up on a little bit of code from here: Receive Numpy Array Realtime from GStreamer
I use videotestsource that should return someting the size of 240x320 with 3 channels. But the buffer size is 115200. Coincidentally this is half the size of 240x320x3 (230400). I tried other video sources of different resolutions and the buffer is always half the size. My guess is the appsink signals the on_new_sample function too early.
import time
import gi
import numpy as np
gi.require_version("Gst", "1.0")
gi.require_version("GstApp", "1.0")
from gi.repository import Gst, GstApp, GLib
_ = GstApp
def on_new_sample(app_sink):
sample = app_sink.pull_sample()
caps = sample.get_caps()
# Extract the width and height info from the sample's caps
height = caps.get_structure(0).get_value("height")
width = caps.get_structure(0).get_value("width")
# Get the actual data
buffer = sample.get_buffer()
print(caps,"buffer size ",buffer.get_size())
# Get read access to the buffer data
success, map_info = buffer.map(Gst.MapFlags.READ)
if not success:
raise RuntimeError("Could not map buffer data!")
numpy_frame = np.ndarray(
shape=(height, width, 3),
dtype=np.uint8,
buffer=map_info.data)
buffer.unmap(map_info)
Gst.init(None)
main_loop = GLib.MainLoop()
pipeline = Gst.parse_launch("""videotestsrc ! video/x-raw, width=320, height=240 ! queue ! appsink sync=true max-buffers=1 drop=true name=sink emit-signals=true""")
appsink = pipeline.get_by_name("sink")
pipeline.set_state(Gst.State.PLAYING)
handler_id = appsink.connect("new-sample", on_new_sample)
time.sleep(30)
pipeline.set_state(Gst.State.NULL)
main_loop.quit()
The error I get is as follows:
Traceback (most recent call last):
File "/home/rolf/scripts/tryAlgos/gst_record2.py", line 31, in on_new_sample
numpy_frame = np.ndarray(
TypeError: buffer is too small for requested array
What is the propper way to get from an appsink buffer to a numpy array? I tried some other examples but always returns a buffer that is too small.