This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

TDA4VM: Unable to run real time inference of yolox_s_lite on TDA4VM

Part Number: TDA4VM

Tool/software:

I have trained the yolox_s_lite model on custom dataset using EDGEAI-MODELMAKER.

Due to local system shut down, the training was stopped at 158th epoch, so I have converted .pth file of model at 158th epoch to .onnx format using EDGEAI-MMDETECTION present inside EDGEAI-TENSORLAB repo.

Then I compiled this .onnx model with the onnxrt_ep.py file present inside the EDGEAI-TIDL-TOOLS repo. While compilation I got the error which says that "IR & OPSET version are mismatched which were before IR10 & OPSET17 , then using below script, I converted them to desired IR and OPSET version which were IR9 & OPSET12, 

"""

m = onnx.load(src)

print("Before -> IR:", m.ir_version, "opsets:",
[(imp.domain or "ai.onnx", imp.version) for imp in m.opset_import])

# Force IR version to 9 (do NOT touch opset)
m.ir_version = 9

onnx.save(m, dst)

# Optional: checker may complain about strict IR/opset pairing; you can skip it
try:
from onnx import checker
checker.check_model(dst)
print("ONNX checker passed.")
except Exception as e:
print("Checker warning:", e)

print("Saved:", dst)

 """

Then the compilation using TIDL TOOLS was successful. 

But still when I am inferecing .onnx model in the PC, it is predicting the bounding boxes correctly , but when I am uploading model, its prototxt and artifacts in the TDA4VM board, it is not able to detect the bounding boxes , only the camera based video starts running without detections ??? 

What should be the reasons??

Could you please provide the solution to it ?

For reference, below is the script that we are using for inferencing on TDA4VM board:

import os

import cv2

import numpy as np

import onnxruntime as ort

import time

import gi

gi.require_version('Gst', '1.0')

from gi.repository import Gst

 

# --- Set TIDL Environment Variables ---

os.environ["TIDL_RT_PERFSTATS"] = "1"

os.environ["TIDL_RT_LOG_LEVEL"] = "2"

 

# Initialize GStreamer

Gst.init(None)

 

# --- GStreamer OUTPUT PIPELINE ---

gst_output_pipeline = (

    "appsrc name=src is-live=true block=true format=GST_FORMAT_TIME "

    "caps=video/x-raw,format=BGR,width=1280,height=720,framerate=30/1 ! "

    "videoconvert ! queue ! waylandsink sync=false"

)

pipeline = Gst.parse_launch(gst_output_pipeline)

appsrc = pipeline.get_by_name("src")

pipeline.set_state(Gst.State.PLAYING)

 

# --- GStreamer INPUT PIPELINE ---

camera_pipeline = (

    "v4l2src device=/dev/video2 ! "

    "image/jpeg,width=1280,height=720,framerate=30/1 ! jpegdec ! "

    "videoconvert ! video/x-raw,format=BGR ! appsink"

)

cap = cv2.VideoCapture(camera_pipeline, cv2.CAP_GSTREAMER)

if not cap.isOpened():

    print("X ERROR: Could not open /dev/video2")

    exit(1)

 

# --- Load TIDL-compiled model ----

model_path = "/opt/model_zoo/158_onnxrt_Dataset_Buit_Over_COCO_edgeai-mmdet_yolox_s_lite__model_onnx/model/yolox_s_lite_158_ir9_opset12.onnx"

session = ort.InferenceSession(

    model_path,

    providers=["TIDLExecutionProvider", "CPUExecutionProvider"],

    provider_options=[

        {"artifacts_folder": "/opt/model_zoo/158_onnxrt_Dataset_Buit_Over_COCO_edgeai-mmdet_yolox_s_lite__model_onnx/artifacts",

         "platform": "J7"},

        {}

    ]

)

 

input_name = session.get_inputs()[0].name

output_names = [o.name for o in session.get_outputs()]

 

# --- Custom 7 classes ---

CLASSES = ["person", "bicycle", "car", "motorcycle", "bus", "truck", "rickshaw"]

 

