using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp51
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Capture capture = new Capture();
            capture.Start();


            HaarCascade haaryuz = new HaarCascade("haarcascade_frontalface_default.xml");

            int Sayac = 1;
            capture.ImageGrabbed += (x, y) =>
            {
                var image = capture.RetrieveBgrFrame();
                if (image != null)
                {
                    var grayimage = image.Convert<Gray, byte>();

                    MCvAvgComp[][] Yuzler = grayimage.DetectHaarCascade(haaryuz, 1.2, 5, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(15, 15));

                    foreach (MCvAvgComp yuz in Yuzler[0])
                    {
                        AForge.Imaging.Filters.Crop Kes = new AForge.Imaging.Filters.Crop(yuz.rect);
                        Bitmap YuzResmi = Kes.Apply(image.Bitmap);

                        if (Sayac != 7)
                        {
                            foreach (var nesne in Controls)
                            {
                                if (nesne is PictureBox pb)
                                    if (pb.Name == "p" + Sayac)
                                    {
                                        pb.Image = YuzResmi;
                                        Sayac++;
                                    }
                            }
                        }
                        else
                            Sayac = 1;

                        //Yüzü Vurguluyorum
                        Graphics g = Graphics.FromImage(image.Bitmap);
                        g.DrawArc(new Pen(Color.Green, 3), yuz.rect, -30, 240);
                        MCvFont font = new MCvFont(FONT.CV_FONT_HERSHEY_COMPLEX, 0.3, 0.3);
                        //Yazı Yazıyorum
                        image.Draw("Yuz", ref font, new Point(yuz.rect.X + 10, yuz.rect.Y + 20), new Bgr(Color.Yellow));
                    }
                }
                pictureBox1.Image = image.ToBitmap();
            };
        }
    }
}
