Integrating multiple CSI cameras in Deepstream Python

System Specifications:
• Hardware Platform (Jetson / GPU) = Jetson
• DeepStream Version = 6.0.1
• JetPack Version (valid for Jetson only) = 4.6

Hello.

I wanted to run the deepstream pipeline on 2 CSI cameras, it works fine on single CSI input. Please can you provide the sample code for multiple CSI cameras or i have a sample code you can modify that as well

import sys

sys.path.append('../')
import gi
import configparser

gi.require_version('Gst', '1.0')
from gi.repository import GLib, Gst
from ctypes import *
import time
import sys
import math
import platform
from common.is_aarch_64 import is_aarch64
from common.bus_call import bus_call
from common.FPS import PERF_DATA
import numpy as np
import pyds
import cv2
import os
import os.path
from os import path
from common import config
import pika
import logger
import json
perf_data = None

global PGIE_CLASS_ID_CIGAR
PGIE_CLASS_ID_CIGAR = 0

MAX_DISPLAY_LEN = 64
MUXER_OUTPUT_WIDTH = 1920
MUXER_OUTPUT_HEIGHT = 1080
MUXER_BATCH_TIMEOUT_USEC = 4000000
TILED_OUTPUT_WIDTH = 1920
TILED_OUTPUT_HEIGHT = 1080
GST_CAPS_FEATURES_NVMM = "memory:NVMM"

pgie_classes_str= ["Cigar"]

Queue = config.Queue

def initializeChannel():
    credentials = pika.PlainCredentials(config.pika_name,config.pika_name)
    parameters = pika.ConnectionParameters('localhost', 5672, '/', credentials, heartbeat=0, blocked_connection_timeout=3000)
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    channel.queue_declare(queue=Queue,durable = True)
    channel.queue_purge(queue=Queue)
    print("connection established")
    return channel, connection

def overlay(frame, n_detections, tray_no, text):

	position = (10, 50)  
	font = cv2.FONT_HERSHEY_SIMPLEX
	font_scale = 2
	font_color = (0, 255, 0)  
	font_thickness = 2
	cv2.putText(frame, str(n_detections), position, font, font_scale, font_color, font_thickness)

	# Overlay before /after
	position = (10, 100)  # (x, y) coordinates
	font = cv2.FONT_HERSHEY_SIMPLEX
	font_scale = 2
	font_color = (0, 255, 0)  # (B, G, R) color
	font_thickness = 2
	cv2.putText(frame, str(text), position, font, font_scale, font_color, font_thickness)


	# Overlay tray number
	position = (10, 150)  # (x, y) coordinates
	font = cv2.FONT_HERSHEY_SIMPLEX
	font_scale = 1
	font_color = (0, 255, 0)  # (B, G, R) color
	font_thickness = 2
	cv2.putText(frame, "Tray No. " + str(tray_no), position, font, font_scale, font_color, font_thickness)

	return frame


def write_file(file_path, value):
    with open(file_path, 'w') as file:
        file.write(str(value))

def read_file(file_path):
    with open(file_path, 'r') as file:
        value = file.read()
    return value.strip()