# ---------- PREPROCESS ----------

def preprocess(image, W=640, H=640, layout="NCHW"):

    resized = cv2.resize(image, (W, H), interpolation=cv2.INTER_LINEAR)

    rgb = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)

    if layout == "NCHW":

        blob = rgb.transpose(2, 0, 1)[None, ...]

    else:

        blob = rgb[None, ...]

    return np.ascontiguousarray(blob, dtype=np.float32)  Warning️ no /255.0

 

# ---------- NMS (NumPy implementation) ----------

def nms_numpy(boxes, scores, conf_threshold=0.3, nms_threshold=0.4):

    boxes = np.array(boxes)

    scores = np.array(scores)

 

    # Filter by confidence

    keep = scores >= conf_threshold

    boxes, scores = boxes[keep], scores[keep]

    indices = np.where(keep)[0]

 

    if len(boxes) == 0:

        return []

 

    x1 = boxes[:, 0]

    y1 = boxes[:, 1]

    x2 = boxes[:, 0] + boxes[:, 2]

    y2 = boxes[:, 1] + boxes[:, 3]

    areas = (x2 - x1 + 1) * (y2 - y1 + 1)

 

    order = scores.argsort()[::-1]

    keep_indices = []

 

    while order.size > 0:

        i = order[0]

        keep_indices.append(indices[i])

 

        xx1 = np.maximum(x1[i], x1[order[1:]])

        yy1 = np.maximum(y1[i], y1[order[1:]])

        xx2 = np.minimum(x2[i], x2[order[1:]])

        yy2 = np.minimum(y2[i], y2[order[1:]])

 

        w = np.maximum(0.0, xx2 - xx1 + 1)

        h = np.maximum(0.0, yy2 - yy1 + 1)

        inter = w * h

 

        iou = inter / (areas[i] + areas[order[1:]] - inter)

 

        inds = np.where(iou <= nms_threshold)[0]

        order = order[inds + 1]

 

    return keep_indices

 

# ---------- GENERIC DECODER ----------

def try_parse_outputs(outs):

    def looks_like_boxes(a):

        return a.ndim >= 2 and a.shape[-1] in (5, 6, 7) and np.issubdtype(a.dtype, np.floating)

 

    def looks_like_labels(a):

        return np.issubdtype(a.dtype, np.integer) and (a.ndim in (1, 2, 3))

 

    def squeeze_to_2d(a):

        a = np.array(a)

        while a.ndim > 2:

            a = a.reshape(-1, a.shape[-1])

        return a

 

    if len(outs) == 2:

        a, b = outs

        if looks_like_boxes(a) and looks_like_labels(b):

            dets, labs = squeeze_to_2d(a), squeeze_to_2d(b).reshape(-1)

        elif looks_like_boxes(b) and looks_like_labels(a):

            dets, labs = squeeze_to_2d(b), squeeze_to_2d(a).reshape(-1)

        else:

            raise RuntimeError("Cannot classify outputs.")

 

        if dets.shape[1] >= 5:

            boxes, scores = dets[:, :4], dets[:, 4]

            if dets.shape[1] >= 6:

                classes = dets[:, 5].astype(np.int32)

            else:

                classes = labs.astype(np.int32)

            return boxes, scores, classes

 

    elif len(outs) == 1:

        x = np.array(outs[0])

        while x.ndim > 2:

            x = x.reshape(-1, x.shape[-1])

        if x.shape[1] in (6, 7):

            boxes, scores, classes = x[:, :4], x[:, 4], x[:, 5].astype(np.int32)

            return boxes, scores, classes

 

    raise RuntimeError("Unexpected model outputs layout.")

 

print("White check mark Running object detection with TIDL acceleration... Press Ctrl+C to stop.")

 

