-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFaceDetection.cs
More file actions
70 lines (60 loc) · 2.16 KB
/
Copy pathFaceDetection.cs
File metadata and controls
70 lines (60 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Dnn;
using Emgu.CV.Structure;
using System;
using System.Collections.Generic;
using System.Drawing;
namespace FaceDetection
{
/// <summary>
/// Wraps the Emgu CV YuNet face-detector and returns the bounding rectangles
/// of all faces found in a bitmap.
/// </summary>
public sealed class FaceRectangleDetector : IDisposable
{
private readonly FaceDetectorYN _model;
/// <param name="inputSize">
/// The width/height that YuNet expects.
/// Pass the frame size of your camera / video source.
/// </param>
public FaceRectangleDetector(Size inputSize)
{
_model = new FaceDetectorYN(
model: "face_detection_yunet_2022mar.onnx",
config: string.Empty,
inputSize: inputSize,
scoreThreshold: 0.9f,
nmsThreshold: 0.3f,
topK: 5,
backendId: Emgu.CV.Dnn.Backend.Default,
targetId: Target.Cpu);
}
/// <summary>
/// Detects faces in <paramref name="image"/> and returns their rectangles.
/// </summary>
/// <param name="image">Source frame (BGR or RGB bitmap).</param>
/// <returns>Zero or more face rectangles.</returns>
public IReadOnlyList<Rectangle> GetFaceRectangles(Bitmap image)
{
using var frame = image.ToMat(); // convert to Mat
using var faces = new Mat();
_model.Detect(frame, faces);
var results = new List<Rectangle>();
if (faces.Rows <= 0)
return results;
var facesData = (float[,])faces.GetData(jagged: true);
for (int i = 0; i < facesData.GetLength(0); i++)
{
var rect = new Rectangle(
x: (int)facesData[i, 0],
y: (int)facesData[i, 1],
width: (int)facesData[i, 2],
height: (int)facesData[i, 3]);
results.Add(rect);
}
return results;
}
public void Dispose() => _model?.Dispose();
}
}