MxPrepost Usage#

MxPrepost is a high-performance pre/post-processing library for MemryX models with compatible image input and output signatures. It is designed to work alongside the MemryX Runtime callbacks and provides optimized implementations for common operations such as preprocessing/formatting, output decoding, NMS, and drawing results on frames.

The library is signature-driven and supports compatible detection, segmentation, pose estimation, and image classification models. It is intended to simplify deployment while maintaining high throughput.

Detection
Object detection with rounded boxes and confidence labels.
Segmentation
Instance segmentation with colored masks and white outlines.
Pose
Pose estimation with keypoints and skeleton connections.
Classification
Cat classification with the top five predictions.

Photo credits: child and dog and cat via Pexels (license). Annotations generated with MxPrepost.

Note

MxPrepost is designed to work hand-in-hand with MxAccl callback-based runtime flows.
For supported models, MxPrepost can run postprocessing on the CPU inside the output callback, replacing the *_post.onnx model generated by --autocrop.

For background and alternatives, see:

See also

For a runnable app using MxPrepost, see this YOLO11 tutorial.

Install MxPrepost#

Install and Verify

Important

Requirements

  • Platform: Linux (x86_64 or aarch64).

  • Runtime: MemryX Runtime / SDK 3.0+, using MxAccl. For setup, see Install Tools.

  • OpenCV: On Ubuntu/Debian, install with sudo apt install libopencv-dev.

Legacy Python bindings (SyncAccl, AsyncAccl, and MultistreamAsyncAccl) are not supported.

Install MxPrepost in the same Python environment as the MemryX SDK.

1. Verify SDK version

mx_nc --version
Optional: Upgrade SDK tools (only if SDK is below 3.0)
pip3 install --extra-index-url https://developer.memryx.com/pip_dev --upgrade memryx

2. Install MxPrepost

pip3 install --extra-index-url https://developer.memryx.com/pip_dev mxprepost
Beta channel (optional): Install the latest version from GitHub
pip3 install "git+https://github.com/memryx/MxPrepost.git"

3. Confirm installation

python3 -m pip show mxprepost

Basic Usage#

The recommended flow is:

  1. Create a MxAccl runtime object.

  2. Create one mxprepost.MxPrepost object (per model/task).

  3. In the input callback, preprocess the frame; use bgr_to_rgb=True for OpenCV capture frames.

  4. In the output callback, call postprocess(ofmaps, ori_h, ori_w) or postprocess(ofmaps, ori_frame). For classification, postprocess(ofmaps) is also supported.

  5. Optionally call draw(frame, result, bgr=True) to overlay output annotations.

import cv2
import mxprepost
from memryx import mxapi

accl = mxapi.MxAccl("model.dfp", use_model_shape=[False, False])
prepost = mxprepost.MxPrepost(accl=accl)

def input_callback(stream_id):
    ok, frame = cap.read()
    if not ok:
        return None
    return prepost.preprocess(frame, bgr_to_rgb=True) # Since opencv provides frames in BGR.

def output_callback(ofmaps, stream_id):
    result = prepost.postprocess(ofmaps, ori_h, ori_w)
    # result.boxes / result.masks / result.keypoints / result.probs
    return True

accl.connect_stream(input_callback, output_callback, stream_id=0)

The recommended flow is:

  1. Create a MxAccl runtime object.

  2. Create one MX::Prepost::MxPrepost object (per model/task) using create or create_safe. Omit the task to use "auto": create(accl, config) or create_safe(accl, config, out, err).

  3. In the input callback, convert OpenCV frames to RGB, then call preprocess and feed the result to runtime input.

  4. In the output callback, gather output feature maps as float* pointers and call postprocess(ofmaps, result, ori_h, ori_w) (or postprocess(ofmaps, result, original_frame)).

  5. Optionally call draw(frame, result, true) to overlay output annotations.

#include <memx/accl/MxAccl.h>
#include <memx/prepost/MxPrepost.h>
#include <opencv2/opencv.hpp>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>

using namespace MX::Runtime;
using namespace MX::Prepost;

// device_ids_to_use is positional here; keep default {0}.
// use_model_shape is the key setting to control input/output shape behavior.
MxAccl accl{"model.dfp", {0}, {false, false}};

YoloUserConfig cfg;  // COCO defaults
cfg.conf = 0.3f;
cfg.iou = 0.4f;

std::unique_ptr<MxPrepost> pp;
std::string err;
if (!MxPrepost::create_safe(&accl, cfg, pp, err)) {
    throw std::runtime_error("Failed to create MxPrepost: " + err);
}