try:

    while True:

        start_time = time.time()

        ret, frame = cap.read()

        if not ret:

            print("Warning️ Failed to read frame")

            continue

 

        # Inference

        outs = session.run(output_names, {input_name: preprocess(frame)})

        boxes_xyxy, scores, class_ids = try_parse_outputs(outs)

 

        # Filter + NMS

        CONF_THRESHOLD, NMS_THRESHOLD = 0.3, 0.4

        keep = scores >= CONF_THRESHOLD

        boxes_xyxy, scores, class_ids = boxes_xyxy[keep], scores[keep], class_ids[keep]

 

        boxes_xywh = boxes_xyxy.copy()

        boxes_xywh[:, 2] -= boxes_xyxy[:, 0]

        boxes_xywh[:, 3] -= boxes_xyxy[:, 1]

 

        boxes_list = boxes_xywh.astype(int).tolist()

        scores_list = scores.astype(float).tolist()

        idxs = nms_numpy(boxes_list, scores_list, CONF_THRESHOLD, NMS_THRESHOLD)

 

        # Draw detections

        sx, sy = frame.shape[1] / 640.0, frame.shape[0] / 640.0

        for i in idxs:

            x, y, w, h = boxes_list[i]

            x1, y1 = int(round(x * sx)), int(round(y * sy))

            x2, y2 = int(round((x + w) * sx)), int(round((y + h) * sy))

            cls = int(class_ids[i])

            name = CLASSES[cls] if 0 <= cls < len(CLASSES) else str(cls)

            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)

            cv2.putText(frame, f"{name} {scores_list[i]:.2f}", (x1, max(0, y1 - 5)),

                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

            if cls == 0:

                print("label:", name, f"{scores_list[i]:.2f}", "x1:", x1, "y1:", y1, "x2:", x2, "y2:", y2)

 

        # Send to GStreamer sink

        data = frame.tobytes()

        buf = Gst.Buffer.new_allocate(None, len(data), None)

        buf.fill(0, data)

        buf.duration = Gst.util_uint64_scale_int(1, Gst.SECOND, 30)

        timestamp = int(time.time() * Gst.SECOND)

        buf.pts = buf.dts = timestamp

        appsrc.emit("push-buffer", buf)

 

        # Frame rate limiting

        elapsed = time.time() - start_time

        delay = max(0, (1 / 30) - elapsed)

        time.sleep(delay)

 

except KeyboardInterrupt:

    print("Octagonal sign Interrupted. Cleaning up...")

 

finally:

    cap.release()

    pipeline.set_state(Gst.State.NULL)

  • Hi Chaitanya,

    Could you share your SDK version, model, model-artifacts and the artifacts you created? You mentioned on PC that this ran correctly right? 

    I recommend running the model based off of our base flow found on our Github before running your own script, just to eliminate variables and ensure that the model is able to run properly on the device. 

    More information on how to can be found here: https://github.com/TexasInstruments/edgeai-tidl-tools/tree/master

    Warm regards,

    Christina

  • Hi Christina,

    The sdk version that I used for compiling the model through Edgeai-tidl-tools was : 10.01.00.04

    The link of the folder containing the zip file of the model after compilation which I am currently using on the board TDA4VM is given below:

    https://drive.google.com/drive/folders/175qEDnnx4tOCIrn61UTg7yc4a7UgpgAs?usp=sharing

    If you have any problem regarding the access, then feel free to ask. 

    I just wanted the reason why the compiled model that I am running on TDA4VM is not able to generate detections??? 

    Thanks,

    Chaitanya

  • Hi Chaitanya,

    Christina moved this to my queue and thank you for providing the model.  Please send me the command line that is working in emulation and not working on the EVM.   There were 3 models in the zip file, which model are you having an issue with?

    158_onnxrt_Dataset_Buit_Over_COCO_edgeai-mmdet_yolox_s_lite__model_onnx/model/yolox_s_lite_158_supported.onnx
    158_onnxrt_Dataset_Buit_Over_COCO_edgeai-mmdet_yolox_s_lite__model_onnx/model/yolox_s_lite_158.onnx
    158_onnxrt_Dataset_Buit_Over_COCO_edgeai-mmdet_yolox_s_lite__model_onnx/model/yolox_s_lite_158_ir9_opset12.onnx

    Regards,

    Chris

  • Hi; based on your input, it seems that your model had some error during compiling. What is your "opset" number when you re-train/convert the yolo model? If it complained about mismatching, it may indicate some operator is missing during training/converting.

    Best regards

    Wen Li     

  • Hi, 

    Yes, there was error while compiling the model. It was IR and opset version mismatch error. The model that we got after training was of below version:

    IR Version: 10
    Producer Name: onnx-TIDL
    Opset Domain: ai.onnx, Version: 17


    But while compiling through TIDL, I was getting the error that IR and opset versions are mismatched with the required one for compilation through EDGE-AI TIDL TOOLS (onnxrt_ep.py), expected was below IR version: 9 and opset :12.

    Regards,

    Chaitanya

  • Hi Chris,

    I am using the "158_onnxrt_Dataset_Buit_Over_COCO_edgeai-mmdet_yolox_s_lite__model_onnx/model/yolox_s_lite_158_ir9_opset12.onnx " model as the model that I got from modelmaker was not able to compiled due to IR and opset mismatch issue. So I need t convert to desired version.

    The code that I am using for inference on laptop is below:

    import cv2
    import numpy as np
    import onnxruntime as ort
    import matplotlib.pyplot as plt

    # ---------- CONFIG ----------
    MODEL_PATH = r"\\wsl.localhost\Ubuntu\home\chai\edgeai-tidl-tools\model-artifacts\158_onnxrt_Dataset_Buit_Over_COCO_edgeai-mmdet_yolox_s_lite__model_onnx\model\yolox_s_lite_158.onnx"
    IMAGE_PATH = r"D:\Chaitanya Suryawanshi\Pretrained Model weights\sample_test_images\frame_0006_152.jpg"
    CONF_THRESHOLD = 0.3
    NMS_THRESHOLD = 0.4
    CLASSES = ['person']

    # ---------- LOAD MODEL ----------
    sess = ort.InferenceSession(MODEL_PATH, providers=["CPUExecutionProvider"])
    inp = sess.get_inputs()[0]
    in_name = inp.name
    in_shape = inp.shape
    print("Input:", in_name, in_shape, inp.type)

    # Layout & size
    if len(in_shape) == 4:
    b, d1, d2, d3 = in_shape
    if d1 == 3:
    layout, H, W = "NCHW", d2, d3
    elif d3 == 3:
    layout, H, W = "NHWC", d1, d2
    else:
    layout, H, W = "NCHW", 640, 640
    else:
    layout, H, W = "NCHW", 640, 640

    # ---------- PREPROCESS (UINT8, RGB, NO /255) ----------
    img0 = cv2.imread(IMAGE_PATH)
    assert img0 is not None
    oh, ow = img0.shape[:2]

    resized = cv2.resize(img0, (W, H), interpolation=cv2.INTER_LINEAR)
    rgb = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)

    if layout == "NCHW":
    blob = rgb.transpose(2, 0, 1)[None, ...]
    else:
    blob = rgb[None, ...]

    blob = np.ascontiguousarray(blob, dtype=np.float32)

    # ---------- INFER & INSPECT ----------
    outs = sess.run(None, {in_name: blob})
    print("Num outputs:", len(outs))
    for i, o in enumerate(outs):
    print(f" out[{i}] -> shape={o.shape}, dtype={o.dtype}, "
    f"min={o.min() if o.size else 'NA'}, max={o.max() if o.size else 'NA'}")

    # ---------- GENERIC DECODER ----------
    def try_parse_outputs(outs):
    """
    Returns (boxes_xyxy, scores, class_ids) in resized-space.
    Tries common TI/YOLOX variants.
    """

    def looks_like_boxes(a):
    if a.ndim < 2:
    return False
    last = a.shape[-1]
    return (last in (5, 6, 7)) and np.issubdtype(a.dtype, np.floating)

    def looks_like_labels(a):
    return np.issubdtype(a.dtype, np.integer) and (a.ndim in (1, 2, 3))

    def squeeze_to_2d(a):
    a = np.array(a)
    while a.ndim > 2:
    a = a.reshape(-1, a.shape[-1])
    return a

    # Case: two outputs
    if len(outs) == 2:
    a, b = outs
    if looks_like_boxes(a) and looks_like_labels(b):
    dets = squeeze_to_2d(a)
    labs = squeeze_to_2d(b).reshape(-1)
    elif looks_like_boxes(b) and looks_like_labels(a):
    dets = squeeze_to_2d(b)
    labs = squeeze_to_2d(a).reshape(-1)
    else:
    floats = [x for x in outs if np.issubdtype(x.dtype, np.floating)]
    ints = [x for x in outs if np.issubdtype(x.dtype, np.integer)]
    if len(floats) == 1 and len(ints) == 1:
    dets = squeeze_to_2d(floats[0])
    labs = squeeze_to_2d(ints[0]).reshape(-1)
    else:
    raise RuntimeError("Cannot classify outputs as dets/labels.")

    if dets.shape[1] == 5:
    boxes = dets[:, :4]
    scores = dets[:, 4]
    if labs.shape[0] != dets.shape[0]:
    if labs.ndim == 2 and labs.shape[1] == 1 and labs.shape[0] == dets.shape[0]:
    labs = labs[:, 0]
    else:
    raise RuntimeError("Labels length mismatch for (N,5) dets.")
    classes = labs.astype(np.int32)
    return boxes, scores, classes

    elif dets.shape[1] >= 6:
    boxes = dets[:, :4]
    scores = dets[:, 4]
    classes = dets[:, 5].astype(np.int32)
    return boxes, scores, classes

    else:
    raise RuntimeError(f"Unsupported dets shape {dets.shape}")

    # Case: single output
    if len(outs) == 1:
    x = outs[0]
    x2 = np.array(x)
    while x2.ndim > 2:
    x2 = x2.reshape(-1, x2.shape[-1])
    if x2.ndim != 2:
    raise RuntimeError(f"Unexpected single output shape: {outs[0].shape}")

    if x2.shape[1] == 6:
    boxes = x2[:, :4]
    scores = x2[:, 4]
    classes = x2[:, 5].astype(np.int32)
    return boxes, scores, classes
    elif x2.shape[1] == 7:
    boxes = x2[:, :4]
    scores = x2[:, 4]
    classes = x2[:, 5].astype(np.int32)
    return boxes, scores, classes
    elif x2.shape[1] == 5:
    raise RuntimeError("Got (N,5) without labels; need the labels tensor.")
    else:
    raise RuntimeError(f"Unsupported single-output last dim {x2.shape[1]}")

    raise RuntimeError("Unexpected model outputs layout.")

    # Try to parse
    boxes_xyxy, scores, class_ids = try_parse_outputs(outs)

    # ---------- FILTER + NMS ----------
    keep = scores >= CONF_THRESHOLD
    boxes_xyxy = boxes_xyxy[keep]
    scores = scores[keep]
    class_ids = class_ids[keep]

    boxes_xywh = boxes_xyxy.copy()
    boxes_xywh[:, 2] = boxes_xyxy[:, 2] - boxes_xyxy[:, 0]
    boxes_xywh[:, 3] = boxes_xyxy[:, 3] - boxes_xyxy[:, 1]

    boxes_list = boxes_xywh.astype(int).tolist()
    scores_list = scores.astype(float).tolist()

    idxs = cv2.dnn.NMSBoxes(boxes_list, scores_list, CONF_THRESHOLD, NMS_THRESHOLD)
    idxs = [int(i) if not isinstance(i, (list, tuple, np.ndarray)) else int(i[0]) for i in idxs]

    # ---------- DRAW (map back to original size) ----------
    sx, sy = ow / float(W), oh / float(H)
    vis = img0.copy()
    for i in idxs:
    x, y, w, h = boxes_list[i]
    x1 = int(round(x * sx)); y1 = int(round(y * sy))
    x2 = int(round((x + w) * sx)); y2 = int(round((y + h) * sy))
    cls = int(class_ids[i])
    name = CLASSES[cls] if 0 <= cls < len(CLASSES) else str(cls)
    cv2.rectangle(vis, (x1, y1), (x2, y2), (0, 255, 0), 2)
    cv2.putText(vis, f"{name} {scores_list[i]:.2f}", (x1, max(0, y1 - 5)),
    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

    # ---------- SHOW INLINE (no separate window) ----------
    plt.figure(figsize=(10, 8))
    plt.imshow(cv2.cvtColor(vis, cv2.COLOR_BGR2RGB))
    plt.axis("off")
    plt.show()



    And the code that I am using for inference on board is below:

    import os

    import cv2

    import numpy as np

    import onnxruntime as ort

    import time

    import gi

    gi.require_version('Gst', '1.0')

    from gi.repository import Gst

     

    # --- Set TIDL Environment Variables ---

    os.environ["TIDL_RT_PERFSTATS"] = "1"

    os.environ["TIDL_RT_LOG_LEVEL"] = "2"

     

    # Initialize GStreamer

    Gst.init(None)

     

    # --- GStreamer OUTPUT PIPELINE ---

    gst_output_pipeline = (

        "appsrc name=src is-live=true block=true format=GST_FORMAT_TIME "

        "caps=video/x-raw,format=BGR,width=1280,height=720,framerate=30/1 ! "

        "videoconvert ! queue ! waylandsink sync=false"

    )

    pipeline = Gst.parse_launch(gst_output_pipeline)

    appsrc = pipeline.get_by_name("src")

    pipeline.set_state(Gst.State.PLAYING)

     

    # --- GStreamer INPUT PIPELINE ---

    camera_pipeline = (

        "v4l2src device=/dev/video2 ! "

        "image/jpeg,width=1280,height=720,framerate=30/1 ! jpegdec ! "

        "videoconvert ! video/x-raw,format=BGR ! appsink"

    )

    cap = cv2.VideoCapture(camera_pipeline, cv2.CAP_GSTREAMER)

    if not cap.isOpened():

        print("X ERROR: Could not open /dev/video2")

        exit(1)

     

    # --- Load TIDL-compiled model ----

    model_path = "/opt/model_zoo/158_onnxrt_Dataset_Buit_Over_COCO_edgeai-mmdet_yolox_s_lite__model_onnx/model/yolox_s_lite_158_ir9_opset12.onnx"

    session = ort.InferenceSession(

        model_path,

        providers=["TIDLExecutionProvider", "CPUExecutionProvider"],

        provider_options=[

            {"artifacts_folder": "/opt/model_zoo/158_onnxrt_Dataset_Buit_Over_COCO_edgeai-mmdet_yolox_s_lite__model_onnx/artifacts",

             "platform": "J7"},

            {}

        ]

    )

     

    input_name = session.get_inputs()[0].name

    output_names = [o.name for o in session.get_outputs()]

     

    # --- Custom 7 classes ---

    CLASSES = ["person", "bicycle", "car", "motorcycle", "bus", "truck", "rickshaw"]

     

    # ---------- PREPROCESS ----------

    def preprocess(image, W=640, H=640, layout="NCHW"):

        resized = cv2.resize(image, (W, H), interpolation=cv2.INTER_LINEAR)

        rgb = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)

        if layout == "NCHW":

            blob = rgb.transpose(2, 0, 1)[None, ...]

        else:

            blob = rgb[None, ...]

        return np.ascontiguousarray(blob, dtype=np.float32)  Warning️ no /255.0

     

    # ---------- NMS (NumPy implementation) ----------

    def nms_numpy(boxes, scores, conf_threshold=0.3, nms_threshold=0.4):

        boxes = np.array(boxes)

        scores = np.array(scores)

     

        # Filter by confidence

        keep = scores >= conf_threshold

        boxes, scores = boxes[keep], scores[keep]

        indices = np.where(keep)[0]

     

        if len(boxes) == 0:

            return []

     

        x1 = boxes[:, 0]

        y1 = boxes[:, 1]

        x2 = boxes[:, 0] + boxes[:, 2]

        y2 = boxes[:, 1] + boxes[:, 3]

        areas = (x2 - x1 + 1) * (y2 - y1 + 1)

     

        order = scores.argsort()[::-1]

        keep_indices = []

     

        while order.size > 0:

            i = order[0]

            keep_indices.append(indices[i])

     

            xx1 = np.maximum(x1[i], x1[order[1:]])

            yy1 = np.maximum(y1[i], y1[order[1:]])

            xx2 = np.minimum(x2[i], x2[order[1:]])

            yy2 = np.minimum(y2[i], y2[order[1:]])

     

            w = np.maximum(0.0, xx2 - xx1 + 1)

            h = np.maximum(0.0, yy2 - yy1 + 1)

            inter = w * h

     

            iou = inter / (areas[i] + areas[order[1:]] - inter)

     

            inds = np.where(iou <= nms_threshold)[0]

            order = order[inds + 1]

     

        return keep_indices

     

    # ---------- GENERIC DECODER ----------

    def try_parse_outputs(outs):

        def looks_like_boxes(a):

            return a.ndim >= 2 and a.shape[-1] in (5, 6, 7) and np.issubdtype(a.dtype, np.floating)

     

        def looks_like_labels(a):

            return np.issubdtype(a.dtype, np.integer) and (a.ndim in (1, 2, 3))

     

        def squeeze_to_2d(a):

            a = np.array(a)

            while a.ndim > 2:

                a = a.reshape(-1, a.shape[-1])

            return a

     

        if len(outs) == 2:

            a, b = outs

            if looks_like_boxes(a) and looks_like_labels(b):

                dets, labs = squeeze_to_2d(a), squeeze_to_2d(b).reshape(-1)

            elif looks_like_boxes(b) and looks_like_labels(a):

                dets, labs = squeeze_to_2d(b), squeeze_to_2d(a).reshape(-1)

            else:

                raise RuntimeError("Cannot classify outputs.")

     

            if dets.shape[1] >= 5:

                boxes, scores = dets[:, :4], dets[:, 4]

                if dets.shape[1] >= 6:

                    classes = dets[:, 5].astype(np.int32)

                else:

                    classes = labs.astype(np.int32)

                return boxes, scores, classes

     

        elif len(outs) == 1:

            x = np.array(outs[0])

            while x.ndim > 2:

                x = x.reshape(-1, x.shape[-1])

            if x.shape[1] in (6, 7):

                boxes, scores, classes = x[:, :4], x[:, 4], x[:, 5].astype(np.int32)

                return boxes, scores, classes

     

        raise RuntimeError("Unexpected model outputs layout.")

     

    print("White check mark Running object detection with TIDL acceleration... Press Ctrl+C to stop.")

     

    try:

        while True:

            start_time = time.time()

            ret, frame = cap.read()

            if not ret:

                print("Warning️ Failed to read frame")

                continue

     

            # Inference

            outs = session.run(output_names, {input_name: preprocess(frame)})

            boxes_xyxy, scores, class_ids = try_parse_outputs(outs)

     

            # Filter + NMS

            CONF_THRESHOLD, NMS_THRESHOLD = 0.3, 0.4

            keep = scores >= CONF_THRESHOLD

            boxes_xyxy, scores, class_ids = boxes_xyxy[keep], scores[keep], class_ids[keep]

     

            boxes_xywh = boxes_xyxy.copy()

            boxes_xywh[:, 2] -= boxes_xyxy[:, 0]

            boxes_xywh[:, 3] -= boxes_xyxy[:, 1]

     

            boxes_list = boxes_xywh.astype(int).tolist()

            scores_list = scores.astype(float).tolist()

            idxs = nms_numpy(boxes_list, scores_list, CONF_THRESHOLD, NMS_THRESHOLD)

     

            # Draw detections

            sx, sy = frame.shape[1] / 640.0, frame.shape[0] / 640.0

            for i in idxs:

                x, y, w, h = boxes_list[i]

                x1, y1 = int(round(x * sx)), int(round(y * sy))

                x2, y2 = int(round((x + w) * sx)), int(round((y + h) * sy))

                cls = int(class_ids[i])

                name = CLASSES[cls] if 0 <= cls < len(CLASSES) else str(cls)

                cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)

                cv2.putText(frame, f"{name} {scores_list[i]:.2f}", (x1, max(0, y1 - 5)),

                            cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

                if cls == 0:

                    print("label:", name, f"{scores_list[i]:.2f}", "x1:", x1, "y1:", y1, "x2:", x2, "y2:", y2)

     

            # Send to GStreamer sink

            data = frame.tobytes()

            buf = Gst.Buffer.new_allocate(None, len(data), None)

            buf.fill(0, data)

            buf.duration = Gst.util_uint64_scale_int(1, Gst.SECOND, 30)

            timestamp = int(time.time() * Gst.SECOND)

            buf.pts = buf.dts = timestamp

            appsrc.emit("push-buffer", buf)

     

            # Frame rate limiting

            elapsed = time.time() - start_time

            delay = max(0, (1 / 30) - elapsed)

            time.sleep(delay)

     

    except KeyboardInterrupt:

        print("Octagonal sign Interrupted. Cleaning up...")

     

    finally:

        cap.release()

        pipeline.set_state(Gst.State.NULL)

    We are doing inference using the teraterm.

  • Hi;

    Can we try to inference a yolo model, which has been compiled successfully and can be downloaded to the EVM for inference (without any modification first)?

    This can be the one to use; it has been used in our SDK/EVM demo. Or, you can pick the one you like. 

    http://software-dl.ti.com/jacinto7/esd/modelzoo/10_01_00/modelartifacts/AM68A/8bits/kd-7060_onnxrt_coco_edgeai-yolox_yolox_s_pose_ti_lite_640_20220301_model_onnx.tar.gz

    And let us know how it goes.

    Also, are you build on the full version RTOS SDK on EVM? or are you using the prebuilt version?

    Best regards

    Wen Li

  • Hi Wen,

    I have already tried compiling yolox_s_lite ( downloaded pretrained model from model_zoo ) , and then after successful compilation, we have tested it on the EVM . The result was it was running good and detecting the objects in the camera, but after training on custom data it is not running as in our case explained above.

    We are using the prebuilt RTOS version which is available online on below link:
    PROCESSOR-SDK-LINUX-SK-TDA4VM Software development kit (SDK) | TI.com

    we just downloaded the image file and then flashed in the EVM using Balena Etcher. 

    Regards,

    Chaitanya Suryawanshi

  • Hi Could you provide the steps that you have compile models (the downloaded model and re-trained model)? Also, could you provide the model configure files or model import files? So we can look into and compare the parameters.

    Thanks and regards

    Wen Li

  • Hi,

    I have trained the yolox_s_lite model on our custom dataset using the Edgeai Modelmaker repo available under Edgeai-Tensorlab using below command:

    ./run_modelmaker.sh <target_device> <config_file>  

    In config. file , I have just updated the dataset path & number of epochs. 

    It seems the model files were imported internally from edgeai-model zoo by the Edgeai-Modelmaker while training.

    And for compilation, I have used Edgeai-TIDL tools repo using TIDL tools version 10.01.00.04 using the script onnxrt_ep.py present inside edgeai-tidl-toolsexamples/osrt_python/ort/ .

    Thanks & Regards

    Chaitanya

  • HI Chaitanya,

    The engineer assigned is currently out-of-office. We appreciate your patience until they are back.

    Warm regards,

    Christina

  • Hi Chaitanya,

    I set this up to run a single frame using the yolox_s_lite_158_ir9_opset12.onnx and it appears to run on the host and EVM.  I do not know if the output I am getting is good or not and my input images may be wrong.   To test this out, I need a single frame input to try along with the input images and configuration you used.  I want to test this on the host (it should work from your initial input).  I want to then take this isolated test to the EVM.  I think the best approach to resolution is not to test the entire pipeline, just an isolated single frame run.  One that works on the host and fails on the EVM.

    Regards,

    CHris