Пример #1
0
        /// <summary>
        ///     Детектирование лиц и прорисовка квадрата на каждом из лиц.
        /// </summary>
        private void DetectFaces()
        {
            // Проверка на получения картинки
            if (null != cameraBitmap)
            {
                //Получаем ширину
                var width = cameraBitmap.Width;
                //Получаем высоту
                var height = cameraBitmap.Height;
                //Создаем экземпляр класса нативных библиотек распознования от Android
                var detector = new FaceDetector(width, height, MaxFaces);
                //Создаем массив лиц
                var faces = new FaceDetector.Face[MaxFaces];
                //Создаем основной Bitmap
                var bitmap565   = Bitmap.CreateBitmap(width, height, Bitmap.Config.Rgb565);
                var ditherPaint = new Paint();
                //Рамка захвата
                var drawPaint = new Paint();
                ditherPaint.Dither = true;
                //Устанавливаем цвет квадрата, штриховку, толщину
                drawPaint.Color = Color.Blue;
                drawPaint.SetStyle(Paint.Style.Stroke);
                drawPaint.StrokeWidth = 2;
                //Создаем холст и устанавливаем
                var canvas = new Canvas();
                canvas.SetBitmap(bitmap565);
                canvas.DrawBitmap(cameraBitmap, 0, 0, ditherPaint);
                //Получаем количество лиц
                var facesFound = detector.FindFaces(bitmap565, faces);
                //Средняя точка
                var midPoint = new PointF();
                //Расстояние до глаз
                float eyeDistance;
                float confidence;
                //Печать в консоль для тестирования приложения
                Console.WriteLine($"Найдено лиц: {facesFound}");
                //Проверка, что найдено хоть одно лицо
                if (facesFound > 0)
                {
                    for (var index = 0; index < facesFound; ++index)
                    {
                        faces[index].GetMidPoint(midPoint);
                        eyeDistance = faces[index].EyesDistance();
                        confidence  = faces[index].Confidence();
                        //Печатаем для отладки в консоль
                        Console.WriteLine($"Коэфициент доверия: {confidence} Расстояние до глаз: {eyeDistance}" +
                                          $"Средняя точка: ( X: {midPoint.X} Y: {midPoint.Y} )");


                        //Передаем в TextView значение расстояния до лица
                        ((TextView)FindViewById(Resource.Id.tvDistanceToCamera)).Text = $"{eyeDistance:0.00} см";

                        //Рисуем квадрат
                        canvas.DrawRect((int)midPoint.X - eyeDistance,
                                        (int)midPoint.Y - eyeDistance,
                                        (int)midPoint.X + eyeDistance,
                                        (int)midPoint.Y + eyeDistance, drawPaint);
                    }
                }

                var imageView = (ImageView)FindViewById(Resource.Id.image_view);
                imageView.SetImageBitmap(bitmap565);
            }
        }
Пример #2
0
        /// <summary>
        /// detect faces on a picture and draw a square in each face
        /// </summary>
        private void detectFaces()
        {
            //first check if picture has been taken
            if (null != cameraBitmap)
            {
                //get width of a picture
                int width = cameraBitmap.Width;
                //get height of a picture
                int height = cameraBitmap.Height;
                //Initialize a facedetector with the picture dimensions and the max number of faces to check
                FaceDetector detector = new FaceDetector(width, height, MainActivity.MAX_FACES);
                //Create an array of faces with the number of max faces to check
                Android.Media.FaceDetector.Face[] faces = new Android.Media.FaceDetector.Face[MainActivity.MAX_FACES];

                //create a main bitmap
                Bitmap bitmap565 = Bitmap.CreateBitmap(width, height, Bitmap.Config.Rgb565);
                //create a dither paint
                Paint ditherPaint = new Paint();
                //create a draw paint
                Paint drawPaint = new Paint();

                //set true dither to dither paint variable
                ditherPaint.Dither = true;
                //set color red for the square
                drawPaint.Color = Color.Red;
                //set stroke to style
                drawPaint.SetStyle(Paint.Style.Stroke);
                //set stroke width
                drawPaint.StrokeWidth = 2;

                //Create a canvas
                Canvas canvas = new Canvas();
                //set bitmap to canvas
                canvas.SetBitmap(bitmap565);
                //draw bitmap to canvas
                canvas.DrawBitmap(cameraBitmap, 0, 0, ditherPaint);

                //get a number of faces detected
                int facesFound = detector.FindFaces(bitmap565, faces);
                //mid face point
                PointF midPoint = new PointF();
                //eye distance variable
                float eyeDistance = 0.0f;
                //confidence variable
                float confidence = 0.0f;
                //print numbre of faces found
                System.Console.WriteLine("Number of faces found: " + facesFound);

                //check if found at least one face
                if (facesFound > 0)
                {
                    //for each face draw a red squeare
                    for (int index = 0; index < facesFound; ++index)
                    {
                        // get midpoint of a face
                        faces[index].GetMidPoint(midPoint);
                        //get eye distance
                        eyeDistance = faces[index].EyesDistance();
                        //get confidence
                        confidence = faces [index].Confidence();
                        //print all parameters
                        System.Console.WriteLine("Confidence: " + confidence +
                                                 ", Eye distance: " + eyeDistance +
                                                 ", Mid Point: (" + midPoint.X + ", " + midPoint.Y + ")");
                        //draw a square in the picture
                        canvas.DrawRect((int)midPoint.X - eyeDistance,
                                        (int)midPoint.Y - eyeDistance,
                                        (int)midPoint.X + eyeDistance,
                                        (int)midPoint.Y + eyeDistance, drawPaint);
                    }
                }

                //get imageview from layout
                ImageView imageView = (ImageView)FindViewById(Resource.Id.image_view);
                //set image with the red squares to imageview
                imageView.SetImageBitmap(bitmap565);
            }
        }
        public void Run()
        {
            EmCropImage eci = this.ECI;

            if (eci == null)
            {
                return;
            }

            this.MImageMatrix = eci.ImageView.ImageMatrix;
            Bitmap faceBitmap = PrepareBitmap();

            if (faceBitmap != null)
            {
                this.Scale = 1.0F / this.Scale;
                if (faceBitmap != null && eci.DoingFaceDetection)
                {
                    FaceDetector detector = new FaceDetector(faceBitmap.Width,
                                                             faceBitmap.Height, this.Faces.Length);
                    this.NumberOfFaces = detector.FindFaces(faceBitmap, this.Faces);
                }

                if (faceBitmap != null && faceBitmap != eci.Bitmap)
                {
                    faceBitmap.Recycle();
                }
            }

            eci.MHandler.Post(() => {
                eci.WaitingToPick = this.NumberOfFaces > 1;

                if (this.NumberOfFaces > 0)
                {
                    for (int i = 0; i < this.NumberOfFaces; i++)
                    {
                        HandleFace(this.Faces[i]);
                    }
                }
                else
                {
                    MakeDefault();
                }

                eci.ImageView.Invalidate();

                if (eci.ImageView.MotionHighlightViews.Count == 1)
                {
                    eci.MCrop         = eci.ImageView.MotionHighlightViews [0];
                    eci.MCrop.Focused = true;
                }

                // Translation Note: I have no idea how to get to this area of code.
                // It has something to do with face recognition.
                if (this.NumberOfFaces > 1)
                {
                    Toast t = Toast.MakeText(eci,
                                             "Touch a face to begin.",
                                             ToastLength.Short);
                    t.Show();
                }
            });
        }