int ori_w = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_WIDTH));
int ori_h = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_HEIGHT));

auto in_cb = [&](std::vector<const MX::Types::FeatureMap*>& input, int stream_id) -> bool {
    cv::Mat frame;
    if (!cap.read(frame)) {
        return false;
    }

    cv::Mat rgb;
    cv::cvtColor(frame, rgb, cv::COLOR_BGR2RGB);
    cv::Mat preprocessed = pp->preprocess(rgb);
    input[0]->set_data(reinterpret_cast<float*>(preprocessed.data));
    return true;
};

auto out_cb = [&](std::vector<const MX::Types::FeatureMap*>& output, int stream_id) -> bool {
    // Copy runtime outputs into your own float buffers, then fill:
    std::vector<float*> ofmap_ptrs;
    // ... populate ofmap_ptrs from output[i]->get_data(...)

    Result result;
    pp->postprocess(ofmap_ptrs, result, ori_h, ori_w);
    // or: pp->postprocess(ofmap_ptrs, result, original_frame);

    // Optional visualization:
    // cv::Mat annotated = original_frame.clone();
    // pp->draw(annotated, result, true);  // OpenCV BGR frame.
    return true;
};

accl.connect_stream(in_cb, out_cb, 0);
accl.start();
accl.wait();

Process Your Frames#

Preprocess Frames#

Call preprocess on the instance you created for the model. It uses the DFP’s input dimensions, applies the task’s default resize, and scales pixels by 1/255.

For BGR frames from OpenCV:

tensor = prepost.preprocess(frame, bgr_to_rgb=True)

For an image already in RGB, use prepost.preprocess(rgb_frame). The returned float32 array has the native DFP input shape.

Convert OpenCV frames to RGB, then use the default arguments:

cv::Mat rgb;
cv::cvtColor(frame, rgb, cv::COLOR_BGR2RGB);
cv::Mat tensor = pp->preprocess(rgb);

The returned cv::Mat contains float32 HWC pixels.

Detection, segmentation, and pose use letterbox; classification uses resize and center crop. Input images can contain uint8 or float32 pixels. Use the defaults unless your model was trained with a different preprocessing recipe.

Custom normalization

Match scale, mean, and std to your model’s training recipe. Normalization is (pixel * scale - mean) / std; means and standard deviations follow the final channel order. Use scale=1.0 when the input is already scaled. These overrides apply only to the current call.

The following values are an example for a classifier trained with RGB mean/std normalization:

tensor = prepost.preprocess(
    frame,
    bgr_to_rgb=True,
    mean=(0.485, 0.456, 0.406),
    std=(0.229, 0.224, 0.225),
)
#include <optional>

cv::Mat tensor = pp->preprocess(
    frame, std::nullopt, std::nullopt, true, 1.0 / 255.0,
    {0.485f, 0.456f, 0.406f},
    {0.229f, 0.224f, 0.225f});

The two std::nullopt arguments keep the default resize size and task geometry. true converts BGR to RGB before normalization.

resize_size accepts an integer (shorter side, preserving aspect ratio) or (height, width) (exact size). None keeps the default resize. A custom size applies only when center cropping is enabled. The resized image must be large enough for the model’s crop:

tensor = prepost.preprocess(frame, resize_size=256, center_crop=True, bgr_to_rgb=True)

C++ accepts an integer or std::array<int, 2>{256, 320}.

See MxPrepost API for all preprocessing parameters.

Postprocess Results#

Call postprocess with the model outputs and the original image dimensions (height, then width) to obtain a Result.

result = prepost.postprocess(ofmaps, ori_h, ori_w)
# Or: result = prepost.postprocess(ofmaps, original_image)
Result result;
pp->postprocess(ofmap_ptrs, result, ori_h, ori_w);
// Or: pp->postprocess(ofmap_ptrs, result, original_image);

Classification also supports prepost.postprocess(ofmaps) in Python and pp->postprocess(ofmap_ptrs, result) in C++ without image dimensions. The populated result fields depend on the task:

Task

Result fields

Behavior

Detection

boxes

Decodes, filters, and scales boxes to the original image; applies NMS when enabled.

Segmentation

boxes, masks

Adds mask polygons in original-image coordinates to detection results.

Pose

boxes, keypoints

Adds keypoint coordinates and confidence values for each detected box.

Classification

probs

