Search code examples
c#winformsface-detection

c# win app forms detect the number of faces on image and prompt error message if there is more than 1 face


I am currently doing an ID pic uploading system using C# Windows App Forms and I would like to allow the user to upload an image and the image must only contain 1 front face. To prevent user from uploading more than 1 face, I would like to prompt them an error message once the system detects more than one face in an image but I am not sure how to go about it. I used takuya takeuchi's dlibdotnet library.

Here is my current code.

namespace DetectTrial


{

    public partial class Form1 : Form
    {
        #region Fields
        private readonly BackgroundWorker _BackgroundWorker;
        #endregion

        #region Constructors
        public Form1()
        {
            this.InitializeComponent();
            this._BackgroundWorker = new BackgroundWorker();
            this._BackgroundWorker.DoWork += this.BackgroundWorkerOnDoWork;
        }
        #endregion

        #region Methods
        #region Event Handlers

        private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            var path = doWorkEventArgs.Argument as string;
            if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
                return;

            using (var faceDetector = Dlib.GetFrontalFaceDetector())
            using (var ms = new MemoryStream(File.ReadAllBytes(path)))
            using (var bitmap = (Bitmap)Image.FromStream(ms))
            {
                using (var image = bitmap.ToArray2D<RgbPixel>())
                {
                    var dets = faceDetector.Operator(image);
                    foreach (var g in dets)
                        Dlib.DrawRectangle(image, g, new RgbPixel { Green = 255 }, thickness: 10);
                    var result = image.ToBitmap();
                    this.pictureBox1.Invoke(new Action(() =>
                    {
                        this.pictureBox1.Image?.Dispose();
                        this.pictureBox1.Image = result;
                    }));

                }

            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (var opnfd = new OpenFileDialog())
            {
                opnfd.Filter = "Image Files (*.jpg;*.jpeg;*.png;)|*.jpg;*.jpeg;*.png";
                if (opnfd.ShowDialog(this) == DialogResult.OK)
                {
                    this._BackgroundWorker.RunWorkerAsync(opnfd.FileName);
                }
            }
        }
        #endregion
        #endregion
    }
}

I don't know where to go from here.


Solution

  • I'm not familiar with the library you're using, but if dets is a collection of detected face rectangles, you can probably use something like this:

    var dets = faceDetector.Operator(image);
    if (dets.Count() > 1)
    {
        MessageBox.Show("Too many faces! Why are there so many faces? I can't look. Please make it stop.");
        return;
    }
    else
    {
        var g = dets.First();
        Dlib.DrawRectangle(image, g, new RgbPixel { Green = 255 }, thickness: 10);
        var result = image.ToBitmap();
        this.pictureBox1.Invoke(new Action(() =>
        {
            this.pictureBox1.Image?.Dispose();
            this.pictureBox1.Image = result;
        }));
    }
    

    Note that Count() and First() are extension methods from System.Linq so you'll need to make sure there's a using System.Linq; directive at the top of your code file.

    Also, the Invoke code is probably better moved to the BackgroundWorker's OnRunWorkerCompleted event (where the cross-thread invoke will no longer be needed) and you can access the PictureBox directly.