You've got an ONNX model for human detection, and you want to use it in C#. Great choice! C# has excellent support for ONNX inference through Microsoft.ML.OnnxRuntime.
This process typically involves:
- Loading the Model: Initializing an
InferenceSession.
- Preparing Input: Loading an image, resizing, normalizing pixel values, and converting it into the tensor format expected by the model.
- Running Inference: Feeding the prepared input tensor to the model.
- Processing Output: Parsing the model's raw output to extract bounding boxes, confidence scores, and class information, and then applying post-processing like Non-Maximum Suppression (NMS).
Let's break it down.
Prerequisites
-
.NET SDK: Make sure you have a recent .NET SDK installed (e.g., .NET 6, 7, or 8).
-
NuGet Packages:
Microsoft.ML.OnnxRuntime: The core library for ONNX inference.
SixLabors.ImageSharp: A powerful, cross-platform image processing library (highly recommended over System.Drawing.Common for modern .NET).
SixLabors.ImageSharp.Drawing: For drawing bounding boxes if you want to visualize.
You can install them via NuGet Package Manager or the .NET CLI:
dotnet add package Microsoft.ML.OnnxRuntime
dotnet add package SixLabors.ImageSharp
dotnet add package SixLabors.ImageSharp.Drawing
Step 1: Inspect Your ONNX Model
Before writing code, you need to know:
- Input Name(s): What are the names of the input nodes? (e.g., "images", "input.1").
- Input Shape: What dimensions does the model expect? (e.g.,
1x3x640x640 for NCHW format: BatchSize x Channels x Height x Width).
- Input Data Type: Usually
float32.
- Normalization: Does it expect pixel values normalized to
0-1, 0-255, or some other range (e.g., mean/std deviation normalization)? This is CRUCIAL.
- Output Name(s): What are the names of the output nodes? (e.g., "output", "detections").
- Output Shape/Structure: How are the detections encoded in the output tensor? This varies a lot between models. A common format for object detection might be
1xNxK where N is the number of potential detections, and K contains [x1, y1, x2, y2, confidence, class_id] or similar.
You can inspect your ONNX model using tools like Netron. Open your .onnx file in Netron and check the input and output nodes.
Example (Common for YOLOv5/v8, RetinaNet, etc.):
- Input:
images (shape 1x3x640x640, type float32, normalized to 0-1).
- Output:
output0 (shape 1x25200x85 where 25200 is the number of anchors/proposals and 85 is [x,y,w,h,objectness_conf, class_conf_0, ..., class_conf_N-1]).
Step 2: Define Data Structures for Detections
It's helpful to have a struct to represent a detected object.
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.ColorSpaces;
using SixLabors.ImageSharp.Formats.Png;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors; // For Tensor<T>
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System;
// Define a struct to hold a single detection result
public struct Detection
{
public SixLabors.ImageSharp.RectangleF Box; // Bounding box coordinates (x, y, width, height or x1, y1, x2, y2)
public float Confidence; // Confidence score for the detection
public int ClassId; // Class ID (e.g., 0 for "person" if it's the only class, or 0 if multi-class)
public string Label; // Optional: A human-readable label for the class
}
Step 3: Implement the Human Detector Class
This class will handle loading the model, preprocessing, inference, and post-processing.
public class HumanDetector : IDisposable
{
private InferenceSession _session;
private readonly string _inputName;
private readonly int _inputWidth;
private readonly int _inputHeight;
private readonly float _confidenceThreshold;
private readonly float _nmsThreshold;
private readonly string[] _classLabels; // Array of class labels (e.g., {"person"})
// Constructor
public HumanDetector(
string modelPath,
string inputName,
int inputWidth,
int inputHeight,
float confidenceThreshold = 0.5f,
float nmsThreshold = 0.4f,
string[] classLabels = null)
{
_session = new InferenceSession(modelPath);
_inputName = inputName;
_inputWidth = inputWidth;
_inputHeight = inputHeight;
_confidenceThreshold = confidenceThreshold;
_nmsThreshold = nmsThreshold;
_classLabels = classLabels ?? new string[] { "person" }; // Default to "person"
// Optional: Verify input/output metadata
// var inputMeta = _session.InputMetadata;
// foreach (var input in inputMeta)
// {
// Console.WriteLine($"Input: {input.Key}, Type: {input.Value.ElementType}, Shape: [{string.Join(", ", input.Value.Dimensions)}]");
// }
// var outputMeta = _session.OutputMetadata;
// foreach (var output in outputMeta)
// {
// Console.WriteLine($"Output: {output.Key}, Type: {output.Value.ElementType}, Shape: [{string.Join(", ", output.Value.Dimensions)}]");
// }
}
/// <summary>
/// Detects humans in the given image.
/// </summary>
/// <param name="imagePath">Path to the image file.</param>
/// <returns>A list of detected humans (bounding boxes, confidence, class).</returns>
public async Task<List<Detection>> DetectAsync(string imagePath)
{
using (Image<Rgb24> image = await Image.LoadAsync<Rgb24>(imagePath))
{
return Detect(image);
}
}
/// <summary>
/// Detects humans in the given ImageSharp image.
/// </summary>
/// <param name="image">The ImageSharp image to process.</param>
/// <returns>A list of detected humans (bounding boxes, confidence, class).</returns>
public List<Detection> Detect(Image<Rgb24> image)
{
// 1. Preprocess Image
var inputTensor = PreprocessImage(image);
// 2. Run Inference
var container = new List<NamedOnnxValue>
{
NamedOnnxValue.CreateFromTensor(_inputName, inputTensor)
};
using (IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = _session.Run(container))
{
// 3. Post-process Output
// The exact output processing depends heavily on your model.
// This example assumes a common YOLO-like output structure:
// [1, N, 85] where N is number of detections, 85 is [x,y,w,h,obj_conf, class_conf_0...class_conf_80]
// Or maybe [1, N, 6] for simpler models [x1,y1,x2,y2,confidence,class_id]
var output = results.First().AsTensor<float>();
var detections = PostProcessOutput(output, image.Width, image.Height);
return detections;
}
}
private Tensor<float> PreprocessImage(Image<Rgb24> image)
{
// Resize image to model's input dimensions
image.Mutate(x => x.Resize(new ResizeOptions
{
Size = new Size(_inputWidth, _inputHeight),
Mode = ResizeMode.Stretch // or Pad, Crop, Min, Max based on model's training
}));
// Create a tensor for the model input
// Models often expect NCHW (Batch, Channels, Height, Width) format
// ImageSharp stores HWC (Height, Width, Channels)
var inputTensor = new DenseTensor<float>(new[] { 1, 3, _inputHeight, _inputWidth });
// Iterate over pixels and populate the tensor
for (int y = 0; y < _inputHeight; y++)
{
Span<Rgb24> row = image.GetPixelRowSpan(y);
for (int x = 0; x < _inputWidth; x++)
{
// Normalize pixel values to 0-1 and populate NCHW tensor
// If your model expects 0-255 or other normalization (e.g., mean/std dev), adjust here.
// For YOLO-like models, 0-1 is common.
inputTensor[0, 0, y, x] = row[x].R / 255.0f; // R
inputTensor[0, 1, y, x] = row[x].G / 255.0f; // G
inputTensor[0, 2, y, x] = row[x].B / 255.0f; // B
}
}
return inputTensor;
}
private List<Detection> PostProcessOutput(Tensor<float> output, int originalWidth, int originalHeight)
{
var detections = new List<Detection>();
// This is a GENERIC EXAMPLE. The exact parsing depends on your model's output format.
// For a YOLOv5/v8 model, the output shape might be [1, NumProposals, 5 + NumClasses]
// where 5 is [center_x, center_y, width, height, objectness_confidence]
// Let's assume the output is [1, Number_of_Detections, 6]
// where 6 columns are [x1, y1, x2, y2, confidence, class_id] - common for simpler models
// OR [1, Number_of_Detections, 5 + NumClasses]
// where 5 columns are [x, y, w, h, objectness_confidence] and then class scores
int numDetections = output.Dimensions[1]; // N in [1, N, K]
int elementsPerDetection = output.Dimensions[2]; // K in [1, N, K]
for (int i = 0; i < numDetections; i++)
{
float x1 = output[0, i, 0];
float y1 = output[0, i, 1];
float x2 = output[0, i, 2];
float y2 = output[0, i, 3];
float confidence = output[0, i, 4]; // Overall detection confidence
int classId = (int)output[0, i, 5]; // Class ID
// If your model outputs class probabilities (e.g., YOLOv5/v8)
// You'd need to find the max class probability and its index:
// float maxClassConf = 0;
// int detectedClassId = -1;
// for (int c = 0; c < elementsPerDetection - 5; c++) // Iterate through class scores
// {
// float classConf = output[0, i, 5 + c];
// if (classConf > maxClassConf)
// {
// maxClassConf = classConf;
// detectedClassId = c;
// }
// }
// confidence = confidence * maxClassConf; // Total confidence
// classId = detectedClassId;
if (confidence >= _confidenceThreshold && classId == 0) // Assuming "person" is class 0
{
// Convert normalized box coordinates back to original image dimensions
// If model outputs x,y,w,h (center, width, height) convert to x1,y1,x2,y2 first
// Then scale
// Example for x1,y1,x2,y2:
float scaleX = (float)originalWidth / _inputWidth;
float scaleY = (float)originalHeight / _inputHeight;
float scaledX1 = x1 * scaleX;
float scaledY1 = y1 * scaleY;
float scaledX2 = x2 * scaleX;
float scaledY2 = y2 * scaleY;
detections.Add(new Detection
{
Box = new RectangleF(scaledX1, scaledY1, scaledX2 - scaledX1, scaledY2 - scaledY1),
Confidence = confidence,
ClassId = classId,
Label = _classLabels.Length > classId ? _classLabels[classId] : $"Class {classId}"
});
}
}
// Apply Non-Maximum Suppression (NMS) to remove overlapping boxes
return ApplyNMS(detections);
}
/// <summary>
/// Applies Non-Maximum Suppression (NMS) to a list of detections.
/// This is a basic implementation. For production, consider a more optimized version.
/// </summary>
private List<Detection> ApplyNMS(List<Detection> detections)
{
if (detections == null || detections.Count == 0)
return new List<Detection>();
// Sort detections by confidence score in descending order
detections = detections.OrderByDescending(d => d.Confidence).ToList();
var selectedDetections = new List<Detection>();
var suppressed = new bool[detections.Count];
for (int i = 0; i < detections.Count; i++)
{
if (suppressed[i])
continue;
var currentDetection = detections[i];
selectedDetections.Add(currentDetection);
for (int j = i + 1; j < detections.Count; j++)
{
if (suppressed[j])
continue;
// Calculate Intersection Over Union (IOU)
float iou = CalculateIOU(currentDetection.Box, detections[j].Box);
if (iou > _nmsThreshold)
{
suppressed[j] = true;
}
}
}
return selectedDetections;
}
/// <summary>
/// Calculates the Intersection Over Union (IOU) of two bounding boxes.
/// </summary>
private float CalculateIOU(RectangleF box1, RectangleF box2)
{
// Get the coordinates of the intersection rectangle
float intersectionX1 = Math.Max(box1.X, box2.X);
float intersectionY1 = Math.Max(box1.Y, box2.Y);
float intersectionX2 = Math.Min(box1.Right, box2.Right);
float intersectionY2 = Math.Min(box1.Bottom, box2.Bottom);
// Calculate the area of intersection
float intersectionWidth = Math.Max(0, intersectionX2 - intersectionX1);
float intersectionHeight = Math.Max(0, intersectionY2 - intersectionY1);
float intersectionArea = intersectionWidth * intersectionHeight;
// Calculate the area of each bounding box
float box1Area = box1.Width * box1.Height;
float box2Area = box2.Width * box2.Height;
// Calculate the union area
float unionArea = box1Area + box2Area - intersectionArea;
// Handle division by zero
if (unionArea == 0) return 0;
return intersectionArea / unionArea;
}
public void Dispose()
{
_session?.Dispose();
_session = null;
}
}
Step 4: Visualize Results (Optional but Recommended)
You might want to draw the bounding boxes on the image to see the results.
public static class ImageExtensions
{
public static void DrawDetections(this Image<Rgb24> image, List<Detection> detections)
{
foreach (var detection in detections)
{
var color = Color.Red; // Or use different colors per class
var pen = Pens.CreateSolid(color, 2); // 2 pixels thick line
image.Mutate(x => x.Draw(pen, detection.Box));
// Draw label
string labelText = $"{detection.Label} ({detection.Confidence:P0})";
var font = SixLabors.Fonts.SystemFonts.CreateFont("Arial", 16); // Make sure Arial font is available or choose another
var textOptions = new SixLabors.ImageSharp.Drawing.TextOptions(font)
{
GraphicsOptions = new GraphicsOptions
{
Antialias = true
},
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top
};
// Calculate text size and position
var textRect = TextMeasurer.Measure(labelText, textOptions);
var textLocation = new PointF(detection.Box.X, detection.Box.Y - textRect.Height - 2); // Above the box
// Draw a background rectangle for the text for better readability
image.Mutate(x => x.Fill(color, new RectangleF(textLocation.X, textLocation.Y, textRect.Width, textRect.Height)));
image.Mutate(x => x.DrawText(textOptions, labelText, textLocation, Color.White)); // Draw text in white
}
}
}
Note: For SixLabors.Fonts, you'll need to install SixLabors.Fonts NuGet package as well.
Step 5: Put It All Together (Example Usage)
class Program
{
static async Task Main(string[] args)
{
// --- Configuration ---
string modelPath = "path/to/your/human_detection_model.onnx"; // REPLACE THIS
string inputImagePath = "path/to/your/input_image.jpg"; // REPLACE THIS
string outputImagePath = "output_image_with_detections.jpg";
// These values depend on your specific ONNX model!
// Use Netron (https://netron.app/) to inspect your model.
string inputTensorName = "images"; // Common input name
int inputWidth = 640; // Common input width
int inputHeight = 640; // Common input height
float confidenceThreshold = 0.5f; // Minimum confidence to consider a detection
float nmsThreshold = 0.4f; // NMS IoU threshold
// Labels for your model's classes. For human detection, usually just one.
// If your model detects multiple objects, list all 80 COCO classes etc.
string[] classLabels = new string[] { "person" }; // Assuming class ID 0 is "person"
// --- Initialize and Run Detector ---
using (var detector = new HumanDetector(
modelPath,
inputTensorName,
inputWidth,
inputHeight,
confidenceThreshold,
nmsThreshold,
classLabels))
{
Console.WriteLine($"Detecting humans in {inputImagePath}...");
// Load the original image again for drawing
using (Image<Rgb24> originalImage = await Image.LoadAsync<Rgb24>(inputImagePath))
{
var detections = detector.Detect(originalImage); // Pass the original image
Console.WriteLine($"Found {detections.Count} human detections.");
if (detections.Any())
{
// Draw detections on the image
originalImage.DrawDetections(detections);
// Save the image with detections
await originalImage.SaveAsync(outputImagePath);
Console.WriteLine($"Saved image with detections to {outputImagePath}");
}
else
{
Console.WriteLine("No humans detected above the confidence threshold.");
}
}
}
Console.WriteLine("Detection process completed.");
Console.ReadKey(); // Keep console open
}
}
Important Considerations and Troubleshooting:
- Model Specifics are Key: The most common pitfalls are incorrect
inputName, inputWidth, inputHeight, and especially the normalization and output parsing.
- Normalization: Some models expect pixel values in
0-255, others 0-1. Some require mean/std dev normalization (e.g., ImageNet models). You must know how your specific model was trained. If your model expects BGR channels instead of RGB, you'll need to swap channel order during preprocessing.
- Output Format: Your model's output tensor could be
[N, 6] (N detections, 6 parameters like x1,y1,x2,y2,conf,class_id), [N, 5+C] (N detections, 5 bounding box params + C class scores), or something entirely different. The PostProcessOutput method needs to be tailored exactly to your model's output. Use Netron to inspect the output node's shape and semantics.
- Coordinate System: Bounding boxes might be
x_center, y_center, width, height or x1, y1, x2, y2. They might also be normalized (0-1) or absolute pixel values.
- Non-Maximum Suppression (NMS): The provided NMS is a basic implementation. For production-level object detection, you might want a more optimized NMS implementation or consider if your ONNX model already includes it (some do).
- Performance (CPU vs. GPU):
Microsoft.ML.OnnxRuntime can leverage different execution providers. By default, it uses the CPU. If you have a powerful GPU (NVIDIA with CUDA, or a recent Windows machine with DirectML), you can configure SessionOptions for GPU acceleration:
var sessionOptions = new SessionOptions();
// For CUDA (NVIDIA GPUs):
// sessionOptions.AppendExecutionProvider_CUDA(0); // 0 is device ID
// For DirectML (Windows, DirectX 12 compatible GPUs):
// sessionOptions.AppendExecutionProvider_DML(0); // 0 is device ID
_session = new InferenceSession(modelPath, sessionOptions);
You'll need to install Microsoft.ML.OnnxRuntime.Gpu or Microsoft.ML.OnnxRuntime.DirectML NuGet packages respectively, and ensure the correct drivers/CUDA toolkit versions are installed.
- Memory Management: Ensure you dispose of
InferenceSession and DisposableNamedOnnxValue objects (using using statements).
- ImageSharp Font Warning: If
SixLabors.Fonts can't find "Arial", it will fall back to a default. For robust font handling, you might need to embed fonts or ensure common system fonts are available in your deployment environment.
By following these steps and adapting the PreprocessImage and PostProcessOutput methods to your specific model's requirements, you should be able to successfully run your human detection ONNX model in C#.