Example #1
0
        public IActionResult CaptureImage(IFormFile file)
        {
            if (file == null)
            {
                return(Json(new
                {
                    Status = 0
                }));
            }
            byte[] imageBytes = null;
            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                imageBytes = ms.ToArray();
            }

            Image image5 = Image.FromBytes(imageBytes);
            ImageAnnotatorClient             client = ImageAnnotatorClient.Create();
            IReadOnlyList <EntityAnnotation> labels = client.DetectLabels(image5);

            client.DetectFaces(image5);
            var faceAttributeList = new List <FaceAttribute>();

            foreach (EntityAnnotation label in labels)
            {
                faceAttributeList.Add(new FaceAttribute()
                {
                    Score       = ((int)(label.Score * 100)).ToString(),
                    Description = label.Description
                });;
                // Console.WriteLine($"Score: {(int)(label.Score * 100)}%; Description: {label.Description}");
            }
            IReadOnlyList <FaceAnnotation> faceAnnotations = client.DetectFaces(image5);

            IReadOnlyList <EntityAnnotation> texts = client.DetectText(image5);
            var textList = new List <FaceAttribute>();

            foreach (EntityAnnotation label in texts)
            {
                textList.Add(new FaceAttribute()
                {
                    Score       = ((int)(label.Score * 100)).ToString(),
                    Description = label.Description
                });;
            }
            SafeSearchAnnotation searchAnnotations = client.DetectSafeSearch(image5);

            return(Json(new FaceResponse()
            {
                labels = faceAttributeList, faceAnnotations = faceAnnotations, texts = textList, searchAnnotations = searchAnnotations
            }));
        }
        public void DetectFaces()
        {
            Image image = LoadResourceImage("SchmidtBrinPage.jpg");
            // Snippet: DetectFaces
            ImageAnnotatorClient           client = ImageAnnotatorClient.Create();
            IReadOnlyList <FaceAnnotation> result = client.DetectFaces(image);

            foreach (FaceAnnotation face in result)
            {
                string poly = string.Join(" - ", face.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
                Console.WriteLine($"Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {poly}");
            }
            // End snippet

            Assert.Equal(3, result.Count);

            // Check the bounding boxes of the faces, with a tolerance of 5px on each edge.
            var rectangles = result.Select(x => Rectangle.FromBoundingPoly(x.BoundingPoly)).ToList();

            Assert.True(rectangles.All(x => x != null));
            rectangles = rectangles.OrderBy(r => r.Left).ToList();
            Assert.True(rectangles[0].Equals(new Rectangle(196, 64, 293, 177), 5.0));
            Assert.True(rectangles[1].Equals(new Rectangle(721, 162, 846, 308), 5.0));
            Assert.True(rectangles[2].Equals(new Rectangle(1009, 113, 1149, 276), 5.0));
        }
Example #3
0
        /// <summary>
        /// Generate and send request for a single image to Google cloud vision for detecting faces
        /// </summary>
        /// <param name="client"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public IReadOnlyList <FaceAnnotation> GetFaceAnnotationResponse(ImageAnnotatorClient client, string file)
        {
            var image    = Image.FromFile($"{file}");
            var response = client.DetectFaces(image);

            return(response);
        }
Example #4
0
        public ActionResult Capture(string base64String)
        {
            byte[] imageBytes = null;

            if (!string.IsNullOrEmpty(base64String))
            {
                var imageParts = base64String.Split(',').ToList <string>();
                imageBytes = Convert.FromBase64String(imageParts[1]);
            }


            Image image5 = Image.FromBytes(imageBytes);
            ImageAnnotatorClient             client = ImageAnnotatorClient.Create();
            IReadOnlyList <EntityAnnotation> labels = client.DetectLabels(image5);

            client.DetectFaces(image5);
            var faceAttributeList = new List <FaceAttribute>();

            foreach (EntityAnnotation label in labels)
            {
                faceAttributeList.Add(new FaceAttribute()
                {
                    Score       = ((int)(label.Score * 100)).ToString(),
                    Description = label.Description
                });;
                // Console.WriteLine($"Score: {(int)(label.Score * 100)}%; Description: {label.Description}");
            }
            IReadOnlyList <FaceAnnotation>   faceAnnotations = client.DetectFaces(image5);
            IReadOnlyList <EntityAnnotation> texts           = client.DetectText(image5);
            var textList = new List <FaceAttribute>();

            foreach (EntityAnnotation label in texts)
            {
                textList.Add(new FaceAttribute()
                {
                    Score       = ((int)(label.Score * 100)).ToString(),
                    Description = label.Description
                });;
            }
            SafeSearchAnnotation searchAnnotations = client.DetectSafeSearch(image5);

            return(Json(new FaceResponse()
            {
                labels = faceAttributeList, faceAnnotations = faceAnnotations, texts = textList, searchAnnotations = searchAnnotations
            }));
        }
Example #5
0
        private List <MediaProperties> AnalyseFaces(ImageAnnotatorClient client, Image image)
        {
            var facesList  = new List <MediaProperties>();
            var imageFaces = client.DetectFaces(image);

            //if (imageFaces != null && imageFaces.Count > 0)
            //{
            //    foreach (var face in imageFaces)
            //    {
            //        facesList.Add(new MediaProperties
            //        {
            //            Type = MediaPropertyType.Vips
            //        });
            //    }
            //}

            return(facesList);
        }
Example #6
0
        // Отдельнй поток с отправкой снимков для анализа
        private void backgroundWorkerDetection_DoWork(object sender, DoWorkEventArgs e)
        {
            // Объявление переменной с количеством отправляемых снимков
            int cases = 1;
            // Создание клиента для работы с Google Vision API
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            // Создание списка, в котором будут хранится результаты анализа
            List <FaceDetectionData> faceDetectionData = new List <FaceDetectionData> {
            };

            // Создание массива содержащего пути ко всем файлам, отправляемым на анализ
            string[] allfiles = Directory.GetFiles(textBoxDirectory.Text + "\\snapshots");
            // Цикл, в котором каждый файл отправляется на анализ, а полученные результаты записываются в созданный CSV-файл
            foreach (string filename in allfiles)
            {
                // Берётся отдельный снимок по пути из списка
                Google.Cloud.Vision.V1.Image image = Google.Cloud.Vision.V1.Image.FromFile($"{filename}");
                // Результат записывается в списке
                IReadOnlyList <FaceAnnotation> result = client.DetectFaces(image);
                // Цикл в котором каждый результат, в нужном представлении, записывается в CSV-файл
                foreach (FaceAnnotation face in result)
                {
                    faceDetectionData.Add(new FaceDetectionData()
                    {
                        Case = $"{cases++}", RecordingTime = $"{Path.GetFileNameWithoutExtension(filename)}", Joy = $"{face.JoyLikelihood}", Surprise = $"{face.SurpriseLikelihood}", Sorrow = $"{face.SorrowLikelihood}", Anger = $"{face.AngerLikelihood}"
                    });
                    using (StreamWriter streamReader = new StreamWriter($"{textBoxDirectory.Text}\\table.csv"))
                    {
                        using (CsvWriter csvReader = new CsvWriter(streamReader, CultureInfo.InvariantCulture))
                        {
                            csvReader.Configuration.Delimiter = ",";
                            csvReader.WriteRecords(faceDetectionData);
                        }
                    }
                }
            }
            // Отображение сообщения о том, что анализ проведён и результаты записаны
            MessageBox.Show("Результаты записаны");
            // Завершает отдельный поток, в котором проводится анализ снимков и запись результатов
            backgroundWorkerDetection.CancelAsync();
        }