Requires raw logits. Applies sigmoid (one class) or softmax (multiple classes), filters by valid_classes, and ranks probabilities with top-1 and top-5 predictions.

Detection, segmentation, and pose use conf and max_dets; classification uses neither and does not apply NMS.

Access result fields by task
# Access outputs (depending on task)
# ---------------------------
# Detection (Bounding Boxes)
# ---------------------------
if result.boxes is not None:
    for box in result.boxes:
        print("xyxy:", box.xyxy)        # [x1, y1, x2, y2]
        print("xywh:", box.xywh)        # [x_center, y_center, w, h]
        print("conf:", box.conf)        # confidence score
        print("cls_id:", box.cls_id)    # class index
        print("cls_name:", box.cls_name)# class label string
        print("----")

# ---------------------------
# Segmentation (Masks)
# ---------------------------
if result.masks is not None:
    for mask in result.masks:
        # mask is a polygon (list of Point2f), not a binary HxW array
        pts = [(p.x, p.y) for p in mask.xys]
        print("mask cls_id:", int(mask.cls_id))
        print("num polygon points:", len(pts))
        if pts:
            print("first 5 points:", pts[:5])
        print("----")

# ---------------------------
# Pose Estimation (Keypoints)
# ---------------------------
if result.keypoints is not None:
    for det_id, kps in enumerate(result.keypoints):
        print(f"detection {det_id} keypoints:", len(kps))
        # each kp has kp.xy (Point2f) and kp.conf
        for kp_id, kp in enumerate(kps):
            print(f"  kp[{kp_id}] = (x={kp.xy.x:.2f}, y={kp.xy.y:.2f}, conf={kp.conf:.3f})")
        print("----")

# ---------------------------
# Classification (Probabilities)
# ---------------------------
if result.probs.top1 >= 0:
    print("top1:", result.probs.top1, result.probs.top1_name, result.probs.top1conf)
    for rank, cls_id in enumerate(result.probs.top5):
        print(
            f"top{rank + 1}:",
            cls_id,
            result.probs.cls_name[rank],
            result.probs.scores[rank],
        )
// Detection (Bounding Boxes)
if (!result.boxes.empty()) {
    for (const auto& box : result.boxes) {
        // box.xyxy, box.xywh, box.conf, box.cls_id, box.cls_name
    }
}

// Segmentation (Masks as polygons)
if (!result.masks.empty()) {
    for (const auto& mask : result.masks) {
        // mask.xys (vector<Point2f>), mask.cls_id, mask.cls_name
    }
}

// Pose Estimation (Keypoints)
if (!result.keypoints.empty()) {
    for (const auto& kps : result.keypoints) {
        for (const auto& kp : kps) {
            // kp.xy.x, kp.xy.y, kp.conf
        }
    }
}

// Classification
if (result.probs.top1 >= 0) {
    // result.probs.top1, result.probs.top1_name, result.probs.top1conf
    // result.probs.top5, result.probs.cls_name, result.probs.scores
}

Draw Results#

draw(image, result) defaults to RGB. For OpenCV BGR frames, pass bgr=True (C++: true). Drawing preserves channel order.

C++ modifies the image in place. Python returns an annotated copy and also modifies the input when its storage is shared (contiguous arrays).

Configure Your Model#

See the MxPrepost API reference for the full list of options. The most common constructor arguments are listed below.

Argument

Type

Description

accl (required)

mxapi.MxAccl

mxapi.MxAccl runtime object used by MxPrepost for shape/task context.

task

str

Task selector. "auto" by default, or explicitly "detect", "segment", "pose", or "cls".

conf

float

Confidence threshold (default: 0.3).

iou

float

IoU threshold for NMS (default: 0.4).

Additional options

Argument

Type

Description

classmap_path

str

Path to a text file containing class labels (one label per line).

custom_class_labels

list[str]

Override class labels directly in code.

valid_classes

list[int]

Keep only selected class IDs.

class_agnostic

bool

Enable class-agnostic NMS when True.

fast_sigmoid

bool

Use approximate sigmoid for slightly faster processing.

multi_label

bool

If True, return one detection per class above threshold per anchor. If False, keep only the best class per anchor.

max_dets

int

Maximum number of boxes returned after NMS.

model_id

int

Select model when multiple models are compiled into one DFP.

override_layer_mapping

dict[int, list[str]]

Advanced override for output layer-to-port mapping.

apply_nms

bool | None

Override inferred NMS behavior when needed.

For Custom Models#