def tiler_sink_pad_buffer_probe(pad, info, u_data):
    frame_number = 0
    num_rects = 0
    gst_buffer = info.get_buffer()
    if not gst_buffer:
        print("Unable to get GstBuffer ")
        return

    batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer))

    l_frame = batch_meta.frame_meta_list
    while l_frame is not None:
        try:
            frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data)
        except StopIteration:
            break

        frame_number = frame_meta.frame_num
        l_obj = frame_meta.obj_meta_list
        num_rects = frame_meta.num_obj_meta
        is_first_obj = True
        save_image = False
        last_frame = False
        

        if frame_number == 0:
            global door_opened, recv, transid
            door_opened = False
            #recv = {'cmd':'DoorOpened', 'parm1':'123:True'}

        if frame_number == 83:
            pass
            #recv = {"cmd": "OrderSettled","transaction_id": "123"}
        method_frame, _ ,recv = channel.basic_get(Queue)
        
        
        #print(recv)

        count_cigars = {'Cigar':0}


        while l_obj is not None:
            try:
                obj_meta = pyds.NvDsObjectMeta.cast(l_obj.data)
            except StopIteration:
                break
            
            count_cigars['Cigar']+=1

            if is_first_obj:
                if recv != None:
                #if 'cmd' in recv:
                    print(recv)
                    #print(frame_meta.source_id)
                    #print(frame_number)
                    recv = str(recv,'utf-8')
                    #logger.info(recv) #Debug
                    recv =json.loads(recv)
                    if recv["cmd"] == 'DoorOpened':
                        
                        transid = recv["parm1"].split(":")[0]
                        door_info = recv["parm1"].split(":")[1]
                        #logger.info('\n')
                        #logger.info("    RECV: {} / cvCigar".format(recv["cmd"]))
                        #logger.info("		TRANSID: {}".format(transid))
                        if door_info == 'True':
                            door_opened = True
                        n_frame = pyds.get_nvds_buf_surface(hash(gst_buffer), frame_meta.batch_id)
                        frame_copy = np.array(n_frame, copy=True, order='C')
                        frame_copy = cv2.cvtColor(frame_copy, cv2.COLOR_RGBA2BGRA)
                        #if is_aarch64(): # If Jetson, since the buffer is mapped to CPU for retrieval, it must also be unmapped 
                            #pyds.unmap_nvds_buf_surface(hash(gst_buffer), frame_meta.batch_id)
                        save_image = True
                        #print("Entered Executed")
                        
                        #recv = {'cmd':''}

                    if recv['cmd'] == 'OrderSettled':
                        door_opened = False
                        last_n_frame = pyds.get_nvds_buf_surface(hash(gst_buffer), frame_meta.batch_id)
                        last_frame_copy = np.array(last_n_frame, copy=True, order='C')
                        last_frame_copy = cv2.cvtColor(last_frame_copy, cv2.COLOR_RGBA2BGRA)
                        #if is_aarch64(): # If Jetson, since the buffer is mapped to CPU for retrieval, it must also be unmapped 
                            #pyds.unmap_nvds_buf_surface(hash(gst_buffer), frame_meta.batch_id)
                        last_frame = True
                        save_image = True
                        
                        #recv = {'cmd':''}

                if door_opened:
                    os.makedirs(os.path.join(config.base_path, 'archive', transid, 'frames_1'),exist_ok = True)
                    os.makedirs(os.path.join(config.base_path, 'archive', transid, 'frames_2'),exist_ok = True)
            
                    new_frame = pyds.get_nvds_buf_surface(hash(gst_buffer), frame_meta.batch_id)
                    new_frame_copy = np.array(new_frame, copy=True, order='C')
                    new_frame_copy = cv2.cvtColor(new_frame_copy, cv2.COLOR_RGBA2BGRA)
                    #if is_aarch64(): # If Jetson, since the buffer is mapped to CPU for retrieval, it must also be unmapped 
                        #pyds.unmap_nvds_buf_surface(hash(gst_buffer), frame_meta.batch_id)

                    img_path = os.path.join(config.base_path, 'archive', transid, 'frames_'+str(frame_meta.source_id+1), str(frame_number)+'.jpg')
                    cv2.imwrite(img_path, new_frame_copy)


                is_first_obj = False

            try:
                l_obj = l_obj.next
            except StopIteration:
                break

        print("Source ID=" , frame_meta.source_id, " Frame Number=", frame_number, "Number of Objects=", num_rects)# update frame rate through this probe
        
        stream_index = "stream{0}".format(frame_meta.pad_index)
        global perf_data
        perf_data.update_fps(stream_index)
        if save_image:
            os.makedirs(os.path.join(config.base_path, 'archive', transid),exist_ok = True)
            if frame_meta.source_id == 0:
                tray_no = '23'
                file_name = 'Cam1.txt'
            else:
                tray_no = '25'
                file_name = 'Cam2.txt'


            if last_frame:
                last_frame_copy = overlay(last_frame_copy, count_cigars['Cigar'], tray_no, 'After')
                cv2.imwrite("{}archive/{}/last_frame{}.jpg".format(config.base_path, transid, frame_meta.pad_index), last_frame_copy)
                initial_cigar_count = int(read_file(os.path.join(config.base_path, 'archive', transid, file_name)))
                if frame_meta.source_id == 0:
                    print("Cam1 Before",initial_cigar_count)
                    print("Cam1 After", count_cigars)
                    print("Cam2 Cigars Sold", initial_cigar_count-count_cigars["Cigar"])
                else:
                    print("Cam2 Before",initial_cigar_count)
                    print("Cam2 After", count_cigars)
                    print("Cam2 Cigars Sold", initial_cigar_count-count_cigars["Cigar"])
            
            else:    
                frame_copy = overlay(frame_copy, count_cigars['Cigar'], tray_no, 'Before')
                cv2.imwrite("{}archive/{}/first_frame{}.jpg".format(config.base_path, transid, frame_meta.pad_index), frame_copy)
                write_file(os.path.join(config.base_path, 'archive', transid, file_name), count_cigars['Cigar'])

        try:
            l_frame = l_frame.next
        except StopIteration:
            break

    return Gst.PadProbeReturn.OK




