MxPrepost API#
For installation and usage examples, see MxPrepost Usage.
MxPrepost#
- class MxPrepost#
- __init__(self: mxprepost.MxPrepost, accl: object, task: str | None = None, conf: SupportsFloat | SupportsIndex = 0.3, iou: SupportsFloat | SupportsIndex = 0.4, max_dets: SupportsInt | SupportsIndex = 300, classmap_path: str = '', custom_class_labels: collections.abc.Sequence[str] = [], valid_classes: collections.abc.Sequence[SupportsInt | SupportsIndex] = [], class_agnostic: bool = False, fast_sigmoid: bool = False, multi_label: bool = False, model_id: SupportsInt | SupportsIndex = 0, override_layer_mapping: dict = {}, apply_nms: bool | None = None) None#
Create MxPrepost object for a specific task.
- Parameters:
- acclMxAccl
The MemryX accelerator object to use for post-processing. This should be an instance of the MxAccl class from the Python bindings.
- taskstr, optional
Post-processing task: “detect”, “segment”, “pose”, or “cls”. When omitted or set to “auto”, the task is detected from model outputs.
- conffloat, optional
Confidence score threshold for post-processing. Default is 0.3.
- ioufloat, optional
Intersection over Union (IoU) threshold for post-processing. Default is 0.4.
- classmap_pathstr, optional
Path to a file containing class names, with one class name per line. If not provided, COCO classes will be used by default for YOLO tasks and ImageNet classes for classification.
- custom_class_labelslist of str, optional
List of custom class labels to use instead of loading from a file. If both classmap_path and custom_class_labels are provided, custom_class_labels will take precedence.
- valid_classeslist of int, optional
List of class IDs to consider during post-processing. If not provided, all classes will be considered.
- max_detsint, optional
Maximum number of detections to keep after NMS. Default is 300.
- class_agnosticbool, optional
Use class-agnostic NMS if True. Default is False.
- fast_sigmoidbool, optional
Use fast sigmoid approximation if True. Default is False.
- multi_labelbool, optional
If True, returns one detection per class above threshold per anchor. If False, returns only the best class per anchor. Default is False.
- model_idint, optional
The ID of the model to be used from the MemryX accelerator object. Default is 0. Useful when multiple models are mapped in the same DFP.
- override_layer_mappingdict, optional
A dictionary mapping stride values to lists of layer names for coord, conf, mask_coef, and keypoint ports (if applicable). This overrides automatic layer mapping for detect, segment, and pose models. Classification does not support layer overrides. The keys should be stride values (e.g., 8, 16, 32) and the values should be lists of layer names corresponding to that stride. For example: {16: [“coord_layer_name”, “conf_layer_name”], 32: [“coord_layer_name”, “conf_layer_name”]}. Use stride=0 for global feature maps such as mask_proto for segmentation. Default is an empty dict, which means auto-mapping will be used.
- apply_nmsbool, optional
Force NMS on or off. When omitted, NMS behavior is inferred from the model.
Notes
After construction, use
set_conf(value)andset_iou(value)to change the thresholds without recreating theMxPrepostinstance. The new values apply to subsequentpostprocesscalls. Useget_conf()andget_iou()to read the current values. Both thresholds must be in the inclusive range [0.0, 1.0].Examples
prepost.set_conf(0.25) prepost.set_iou(0.45) print(prepost.get_conf(), prepost.get_iou())
- preprocess(self: mxprepost.MxPrepost, input_image: numpy.ndarray, *, resize_size: SupportsInt | SupportsIndex | Annotated[collections.abc.Sequence[SupportsInt | SupportsIndex], 'FixedSize(2)'] | None = None, center_crop: bool | None = None, bgr_to_rgb: bool = False, scale: SupportsFloat | SupportsIndex = 0.00392156862745098, mean: Annotated[collections.abc.Sequence[SupportsFloat | SupportsIndex], 'FixedSize(3)'] = [0.0, 0.0, 0.0], std: Annotated[collections.abc.Sequence[SupportsFloat | SupportsIndex], 'FixedSize(3)'] = [1.0, 1.0, 1.0]) numpy.ndarray#
Resize and normalize an image using the compiled model dimensions. Options apply only to this call.
- Parameters:
- input_imagenumpy.ndarray
Non-empty HWC uint8 or float32 image, RGB by default.
- resize_sizeint, tuple of two ints, or None, default None
Integer: shorter side, preserving aspect ratio. (height, width): exact size. None keeps defaults. Center crop only; positive sizes must fit the model crop.
- center_cropbool or None, default None
None selects letterbox for detect/segment/pose and center crop for classification. False uses letterbox with centered padding 114. True resizes the short edge for square targets and resizes directly for non-square targets, then center crops. Resize is antialiased bilinear for uint8 center crop and OpenCV linear otherwise. Spatial postprocessing assumes letterbox; center crop needs custom coordinate mapping.
- bgr_to_rgbbool, default False
Convert BGR input to RGB before normalization.
- scalefloat, default 1/255
Pixel multiplier in (pixel * scale - mean) / std. Input range is not inferred; use 1.0 for already-scaled input.
- meansequence of 3 floats, default (0, 0, 0)
Channel means subtracted after scaling, in final channel order.
- stdsequence of 3 floats, default (1, 1, 1)
Positive channel standard deviations used to divide after mean subtraction, in final channel order.
- Returns:
- numpy.ndarray
Float32 image reshaped to the native DFP input shape.
- postprocess(ofmaps) Result#
Classification only. No original image or dimensions required.
- Parameters:
ofmaps (list[numpy.ndarray]) – Model output feature maps, in output-port order.
- Returns:
Classification predictions in
Result.probs.- Return type:
See Behavior by task.
- postprocess(ofmaps, ori_h, ori_w) Result
All tasks. Scales spatial predictions using the original image dimensions, passed as height, then width. Classification ignores these dimensions.
- Parameters:
ofmaps (list[numpy.ndarray]) – Model output feature maps, in output-port order.
ori_h (int) – Original image height before preprocessing.
ori_w (int) – Original image width before preprocessing.
- Returns:
Task-specific predictions.
- Return type:
See Behavior by task.
- postprocess(ofmaps, original_image) Result
All tasks. Uses the original image’s dimensions to scale spatial predictions. Classification does not use the image dimensions.
- Parameters:
ofmaps (list[numpy.ndarray]) – Model output feature maps, in output-port order.
original_image (numpy.ndarray) – Original image before preprocessing.
- Returns:
Task-specific predictions.
- Return type:
See Behavior by task.
- set_conf(self: mxprepost.MxPrepost, conf: SupportsFloat | SupportsIndex) None#
Set the confidence threshold for subsequent postprocess calls.
This may be called after construction without recreating the
MxPrepostinstance. The value must be between 0.0 and 1.0, inclusive. Higher values keep fewer, more-confident detections.- Parameters:
- conffloat
Confidence threshold in the inclusive range [0.0, 1.0].
- Raises:
- MxError
If
confis outside [0.0, 1.0].
- get_conf(self: mxprepost.MxPrepost) float#
Get the current confidence threshold.
- Returns:
- float
Confidence threshold used by subsequent postprocess calls.
- set_iou(self: mxprepost.MxPrepost, iou: SupportsFloat | SupportsIndex) None#
Set the IoU threshold for subsequent postprocess calls.
The threshold is used for non-maximum suppression (NMS). This may be called after construction without recreating the
MxPrepostinstance. The value must be between 0.0 and 1.0, inclusive. Lower values suppress overlapping detections more aggressively.- Parameters:
- ioufloat
Intersection over Union threshold in the inclusive range [0.0, 1.0].
- Raises:
- MxError
If
iouis outside [0.0, 1.0].
- get_iou(self: mxprepost.MxPrepost) float#
Get the current IoU threshold used for NMS.
- Returns:
- float
IoU threshold used by subsequent postprocess calls.
- draw(self: mxprepost.MxPrepost, image: numpy.ndarray, result: mxprepost.Result, bgr: bool = False) numpy.ndarray#
Draws the post-processing results on the input image.
- Parameters:
- imagenp.ndarray
The input image as an HWC numpy array, RGB by default. The input is modified in place when its storage is shared.
- resultResult
The post-processing result containing boxes, masks, keypoints, classification probabilities, etc., to be drawn on the image.
- bgrbool, optional
False (default) for RGB; True for BGR images such as OpenCV camera frames. Drawing preserves the input channel order without converting the image.
- Returns:
- np.ndarray
A copy of the annotated image in the same channel order as the input.
-
class MX::Prepost::MxPrepost#
Create an instance with
createorcreate_safe. Task detection is automatic when you omittask. Pass aYoloUserConfigto customize thresholds, class labels, or decoding options;create(accl)uses the default configuration.Use
create(accl, config)orcreate_safe(accl, config, out, err)for automatic detection with a custom configuration. To select a task, pass it before the configuration, for examplecreate(accl, "detect", config).With an existing
MxAccl accl:#include <memx/prepost/MxPrepost.h> #include <memory> using namespace MX::Prepost; YoloUserConfig config; config.conf = 0.25f; config.iou = 0.45f; std::unique_ptr<MxPrepost> prepost{ MxPrepost::create(&accl, config)};
Create an instance
createreturns a caller-owned pointer and throws on failure.create_safefills aunique_ptrand an error message, returningfalseon failure.-
static MxPrepost *MX::Prepost::MxPrepost::create(MX::Runtime::MxAcclBase *accl, const std::string &task = "auto", const YoloUserConfig &config = {})#
Factory function to create a pre/post-processing object for the given task.
- Parameters:
accl – Accelerator runtime object: MxAccl or MxAcclMT
task – Task string: “auto” (default), “detect”, “segment”, “pose”, or “cls”. model outputs determine the task, ports, and postprocessor.
config – User config.
- Throws:
UnsupportedTaskError – if task is not recognized.
- Returns:
Raw pointer owned by caller (or wrap into std::unique_ptr).
-
static inline MxPrepost *MX::Prepost::MxPrepost::create(MX::Runtime::MxAcclBase *accl, const YoloUserConfig &config)#
Create with a custom config and automatic task detection.
-
static bool MX::Prepost::MxPrepost::create_safe(MX::Runtime::MxAcclBase *accl, const std::string &task, const YoloUserConfig &config, std::unique_ptr<MxPrepost> &out, std::string &err) noexcept#
No-throw factory function to create a pre/post-processing object for the given task.
- Parameters:
accl – Accelerator runtime object: MxAccl or MxAcclMT
task – Task string: “auto”, “detect”, “segment”, “pose”, or “cls”.
config – User config.
out – Output unique_ptr to hold the created MxPrepost object if successful.
err – Output string to hold error message if creation fails.
- Returns:
true if creation is successful, false otherwise. If false is returned, ‘out’ will be set to nullptr and ‘err’ will contain the error message.
-
static inline bool MX::Prepost::MxPrepost::create_safe(MX::Runtime::MxAcclBase *accl, const YoloUserConfig &config, std::unique_ptr<MxPrepost> &out, std::string &err) noexcept#
No-throw factory with automatic task detection.
-
struct MX::Prepost::YoloUserConfig#
Configuration for create / create_safe
These are the fields accepted by the
configargument ofcreateandcreate_safe. They are read when the instance is created; changing this struct later does not update the instance.Confidence and detection limits
-
float MX::Prepost::YoloUserConfig::conf = 0.3f
Confidence threshold for filtering detections. Default 0.3.
-
float MX::Prepost::YoloUserConfig::iou = 0.4f
IoU threshold for NMS. Default 0.4.
-
int MX::Prepost::YoloUserConfig::max_dets = 300
Maximum number of detections to keep after NMS. Default 300.
Class labels and filtering
-
std::string MX::Prepost::YoloUserConfig::classmap_path = ""
Path to a .txt file containing custom class names (one per line). If this and custom_class_labels are not set, defaults to COCO dataset.
-
std::vector<std::string> MX::Prepost::YoloUserConfig::custom_class_labels = {}
List of custom class labels in order of their IDs. If this and classmap_path are not set, defaults to COCO dataset.
-
std::unordered_set<int> MX::Prepost::YoloUserConfig::valid_classes
List of valid class IDs to consider during post-processing. If empty, all classes will be considered.
Advanced options
-
bool MX::Prepost::YoloUserConfig::class_agnostic = false
Whether to use class-agnostic NMS (true) or class-aware NMS (false). Default is false (class-aware).
-
bool MX::Prepost::YoloUserConfig::fast_sigmoid = false
Whether to use fast sigmoid approximation for confidence scores. Default is false (use standard sigmoid).
-
bool MX::Prepost::YoloUserConfig::multi_label = false
Whether to emit one detection per class above threshold (true) or only best class per anchor (false). Default false.
-
std::optional<bool> MX::Prepost::YoloUserConfig::apply_nms = std::nullopt
Force NMS on/off. When unset, NMS behavior is inferred from the model.
-
int MX::Prepost::YoloUserConfig::model_id = 0
The ID of the model within the running DFP to connect to. Default is 0. Useful when multiple models are mapped in the same DFP and you want to specify which one to use for post-processing.
-
std::map<int, std::vector<std::string>> MX::Prepost::YoloUserConfig::override_layer_mapping
Optional mapping of stride values to lists of layer names for coord, conf, mask_coef, and keypoint ports (if applicable). This is used to override the automatic layer mapping based on output shapes, in case it fails. The keys should be stride values (e.g., 8, 16, 32) and the values should be lists of layer names corresponding to that stride. Use stride=0 for global feature maps such as mask_proto for segmentation. Default is an empty map, which means auto-mapping will be used.
-
float MX::Prepost::YoloUserConfig::conf = 0.3f
Process images
-
virtual cv::Mat MX::Prepost::MxPrepost::preprocess(const cv::Mat &input, std::optional<ResizeSize> resize_size = std::nullopt, std::optional<bool> center_crop = std::nullopt, bool bgr_to_rgb = false, double scale = 1.0 / 255.0, const std::array<float, 3> &mean = {0.f, 0.f, 0.f}, const std::array<float, 3> &std = {1.f, 1.f, 1.f}) = 0#
Resize and normalize an image using the compiled model dimensions. Options apply only to this call.
- Parameters:
input – Non-empty HWC uint8 or float32 image, RGB by default.
resize_size – Short edge (preserves aspect ratio) or exact {height, width}. Center crop only; positive sizes must fit the model crop. nullopt keeps defaults.
center_crop – nullopt selects letterbox for detect/segment/pose and center crop for classification. False uses letterbox with centered padding 114. True resizes the short edge for square targets and resizes directly for non-square targets, then center crops. Resize is antialiased bilinear for uint8 center crop and OpenCV linear otherwise. Spatial postprocessing assumes letterbox; center crop needs custom coordinate mapping.
bgr_to_rgb – Convert BGR to RGB before normalization.
scale – Pixel multiplier in (pixel * scale - mean) / std. Input range is not inferred; use 1.0 for already-scaled input.
mean – Three channel means subtracted after scaling, in final channel order.
std – Three positive channel standard deviations used to divide after mean subtraction, in final channel order.
bgr_to_rgb – Convert BGR input to RGB before normalization.
- Returns:
Float32 HWC image.
-
virtual void MX::Prepost::MxPrepost::postprocess(const std::vector<float*> &outputs, Result &result) = 0#
Postprocess classification outputs without original image dimensions. Detection, segmentation, and pose require an image or dimensions and throw here.
- Parameters:
outputs – Model output float arrays, in output-port order.
result – Classification predictions in Result::probs.
-
virtual void MX::Prepost::MxPrepost::postprocess(const std::vector<float*> &outputs, Result &result, int ori_h, int ori_w) = 0#
Postprocess outputs using original image dimensions. Supports all tasks. Scales spatial predictions to the original image. Pass height before width. Classification ignores these dimensions.
- Parameters:
outputs – Model output float arrays, in output-port order.
result – Task-specific predictions; see Result.
ori_h – Original image height before preprocessing.
ori_w – Original image width before preprocessing.
-
virtual void MX::Prepost::MxPrepost::postprocess(const std::vector<float*> &outputs, Result &result, const cv::Mat &original_image) = 0#
Postprocess outputs using the original image. Supports all tasks. Uses only the image dimensions to scale spatial predictions. Classification does not use the image dimensions.
- Parameters:
outputs – Model output float arrays, in output-port order.
result – Task-specific predictions; see Result.
original_image – Original image before preprocessing; only its dimensions are used.
-
virtual void MX::Prepost::MxPrepost::draw(cv::Mat &image, const Result &result, bool bgr = false) = 0#
Draw the post-processing Result data on the given image (e.g., draw detected boxes, masks, keypoints, etc.).
- Parameters:
image – The image (RGB by default) on which to draw the post-processing results. This will be modified in-place.
result – The Result object containing post-processing results to be drawn on the image.
bgr – Set true for BGR images, such as OpenCV camera frames. Defaults to false (RGB). Drawing preserves the image’s channel order; no image conversion is performed.
Adjust thresholds at runtime
Use these setters to change thresholds after creation.
-
virtual void MX::Prepost::MxPrepost::set_conf(float conf)#
Set the confidence threshold used by subsequent postprocess calls.
This can be changed after construction without recreating the MxPrepost instance. The value must be in the inclusive range [0.0, 1.0]. A higher value keeps fewer, more-confident detections.
- Parameters:
conf – Confidence threshold.
- Throws:
MxError – if conf is outside [0.0, 1.0].
-
virtual float MX::Prepost::MxPrepost::get_conf() const#
Get the current confidence threshold.
- Returns:
Confidence threshold used by subsequent postprocess calls.
-
virtual void MX::Prepost::MxPrepost::set_iou(float iou)#
Set the IoU threshold used by subsequent postprocess calls for non-maximum suppression (NMS).
This can be changed after construction without recreating the MxPrepost instance. The value must be in the inclusive range [0.0, 1.0]. A lower value suppresses overlapping detections more aggressively.
- Parameters:
iou – Intersection over Union threshold for NMS.
- Throws:
MxError – if iou is outside [0.0, 1.0].
-
static MxPrepost *MX::Prepost::MxPrepost::create(MX::Runtime::MxAcclBase *accl, const std::string &task = "auto", const YoloUserConfig &config = {})#
Result#
An inference returns a Result object. Fields for tasks that do not
apply remain empty.
- class Result#
Result class for post-processing output, containing detected bounding boxes, masks, and/or keypoints.
- Attributes:
- boxesList[Box]
List of detected bounding boxes. Each box is represented as a Box object containing coordinates, confidence score, class ID, and class name.
- masksList[Mask]
List of detected masks. Each mask is represented as a Mask object containing the polygon coordinates, class ID, and class name.
- keypointsList[Keypoint]
List of detected keypoints. Each keypoint is represented as a Keypoint object containing the (x, y) coordinates and confidence score.
- probsClassificationResult
Classification probabilities and top-k results.
- property boxes#
- property keypoints#
- property masks#
- property probs#
-
struct Result#
Task-specific postprocessing predictions for a single input image. Fields for tasks that do not apply remain empty.
Detection decodes, filters, and scales boxes to the original image, applying NMS when enabled. Segmentation also returns mask polygons in original-image coordinates. Pose also returns keypoint coordinates and confidence values for each detected box. Classification returns probabilities and ranked predictions in probs. Detection, segmentation, and pose use conf and max_dets; classification uses neither and does not apply NMS.
Public Members
-
std::vector<BBox> boxes#
List of detected bounding boxes in the input image, each represented as a BBox struct.
-
std::vector<Mask> masks#
List of detected segmentation masks in the input image, each represented as a Mask struct.
-
std::vector<std::vector<Keypoint>> keypoints#
List of detected keypoints for pose estimation in the input image. Each element in the outer vector corresponds to a detected instance (e.g., a person), and contains a vector of Keypoint structs representing the keypoints for that instance.
-
ClassificationResult probs#
Classification probabilities and top-k results.
-
std::vector<BBox> boxes#
ClassificationResult#
For classification, Result.probs is a
ClassificationResult. It contains the class probabilities and the
highest-ranked predictions.
- class ClassificationResult#
ClassificationResult class for grouped classification probabilities.
- Attributes:
- scoresList[float]
Probabilities sorted from highest to lowest after applying valid_classes.
- cls_idList[int]
Class IDs aligned with scores.
- cls_nameList[str]
Class names aligned with scores.
- top1int
Highest-probability class ID, or -1 when no class is available.
- top1_namestr
Class name for top1.
- top1conffloat
Probability for top1.
- top5List[int]
Up to five highest-probability class IDs.
- property cls_id#
- property cls_name#
- property scores#
- property top1#
- property top1_name#
- property top1conf#
- property top5#
-
struct ClassificationResult#
Struct representing classification probabilities and top-k class results. Scores are computed from raw logits using sigmoid for one class or softmax across all classes for multiple classes, before valid_classes filtering.
Public Members
-
std::vector<float> scores#
Probabilities sorted from highest to lowest after applying valid_classes.
-
std::vector<int> cls_id#
Class IDs aligned with scores.
-
std::vector<std::string> cls_name#
Class names aligned with scores.
-
int top1 = -1#
Highest-probability class ID, or -1 when no class is available.
-
std::string top1_name#
Class name for top1.
-
float top1conf = 0.0f#
Probability for top1.
-
std::vector<int> top5#
Up to five highest-probability class IDs.
-
std::vector<float> scores#
Box#
The Python binding calls this type Box; the C++ API calls the same
concept BBox.
- class Box#
Box class for representing detected bounding boxes.
- Attributes:
- xywhTuple[float, float, float, float]
Bounding box represented as (x_center, y_center, width, height).
- xyxyTuple[float, float, float, float]
Bounding box represented as (x_min, y_min, x_max, y_max).
- conffloat
Confidence score of the detected bounding box.
- cls_idint
Class ID of the detected object.
- cls_namestr
Class name as string of the detected object.
- property cls_id#
- property cls_name#
- property conf#
- property xywh#
- property xyxy#
-
struct BBox#
Struct representing a bounding box detection result, with multiple representations (xyxy and xywh) for convenience.
Mask#
- class Mask#
Mask class for representing segmentation masks.
- Attributes:
- xysList[Point2f]
List of (x, y) coordinates representing the polygon of the detected mask. Each coordinate is a Point2f object.
- cls_idint
Class ID of the detected mask.
- cls_namestr
Class name as string of the detected mask.
- property cls_id#
- property cls_name#
- property xys#
-
struct Mask#
Struct representing a detected segmentation mask, defined by a polygon of (x, y) coordinates and associated class information.
Keypoint#
Point2f#
Exceptions#
- exception MxError#
- exception TaskDetectionError#
- exception TaskMismatchError#
- exception UnsupportedTaskError#