Use these arguments to align MxPrepost with your custom model and dataset:

  • classmap_path: load class labels from a text file (one label per line).

  • custom_class_labels: provide labels directly in code.

  • valid_classes: return only selected class IDs.

  • model_id: choose the correct model when a DFP contains multiple models.

Note

If both classmap_path and custom_class_labels are provided, MxPrepost raises an exception and requires you to specify only one.

For custom models, check that the number of class labels matches the model outputs. With the correct class count and model ID, automatic mapping usually works without override_layer_mapping.

prepost = mxprepost.MxPrepost(
    accl=accl,
    custom_class_labels=["person", "helmet", "vest"],
    valid_classes=[0, 1],
    model_id=0,
)
YoloUserConfig config;
config.custom_class_labels = {"person", "helmet", "vest"};
config.valid_classes = {0, 1};
config.model_id = 0;
std::unique_ptr<MxPrepost> pp{MxPrepost::create(&accl, config)};

Runtime Thresholds#

The confidence and IoU thresholds can be changed after construction without recreating the MxPrepost instance. New values apply to subsequent postprocess calls.

prepost.set_conf(0.25)
prepost.set_iou(0.45)
print(prepost.get_conf(), prepost.get_iou())
pp->set_conf(0.25f);
pp->set_iou(0.45f);
float confidence = pp->get_conf();
float iou = pp->get_iou();

Supported Models#

MxPrepost detects the task, ports, and decoding profile from the outputs of a model compiled for MemryX.

Capability

Compatible output signature

Detect

YOLO-style box and class heads; direct coordinates or DFL; flexible stride count.

Segment

Detection heads plus mask coefficients and mask prototypes.

Pose

Detection heads plus keypoint coordinates and confidence.

Classify

One output containing exactly num_classes raw logits, such as (num_classes,) or (1, 1, 1, num_classes); postprocess uses sigmoid (one class) or softmax (multiple classes).

This design supports tested MemryX-compilable models as well as compatible architectures beyond one framework or model family, including YOLOv7 and models with equivalent signatures.

Warning

OBB and YOLOE layouts are not currently supported.

Note

Matching shapes cannot prove matching tensor semantics. When an ambiguous layout still matches a supported signature, MxPrepost falls back to the default port order and prints a warning. Use override_layer_mapping when that order does not match the model. Layouts that cannot be resolved safely are rejected.

MxPrepost works with custom class labels and uses the compiled input shape, so it is not limited to 640x640 inputs.

Troubleshooting#

What if auto layer detection fails?

Use this only when auto layer detection fails and your task, class count, and model_id are already correct.

  1. Inspect model output layer names and shapes:

dfp_inspect path_dfp_file

or using C++ code:

#include <iostream>
#include <memx/accl/MxAccl.h>

MX::Runtime::MxAccl accl{"model.dfp", {0}, {false, false}};
auto info = accl.get_model_info(0);  // use your model_id

for (size_t i = 0; i < info.output_layer_names.size(); ++i) {
    std::cout << i << " | "
              << info.output_layer_names[i] << " | "
              << info.out_featuremap_shapes[i].to_string() << "\n";
}
  1. Build override_layer_mapping with those exact layer names:

  • Detection: each stride maps to [coord_layer_name, conf_layer_name].

  • Segmentation: each stride maps to [coord_layer_name, conf_layer_name, mask_coef_layer_name] plus 0: [mask_proto_layer_name].

  • Pose: each stride maps to [coord_layer_name, conf_layer_name, keypoint_layer_name].

  1. Include all required stride entries (commonly 8, 16, 32):

# Example: explicit mapping for detection
prepost = mxprepost.MxPrepost(
    accl=accl,
    task="detect",
    override_layer_mapping={
        8:  ["/model.22/cv2.0/cv2.0.2/Conv_output_0", "/model.22/cv3.0/cv3.0.2/Conv_output_0"],
        16: ["/model.22/cv2.1/cv2.1.2/Conv_output_0", "/model.22/cv3.1/cv3.1.2/Conv_output_0"],
        32: ["/model.22/cv2.2/cv2.2.2/Conv_output_0", "/model.22/cv3.2/cv3.2.2/Conv_output_0"],
    },
)

# Segmentation additionally needs global mask proto:
# override_layer_mapping = {
#     8:  ["coord_s8",  "conf_s8",  "maskcoef_s8"],
#     16: ["coord_s16", "conf_s16", "maskcoef_s16"],
#     32: ["coord_s32", "conf_s32", "maskcoef_s32"],
#     0:  ["mask_proto_global"],
# }

See also