def cb_newpad(decodebin, decoder_src_pad, data):
    print("In cb_newpad\n")
    caps = decoder_src_pad.get_current_caps()
    gststruct = caps.get_structure(0)
    gstname = gststruct.get_name()
    source_bin = data
    features = caps.get_features(0)

    # Need to check if the pad created by the decodebin is for video and not
    # audio.
    if (gstname.find("video") != -1):
        # Link the decodebin pad only if decodebin has picked nvidia
        # decoder plugin nvdec_*. We do this by checking if the pad caps contain
        # NVMM memory features.
        if features.contains("memory:NVMM"):
            # Get the source bin ghost pad
            bin_ghost_pad = source_bin.get_static_pad("src")
            if not bin_ghost_pad.set_target(decoder_src_pad):
                sys.stderr.write("Failed to link decoder src pad to source bin ghost pad\n")
        else:
            sys.stderr.write(" Error: Decodebin did not pick nvidia decoder plugin.\n")


def decodebin_child_added(child_proxy, Object, name, user_data):
    print("Decodebin child added:", name, "\n")
    if name.find("decodebin") != -1:
        Object.connect("child-added", decodebin_child_added, user_data)

    if not is_aarch64() and name.find("nvv4l2decoder") != -1:
        # Use CUDA unified memory in the pipeline so frames
        # can be easily accessed on CPU in Python.
        Object.set_property("cudadec-memtype", 2)

    if "source" in name:
        source_element = child_proxy.get_by_name("source")
        if source_element.find_property('drop-on-latency') != None:
            Object.set_property("drop-on-latency", True)

def create_source_bin(index, uri):
    print("Creating source bin")

    # Create a source GstBin to abstract this bin's content from the rest of the
    # pipeline
    bin_name = "source-bin-%02d" % index
    print(bin_name)
    nbin = Gst.Bin.new(bin_name)
    if not nbin:
        sys.stderr.write(" Unable to create source bin \n")

    # Source element for reading from the uri.
    # We will use decodebin and let it figure out the container format of the
    # stream and the codec and plug the appropriate demux and decode plugins.
    uri_decode_bin = Gst.ElementFactory.make("uridecodebin", "uri-decode-bin")
    if not uri_decode_bin:
        sys.stderr.write(" Unable to create uri decode bin \n")
    # We set the input uri to the source element
    uri_decode_bin.set_property("uri", uri)
    # Connect to the "pad-added" signal of the decodebin which generates a
    # callback once a new pad for raw data has beed created by the decodebin
    uri_decode_bin.connect("pad-added", cb_newpad, nbin)
    uri_decode_bin.connect("child-added", decodebin_child_added, nbin)

    # We need to create a ghost pad for the source bin which will act as a proxy
    # for the video decoder src pad. The ghost pad will not have a target right
    # now. Once the decode bin creates the video decoder and generates the
    # cb_newpad callback, we will set the ghost pad target to the video decoder
    # src pad.
    Gst.Bin.add(nbin, uri_decode_bin)
    bin_pad = nbin.add_pad(Gst.GhostPad.new_no_target("src", Gst.PadDirection.SRC))
    if not bin_pad:
        sys.stderr.write(" Failed to add ghost pad in source bin \n")
        return None
    return nbin

