端くれプログラマの備忘録 OpenCV [OpenCV] 顔検出サンプル (C#版)

[OpenCV] 顔検出サンプル (C#版)

C++のサンプルをOpenCVSharp3を使ってC#に書き直してみた。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace OpenCVFaceCSharp
{
    class Program
    {
        static Mat detectFaceInImage(Mat image, string cascade_file)
        {
            CascadeClassifier cascade = new CascadeClassifier();
            cascade.Load(cascade_file);
            Rect[] faces = cascade.DetectMultiScale(image, 1.1, 3, 0, new Size(20, 20));

            for (int i = 0; i < faces.Length; i++)
            {
                Cv2.Rectangle(
                    image,
                    new Point(faces[i].X, faces[i].Y),
                    new Point(faces[i].X + faces[i].Width, faces[i].Y + faces[i].Height),
                    new Scalar(0, 200, 0), 3, LineTypes.AntiAlias);
            }
            return image;
        }

        static void Main(string[] args)
        {
            Mat image = Cv2.ImRead("lena.png");
            string filename = "C:\\OpenCV\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml";
            Mat detectFaceImage = detectFaceInImage(image, filename);
            Cv2.ImShow("detect face", detectFaceImage);
            Cv2.WaitKey(0);
        }
    }
}