< Summary

Information
Class: InferenceEngine.Examples.FaceDetectionEngine
Assembly: InferenceEngine.Examples
File(s): /home/runner/work/inference-engine-lib/inference-engine-lib/InferenceEngine.Examples/FaceDetectionEngine.cs
Line coverage
38%
Covered lines: 51
Uncovered lines: 83
Coverable lines: 134
Total lines: 279
Line coverage: 38%
Branch coverage
25%
Covered branches: 16
Total branches: 62
Branch coverage: 25.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
.ctor(...)100%11100%
get_ModelName()100%210%
PreProcessWithContext(...)0%272160%
PostProcessWithContext(...)0%812280%
get_ScaleX()100%210%
get_ScaleY()100%210%
get_SourceWidth()100%210%
get_SourceHeight()100%210%
get_Label()100%11100%
get_Confidence()100%11100%
get_X()100%11100%
get_Y()100%11100%
get_Width()100%11100%
get_Height()100%11100%
InferBoxCoordSpace(...)83.33%6685.71%
DecodeToSourcePixels(...)100%44100%
ApplyNMS(...)100%66100%
CalculateIoU(...)50%22100%

File(s)

/home/runner/work/inference-engine-lib/inference-engine-lib/InferenceEngine.Examples/FaceDetectionEngine.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Threading.Tasks;
 5using Microsoft.Extensions.Logging;
 6using Microsoft.ML.OnnxRuntime;
 7using Microsoft.ML.OnnxRuntime.Tensors;
 8using SkiaSharp;
 9using InferenceEngine.Core;
 10
 11namespace InferenceEngine.Examples
 12{
 13    /// <summary>
 14    /// Specialized Inference Engine for Face/Object Detection (YOLOv8 based).
 15    /// Adapts the generic BaseInferenceEngine to handle Computer Vision specific tasks
 16    /// like image resizing, aspect ratio scaling, and coordinate mapping.
 17    /// </summary>
 18    public class FaceDetectionEngine : BaseInferenceEngine<byte[], List<FaceDetectionEngine.PredictionResult>>
 19    {
 20        // Configuration
 21        private const float ConfidenceThreshold = 0.45f;
 22        private const float IouThreshold = 0.5f;
 23
 24        // Diagnostics
 025        private static readonly bool BboxDiagEnabled =
 026            string.Equals(Environment.GetEnvironmentVariable("INFERENCEAPP_BBOX_DIAG"), "1", StringComparison.OrdinalIgn
 27        private const float CoordSpaceToleranceMargin = 1.15f;
 28
 629        private readonly string[] _labels =
 630        [
 631            "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
 632            "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
 633            "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
 634            "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
 635            "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
 636            "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
 637            "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard",
 638            "cell phone",
 639            "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
 640            "hair drier", "toothbrush"
 641        ];
 42
 43        /// <summary>
 44        /// Name of the model file required by this engine.
 45        /// The yolo11n.onnx model is registered in the default ModelRegistry.
 46        /// </summary>
 047        protected override string ModelName => "yolo11n.onnx";
 48
 49        // Note: ModelDownloadUrls is not overridden because yolo11n.onnx is in the default registry.
 50        // The engine will automatically find download URLs from models.json.
 51        // Override ModelDownloadUrls only for custom/unregistered models.
 52
 53        public FaceDetectionEngine(InferenceEngineOptions options, ILogger<FaceDetectionEngine> logger)
 654            : base(options, logger)
 55        {
 656        }
 57
 58        // --- Pipeline Implementation ---
 59
 60        /// <summary>
 61        /// Preprocesses the image and returns the tensor + scaling context.
 62        /// </summary>
 63        protected override (List<NamedOnnxValue> InputTensors, object? Context) PreProcessWithContext(byte[] imageBytes)
 64        {
 65            // 1. Decode
 066            using var sourceImage = SKBitmap.Decode(imageBytes)
 067                ?? throw new ArgumentException("Failed to decode input image bytes", nameof(imageBytes));
 68
 69            // 2. Get Dimensions (Metadata is auto-populated by BaseInferenceEngine)
 70            // Dimensions are usually [-1, 3, Height, Width] or [-1, 3, -1, -1] for dynamic shapes
 071            if (InputMetadata is null || PrimaryInputName is null || !InputMetadata.ContainsKey(PrimaryInputName))
 72            {
 073                throw new InvalidOperationException($"Engine is not loaded or model metadata is missing. Ensure {nameof(
 74            }
 075            var dims = InputMetadata[PrimaryInputName].Dimensions;
 076            int modelH = dims[2] > 0 ? dims[2] : 640; // Default to 640 for dynamic shapes
 077            int modelW = dims[3] > 0 ? dims[3] : 640;
 78
 79            // 3. Resize
 080            using var resized = sourceImage.Resize(new SKImageInfo(modelW, modelH), SKSamplingOptions.Default)
 081                ?? throw new Exception($"Failed to resize image to {modelW}x{modelH}");
 82
 83            // 4. Calculate Scale Factors (Context)
 084            var context = new ImageScaleContext
 085            {
 086                ScaleX = (float)sourceImage.Width / modelW,
 087                ScaleY = (float)sourceImage.Height / modelH,
 088                SourceWidth = sourceImage.Width,
 089                SourceHeight = sourceImage.Height
 090            };
 91
 92            // 5. To Tensor (NCHW)
 093            var tensor = new DenseTensor<float>([1, 3, modelH, modelW]);
 094            using var converted = resized.Copy(SKColorType.Rgba8888);
 095            var pixels = converted.Bytes;
 096            var bytesPerPixel = converted.BytesPerPixel;
 97
 098            Parallel.For(0, modelH, y =>
 099            {
 0100                for (int x = 0; x < modelW; x++)
 0101                {
 0102                    int offset = (y * modelW + x) * bytesPerPixel;
 0103                    tensor[0, 0, y, x] = pixels[offset] / 255.0f; // R
 0104                    tensor[0, 1, y, x] = pixels[offset + 1] / 255.0f; // G
 0105                    tensor[0, 2, y, x] = pixels[offset + 2] / 255.0f; // B
 0106                }
 0107            });
 108
 0109            return (new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor(PrimaryInputName, tensor) }, context);
 0110        }
 111
 112        /// <summary>
 113        /// Postprocesses the output tensors using the scaling context to map boxes.
 114        /// </summary>
 115        protected override List<PredictionResult> PostProcessWithContext(
 116            IDisposableReadOnlyCollection<DisposableNamedOnnxValue> output,
 117            object? context)
 118        {
 0119            var scaleCtx = context as ImageScaleContext
 0120                ?? throw new InvalidOperationException("Invalid context type passed to PostProcess");
 121
 0122            var outputTensor = output.First(o => o.Name == "output0").AsTensor<float>();
 0123            var predictions = new List<PredictionResult>();
 124
 0125            int channels = outputTensor.Dimensions[1];
 0126            int anchors = outputTensor.Dimensions[2];
 127
 128            // 1. Determine Coordinate Space (Heuristic)
 0129            float maxCx = float.NegativeInfinity, maxCy = float.NegativeInfinity;
 0130            float maxW = float.NegativeInfinity, maxH = float.NegativeInfinity;
 131
 0132            for (int i = 0; i < anchors; i++)
 133            {
 0134                if (outputTensor[0, 0, i] > maxCx) maxCx = outputTensor[0, 0, i];
 0135                if (outputTensor[0, 1, i] > maxCy) maxCy = outputTensor[0, 1, i];
 0136                if (outputTensor[0, 2, i] > maxW) maxW = outputTensor[0, 2, i];
 0137                if (outputTensor[0, 3, i] > maxH) maxH = outputTensor[0, 3, i];
 138            }
 139
 140            // Using Dimensions from Metadata for accurate space inference
 141            // Apply same dynamic-shape fallback as PreProcessWithContext
 0142            var postDims = InputMetadata![PrimaryInputName!].Dimensions;
 0143            int modelH = postDims[2] > 0 ? postDims[2] : 640;
 0144            int modelW = postDims[3] > 0 ? postDims[3] : 640;
 145
 0146            var coordSpace = InferBoxCoordSpace(maxCx, maxCy, maxW, maxH, scaleCtx.SourceWidth, scaleCtx.SourceHeight, m
 147
 148            // 2. Filter & Decode
 0149            for (int i = 0; i < anchors; i++)
 150            {
 151                // Find max class score
 0152                float maxScore = 0;
 0153                int maxClassId = -1;
 154
 0155                for (int c = 4; c < channels; c++)
 156                {
 0157                    float score = outputTensor[0, c, i];
 0158                    if (score > maxScore)
 159                    {
 0160                        maxScore = score;
 0161                        maxClassId = c - 4;
 162                    }
 163                }
 164
 0165                if (maxScore < ConfidenceThreshold) continue;
 166
 167                // Extract Box
 0168                float cx = outputTensor[0, 0, i];
 0169                float cy = outputTensor[0, 1, i];
 0170                float w = outputTensor[0, 2, i];
 0171                float h = outputTensor[0, 3, i];
 172
 173                // Center -> Top-Left
 0174                float x = cx - (w / 2);
 0175                float y = cy - (h / 2);
 176
 177                // Decode
 0178                var (px, py, pw, ph) = DecodeToSourcePixels(
 0179                    coordSpace, x, y, w, h,
 0180                    scaleCtx.ScaleX, scaleCtx.ScaleY,
 0181                    scaleCtx.SourceWidth, scaleCtx.SourceHeight);
 182
 0183                predictions.Add(new PredictionResult
 0184                {
 0185                    Label = maxClassId >= 0 && maxClassId < _labels.Length ? _labels[maxClassId] : "Unknown",
 0186                    Confidence = maxScore,
 0187                    X = px, Y = py, Width = pw, Height = ph
 0188                });
 189            }
 190
 0191            return ApplyNMS(predictions);
 192        }
 193
 194        // --- DTOs & Helpers ---
 195
 196        private class ImageScaleContext
 197        {
 0198            public float ScaleX { get; set; }
 0199            public float ScaleY { get; set; }
 0200            public int SourceWidth { get; set; }
 0201            public int SourceHeight { get; set; }
 202        }
 203
 204        public class PredictionResult
 205        {
 16206            public string Label { get; set; } = string.Empty;
 13207            public float Confidence { get; set; }
 23208            public float X { get; set; }
 23209            public float Y { get; set; }
 23210            public float Width { get; set; }
 23211            public float Height { get; set; }
 212        }
 213
 214        public enum BoxCoordSpace { Normalized01, ModelInputPixels, SourcePixels, Unknown }
 215
 216        public BoxCoordSpace InferBoxCoordSpace(
 217            float maxCx, float maxCy, float maxW, float maxH,
 218            int srcW, int srcH, int modelW, int modelH)
 219        {
 3220            float maxAll = Math.Max(Math.Max(maxCx, maxCy), Math.Max(maxW, maxH));
 221
 4222            if (maxAll <= CoordSpaceToleranceMargin) return BoxCoordSpace.Normalized01;
 223
 2224            float modelMax = Math.Max(modelW, modelH);
 3225            if (maxAll <= modelMax * CoordSpaceToleranceMargin) return BoxCoordSpace.ModelInputPixels;
 226
 1227            float srcMax = Math.Max(srcW, srcH);
 2228            if (maxAll <= srcMax * CoordSpaceToleranceMargin) return BoxCoordSpace.SourcePixels;
 229
 0230            return BoxCoordSpace.Unknown;
 231        }
 232
 233        public static (float X, float Y, float W, float H) DecodeToSourcePixels(
 234            BoxCoordSpace space, float x, float y, float w, float h, float sX, float sY, int srcW, int srcH)
 235        {
 4236            return space switch
 4237            {
 1238                BoxCoordSpace.Normalized01 => (x * srcW, y * srcH, w * srcW, h * srcH),
 1239                BoxCoordSpace.ModelInputPixels => (x * sX, y * sY, w * sX, h * sY),
 1240                BoxCoordSpace.SourcePixels => (x, y, w, h),
 1241                _ => throw new InvalidOperationException($"Unknown coordinate space detected.")
 4242            };
 243        }
 244
 245        protected List<PredictionResult> ApplyNMS(List<PredictionResult> boxes)
 246        {
 4247            var sorted = boxes.OrderByDescending(b => b.Confidence).ToList();
 1248            var selected = new List<PredictionResult>();
 249
 3250            while (sorted.Count > 0)
 251            {
 2252                var best = sorted[0];
 2253                selected.Add(best);
 2254                sorted.RemoveAt(0);
 255
 8256                for (int i = sorted.Count - 1; i >= 0; i--)
 257                {
 3258                    if (CalculateIoU(best, sorted[i]) > IouThreshold) sorted.RemoveAt(i);
 259                }
 260            }
 1261            return selected;
 262        }
 263
 264        protected float CalculateIoU(PredictionResult boxA, PredictionResult boxB)
 265        {
 4266            float xA = Math.Max(boxA.X, boxB.X);
 4267            float yA = Math.Max(boxA.Y, boxB.Y);
 4268            float xB = Math.Min(boxA.X + boxA.Width, boxB.X + boxB.Width);
 4269            float yB = Math.Min(boxA.Y + boxA.Height, boxB.Y + boxB.Height);
 270
 4271            float interArea = Math.Max(0, xB - xA) * Math.Max(0, yB - yA);
 4272            float unionArea = (boxA.Width * boxA.Height) + (boxB.Width * boxB.Height) - interArea;
 273
 4274            if (unionArea <= 0f) return 0f;
 275
 4276            return interArea / unionArea;
 277        }
 278    }
 279}