Search code examples
c#.netopencvfacial-identification

Drawing rectangles using OpenCvSharp


I am trying to draw the faces detected in a video live on it, but I seem to be having troubles getting it to work

var haarcascade = new CascadeClassifier("C:/Users/NotMyName/Desktop/haar/haarcascade_frontalface_alt2.xml");
using (Window window = new Window("capture"))
using (Mat image = new Mat())//Image Buffer
{
    while (true)
    {
        Video.Read(image);
        var gray = image.CvtColor(ColorConversionCodes.RGB2GRAY);
        OpenCvSharp.Rect[] faces = haarcascade.DetectMultiScale(gray, 1.08, 2, HaarDetectionTypes.ScaleImage, new OpenCvSharp.Size(30,30));
        foreach (Rect i in faces)
        {
            Cv2.Rectangle(image, (faces[i].BottomRight.X, faces[i].BottomRight.Y), (faces[i].TopLeft.X, faces[i].TopLeft.Y), 255, 1);
        }

However, the compiler is only spitting errors. Passing the faces array directly to the function also didn't work. The error message is (translated from German).

Error CS0029 The Type "OpenCvSharp.Rect" can't be converted to "int"


Solution

  • I think that correct way should be this:

    ...
    foreach (Rect i in faces)
    {
        Cv2.Rectangle(image, new Point(i.BottomRight.X, i.BottomRight.Y), new Point(i.TopLeft.X, i.TopLeft.Y), 255, 1);
    }
    ....
    

    The local variable i inside the foreach reference to current Rect.

    Cv2.Rectangle method accepts OpenCvSharp.Point.