def main(args):
    # Check input arguments
    if len(args) < 2:
        sys.stderr.write("usage: %s <uri1> [uri2] ... [uriN] <folder to save frames>\n" % args[0])
        sys.exit(1)

    global perf_data
    perf_data = PERF_DATA(len(args) - 1)
    number_sources = len(args) - 1

    global channel, connection
    channel, connection = initializeChannel()
    # Standard GStreamer initialization
    Gst.init(None)

    # Create gstreamer elements */
    # Create Pipeline element that will form a connection of other elements
    print("Creating Pipeline \n ")
    pipeline = Gst.Pipeline()
    is_live = False

    if not pipeline:
        sys.stderr.write(" Unable to create Pipeline \n")
    print("Creating streamux \n ")

    source = Gst.ElementFactory.make("nvarguscamerasrc", "src-elem")
    if not source:
        sys.stderr.write(" Unable to create Source \n")

    # Converter to scale the image
    nvvidconv_src = Gst.ElementFactory.make("nvvideoconvert", "convertor_src")
    if not nvvidconv_src:
        sys.stderr.write(" Unable to create nvvidconv_src \n")

    # Caps for NVMM and resolution scaling
    caps_nvvidconv_src = Gst.ElementFactory.make("capsfilter", "nvmm_caps")
    if not caps_nvvidconv_src:
        sys.stderr.write(" Unable to create capsfilter \n")

    # Create nvstreammux instance to form batches from one or more sources.
    streammux = Gst.ElementFactory.make("nvstreammux", "Stream-muxer")
    if not streammux:
        sys.stderr.write(" Unable to create NvStreamMux \n")

    pgie = Gst.ElementFactory.make("nvinfer", "primary-inference")
    if not pgie:
        sys.stderr.write(" Unable to create pgie \n")
    # Add nvvidconv1 and filter1 to convert the frames to RGBA
    # which is easier to work with in Python.
    print("Creating nvvidconv1 \n ")
    nvvidconv1 = Gst.ElementFactory.make("nvvideoconvert", "convertor1")
    if not nvvidconv1:
        sys.stderr.write(" Unable to create nvvidconv1 \n")
    print("Creating filter1 \n ")
    caps1 = Gst.Caps.from_string("video/x-raw(memory:NVMM), format=RGBA")
    filter1 = Gst.ElementFactory.make("capsfilter", "filter1")
    if not filter1:
        sys.stderr.write(" Unable to get the caps filter1 \n")
    filter1.set_property("caps", caps1)
    print("Creating tiler \n ")
    tiler = Gst.ElementFactory.make("nvmultistreamtiler", "nvtiler")
    if not tiler:
        sys.stderr.write(" Unable to create tiler \n")
    print("Creating nvvidconv \n ")
    nvvidconv = Gst.ElementFactory.make("nvvideoconvert", "convertor")
    if not nvvidconv:
        sys.stderr.write(" Unable to create nvvidconv \n")
    print("Creating nvosd \n ")
    nvosd = Gst.ElementFactory.make("nvdsosd", "onscreendisplay")
    if not nvosd:
        sys.stderr.write(" Unable to create nvosd \n")
    if is_aarch64():
        print("Creating nv3dsink \n")
        sink = Gst.ElementFactory.make("fakesink", "fakesink")
        if not sink:
            sys.stderr.write(" Unable to create nv3dsink \n")
    else:
        print("Creating EGLSink \n")
        sink = Gst.ElementFactory.make("fakesink", "fakesink")
        if not sink:
            sys.stderr.write(" Unable to create egl sink \n")

    source.set_property('bufapi-version', True)

    caps_nvvidconv_src.set_property('caps', Gst.Caps.from_string('video/x-raw(memory:NVMM), width=1280, height=720'))

    streammux.set_property('width', 1280)
    streammux.set_property('height', 720)
    streammux.set_property('batch-size', 1)
    streammux.set_property('batched-push-timeout', 4000000)

    pgie.set_property('config-file-path', "configs/pgie_yolov8.txt")
    pgie_batch_size = pgie.get_property("batch-size")
    if (pgie_batch_size != number_sources):
        print("WARNING: Overriding infer-config batch-size", pgie_batch_size, " with number of sources ",
              number_sources, " \n")
        pgie.set_property("batch-size", number_sources)
    tiler_rows = int(math.sqrt(number_sources))
    tiler_columns = int(math.ceil((1.0 * number_sources) / tiler_rows))
    tiler.set_property("rows", tiler_rows)
    tiler.set_property("columns", tiler_columns)
    tiler.set_property("width", TILED_OUTPUT_WIDTH)
    tiler.set_property("height", TILED_OUTPUT_HEIGHT)

    sink.set_property("sync", 0)
    sink.set_property("qos", 0)

    if not is_aarch64():
        # Use CUDA unified memory in the pipeline so frames
        # can be easily accessed on CPU in Python.
        mem_type = int(pyds.NVBUF_MEM_CUDA_UNIFIED)
        streammux.set_property("nvbuf-memory-type", mem_type)
        nvvidconv.set_property("nvbuf-memory-type", mem_type)
        nvvidconv1.set_property("nvbuf-memory-type", mem_type)
        tiler.set_property("nvbuf-memory-type", mem_type)

    print("Adding elements to Pipeline \n")
    pipeline.add(source)
    pipeline.add(nvvidconv_src)
    pipeline.add(caps_nvvidconv_src)
    pipeline.add(streammux)
    pipeline.add(pgie)
    pipeline.add(tiler)
    pipeline.add(nvvidconv)
    pipeline.add(filter1)
    pipeline.add(nvvidconv1)
    pipeline.add(nvosd)
    pipeline.add(sink)



    source.link(nvvidconv_src)
    nvvidconv_src.link(caps_nvvidconv_src)

    sinkpad = streammux.get_request_pad("sink_0")
    if not sinkpad:
        sys.stderr.write(" Unable to get the sink pad of streammux \n")
    srcpad = caps_nvvidconv_src.get_static_pad("src")
    if not srcpad:
        sys.stderr.write(" Unable to get source pad of source \n")
    srcpad.link(sinkpad)
    streammux.link(pgie)
    pgie.link(nvvidconv1)
    nvvidconv1.link(filter1)
    filter1.link(tiler)
    tiler.link(nvvidconv)
    nvvidconv.link(nvosd)
    nvosd.link(sink)

    # create an event loop and feed gstreamer bus mesages to it
    loop = GLib.MainLoop()
    bus = pipeline.get_bus()
    bus.add_signal_watch()
    bus.connect("message", bus_call, loop)

    tiler_sink_pad = tiler.get_static_pad("sink")
    if not tiler_sink_pad:
        sys.stderr.write(" Unable to get src pad \n")
    else:
        #print("Hello World")
        tiler_sink_pad.add_probe(Gst.PadProbeType.BUFFER, tiler_sink_pad_buffer_probe, 0)
        # perf callback function to print fps every 5 sec
        GLib.timeout_add(5000, perf_data.perf_print_callback)

    # List the sources
    print("Now playing...")
    for i, source in enumerate(args[:-1]):
        if i != 0:
            print(i, ": ", source)

    print("Starting pipeline \n")
    # start play back and listed to events		
    pipeline.set_state(Gst.State.PLAYING)
    try:
        loop.run()
    except:
        pass
    # cleanup
    print("Exiting app\n")
    pipeline.set_state(Gst.State.NULL)


if __name__ == '__main__':
    sys.exit(main(sys.argv))

Just build the pipeline as follows

nvarguscamerasrc sensor-id=0 |
                             |   -- > nvstreammux ......
nvarguscamerasrc sensor-id=1 |

Or you can use deepstream-app, deepstream-app supports multiple CSI cameras