Пример #1
0
        static void IdentifyCelebrityFaces(string filename)
        {
            // Using USWest2, not the default region
            AmazonRekognitionClient rekoClient = new AmazonRekognitionClient(Amazon.RegionEndpoint.USWest2);

            // Request needs image bytes, so read and add to request
            byte[] data = File.ReadAllBytes(filename);

            RecognizeCelebritiesRequest rcr = new RecognizeCelebritiesRequest
            {
                Image = new Amazon.Rekognition.Model.Image
                {
                    Bytes = new MemoryStream(data)
                }
            };

            RecognizeCelebritiesResponse outcome = rekoClient.RecognizeCelebrities(rcr);

            if (outcome.CelebrityFaces.Count > 0)
            {
                // Load a bitmap to modify with face bounding box rectangles
                Bitmap facesHighlighted = new Bitmap(filename);
                Pen    pen      = new Pen(Color.Black, 3);
                Font   drawFont = new Font("Arial", 12);

                // Create a graphics context
                using (var graphics = Graphics.FromImage(facesHighlighted))
                {
                    foreach (var fd in outcome.CelebrityFaces)
                    {
                        // Get the bounding box
                        BoundingBox bb = fd.Face.BoundingBox;
                        Console.WriteLine($"Bounding box = ({bb.Left}, {bb.Top}, {bb.Height}, {bb.Width})");

                        // Draw the rectangle using the bounding box values
                        // They are percentages so scale them to picture
                        graphics.DrawRectangle(pen,
                                               x: facesHighlighted.Width * bb.Left,
                                               y: facesHighlighted.Height * bb.Top,
                                               width: facesHighlighted.Width * bb.Width,
                                               height: facesHighlighted.Height * bb.Height);
                        graphics.DrawString(fd.Name,
                                            font: drawFont,
                                            brush: Brushes.White,
                                            x: facesHighlighted.Width * bb.Left,
                                            y: facesHighlighted.Height * bb.Top + facesHighlighted.Height * bb.Height);
                    }
                }

                // Save the image with highlights as PNG
                string fileout = filename.Replace(Path.GetExtension(filename), "_celebrityfaces.png");
                facesHighlighted.Save(fileout, System.Drawing.Imaging.ImageFormat.Png);

                Console.WriteLine(">>> " + outcome.CelebrityFaces.Count + " celebrity face(s) highlighted in file " + fileout);
            }
            else
            {
                Console.WriteLine(">>> No celebrity faces found");
            }
        }
Пример #2
0
        public static async Task <List <Face> > PerformRecognition(ProcessedImage processedImage)
        {
            if (!processedImage.IsSizeOk())
            {
                throw new SourceImageContentTooLargeException();
            }

            if (!processedImage.AreDimensionsOk())
            {
                throw new SourceImageDimensionsTooSmallException();
            }

            var client = new AmazonRekognitionClient(GetCredentials(), Region);

            var stream = new MemoryStream(processedImage.ImageData);
            await stream.WriteAsync(processedImage.ImageData, 0, processedImage.ImageData.Length);

            stream.Seek(0, SeekOrigin.Begin);

            var image = new Image {
                Bytes = stream
            };
            var request = new RecognizeCelebritiesRequest {
                Image = image
            };
            var response = await client.RecognizeCelebritiesAsync(request);

            return(MapResponse(processedImage, response));
        }
        internal RecognizeCelebritiesResponse RecognizeCelebrities(RecognizeCelebritiesRequest request)
        {
            var marshaller   = new RecognizeCelebritiesRequestMarshaller();
            var unmarshaller = RecognizeCelebritiesResponseUnmarshaller.Instance;

            return(Invoke <RecognizeCelebritiesRequest, RecognizeCelebritiesResponse>(request, marshaller, unmarshaller));
        }
        /// <summary>
        /// Initiates the asynchronous execution of the RecognizeCelebrities operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the RecognizeCelebrities operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/rekognition-2016-06-27/RecognizeCelebrities">REST API Reference for RecognizeCelebrities Operation</seealso>
        public Task <RecognizeCelebritiesResponse> RecognizeCelebritiesAsync(RecognizeCelebritiesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new RecognizeCelebritiesRequestMarshaller();
            var unmarshaller = RecognizeCelebritiesResponseUnmarshaller.Instance;

            return(InvokeAsync <RecognizeCelebritiesRequest, RecognizeCelebritiesResponse>(request, marshaller,
                                                                                           unmarshaller, cancellationToken));
        }
Пример #5
0
        public async Task <IActionResult> Login(IFormFile file)
        {
            CelebrityModel celeb = new CelebrityModel();

            Directory.Delete(_appEnvironment.WebRootPath + "/resources/", true);
            Directory.CreateDirectory(_appEnvironment.WebRootPath + "/resources/");

            if (null != file && file.Length > 0)
            {
                string speechFileName = "notjeff.mp3";
                string speechText     = "Nice try. You're not Jeff, I can't let you in.";

                AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();

                RecognizeCelebritiesRequest    recognizeCelebritiesRequest = new RecognizeCelebritiesRequest();
                Amazon.Rekognition.Model.Image img = new Amazon.Rekognition.Model.Image();

                MemoryStream memStream = new MemoryStream();
                file.CopyTo(memStream);
                img.Bytes = memStream;
                recognizeCelebritiesRequest.Image = img;

                RecognizeCelebritiesResponse recognizeCelebritiesResponse = await rekognitionClient.RecognizeCelebritiesAsync(recognizeCelebritiesRequest);

                if (null != recognizeCelebritiesResponse && recognizeCelebritiesResponse.CelebrityFaces.Count > 0)
                {
                    celeb.CelebrityName = recognizeCelebritiesResponse.CelebrityFaces[0].Name;
                    celeb.Confidence    = recognizeCelebritiesResponse.CelebrityFaces[0].MatchConfidence;

                    if (celeb.CelebrityName == "Jeff Bezos")
                    {
                        speechText     = "Hello Boss, Welcome to the Deployment Bot. Please continue to start the deployment.";
                        celeb.IsJeff   = true;
                        speechFileName = "jeff.mp3";
                    }
                }
                else
                {
                    celeb.CelebrityName = "Sure, you're popular among your friends. But that doesn't make you a celebrity.";
                    celeb.Confidence    = 0;
                }

                AmazonPollyClient pollyclient = new AmazonPollyClient();
                Amazon.Polly.Model.SynthesizeSpeechResponse speechResponse =
                    await pollyclient.SynthesizeSpeechAsync(new Amazon.Polly.Model.SynthesizeSpeechRequest()
                {
                    OutputFormat = OutputFormat.Mp3, Text = speechText, VoiceId = VoiceId.Joanna
                });

                var stream = new FileStream(_appEnvironment.WebRootPath + "/resources/" + speechFileName, FileMode.Create);
                await speechResponse.AudioStream.CopyToAsync(stream);

                stream.Close();
            }

            return(View("Login", celeb));
        }
Пример #6
0
        static void IdentifyCelebrityFaces(string filename)
        {
            // Using USWest2, not the default region
            AmazonRekognitionClient rekoClient = new AmazonRekognitionClient(Amazon.RegionEndpoint.USWest2);

            RecognizeCelebritiesRequest dfr = new RecognizeCelebritiesRequest();

            // Request needs image butes, so read and add to request
            Amazon.Rekognition.Model.Image img = new Amazon.Rekognition.Model.Image();
            byte[] data = null;
            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                data = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
            }
            img.Bytes = new MemoryStream(data);
            dfr.Image = img;
            var outcome = rekoClient.RecognizeCelebrities(dfr);

            if (outcome.CelebrityFaces.Count > 0)
            {
                // Load a bitmap to modify with face bounding box rectangles
                System.Drawing.Bitmap facesHighlighted = new System.Drawing.Bitmap(filename);
                Pen  pen      = new Pen(Color.Black, 3);
                Font drawFont = new Font("Arial", 12);

                // Create a graphics context
                using (var graphics = Graphics.FromImage(facesHighlighted))
                {
                    foreach (var fd in outcome.CelebrityFaces)
                    {
                        // Get the bounding box
                        BoundingBox bb = fd.Face.BoundingBox;
                        Console.WriteLine("Bounding box = (" + bb.Left + ", " + bb.Top + ", " +
                                          bb.Height + ", " + bb.Width + ")");
                        // Draw the rectangle using the bounding box values
                        // They are percentages so scale them to picture
                        graphics.DrawRectangle(pen, x: facesHighlighted.Width * bb.Left,
                                               y: facesHighlighted.Height * bb.Top,
                                               width: facesHighlighted.Width * bb.Width,
                                               height: facesHighlighted.Height * bb.Height);
                        graphics.DrawString(fd.Name, drawFont, Brushes.White, facesHighlighted.Width * bb.Left,
                                            facesHighlighted.Height * bb.Top + facesHighlighted.Height * bb.Height);
                    }
                }
                // Save the image with highlights as PNG
                string fileout = filename.Replace(Path.GetExtension(filename), "_celebrityfaces.png");
                facesHighlighted.Save(fileout, System.Drawing.Imaging.ImageFormat.Png);
                Console.WriteLine(">>> " + outcome.CelebrityFaces.Count + " celebrity face(s) highlighted in file " + fileout);
            }
            else
            {
                Console.WriteLine(">>> No celebrity faces found");
            }
        }
Пример #7
0
        public async Task <RekognizedImage> RekognizeImage(byte[] imageData)
        {
            var dataService   = new DataService();
            var hash          = imageData.GetSha1Hash();
            var existingImage = await dataService.GetImage(hash);

            if (existingImage != null)
            {
                return(existingImage);
            }

            var convertedImage = _converterService.GetRekognitionCompatibleImage(imageData);

            if (!convertedImage.IsSizeOk())
            {
                throw new SourceImageContentTooLargeException();
            }

            if (!convertedImage.AreDimensionsOk())
            {
                throw new SourceImageDimensionsTooSmallException();
            }

            var client = new AmazonRekognitionClient(GetCredentials(), Region);

            var stream = new MemoryStream(convertedImage.ImageData);
            await stream.WriteAsync(convertedImage.ImageData, 0, convertedImage.ImageData.Length);

            stream.Seek(0, SeekOrigin.Begin);

            var image = new Image {
                Bytes = stream
            };
            var request = new RecognizeCelebritiesRequest {
                Image = image
            };
            var response = await client.RecognizeCelebritiesAsync(request);

            var recoknizedImage = new RekognizedImage
            {
                Width  = convertedImage.Width,
                Height = convertedImage.Height,
                Hash   = hash,
                Faces  = MapResponse(convertedImage, response)
            };

            await dataService.SaveImage(recoknizedImage);

            return(recoknizedImage);
        }
Пример #8
0
    public static void Example()
    {
        String photo = "moviestars.jpg";

        AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();

        RecognizeCelebritiesRequest recognizeCelebritiesRequest = new RecognizeCelebritiesRequest();

        Amazon.Rekognition.Model.Image img = new Amazon.Rekognition.Model.Image();
        byte[] data = null;
        try
        {
            using (FileStream fs = new FileStream(photo, FileMode.Open, FileAccess.Read))
            {
                data = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
            }
        }
        catch (Exception)
        {
            Console.WriteLine("Failed to load file " + photo);
            return;
        }

        img.Bytes = new MemoryStream(data);
        recognizeCelebritiesRequest.Image = img;

        Console.WriteLine("Looking for celebrities in image " + photo + "\n");

        RecognizeCelebritiesResponse recognizeCelebritiesResponse = rekognitionClient.RecognizeCelebrities(recognizeCelebritiesRequest);

        Console.WriteLine(recognizeCelebritiesResponse.CelebrityFaces.Count + " celebrity(s) were recognized.\n");
        foreach (Celebrity celebrity in recognizeCelebritiesResponse.CelebrityFaces)
        {
            Console.WriteLine("Celebrity recognized: " + celebrity.Name);
            Console.WriteLine("Celebrity ID: " + celebrity.Id);
            BoundingBox boundingBox = celebrity.Face.BoundingBox;
            Console.WriteLine("position: " +
                              boundingBox.Left + " " + boundingBox.Top);
            Console.WriteLine("Further information (if available):");
            foreach (String url in celebrity.Urls)
            {
                Console.WriteLine(url);
            }
        }
        Console.WriteLine(recognizeCelebritiesResponse.UnrecognizedFaces.Count + " face(s) were unrecognized.");
    }
        /// <summary>
        /// Get Face Matches for Celebrities from Amazon service
        /// </summary>
        /// <param name="photo"></param>
        /// <returns></returns>
        public async Task <ResponseDTO> GetMatches(IFormFile photo)
        {
            try
            {
                AmazonRekognitionClient     rekognitionClient           = new AmazonRekognitionClient(_awsCredentials.Value.Id, _awsCredentials.Value.Key, Amazon.RegionEndpoint.USEast2);
                RecognizeCelebritiesRequest recognizeCelebritiesRequest = new RecognizeCelebritiesRequest();
                Image  img  = new Image();
                byte[] data = null;
                try
                {
                    if (photo.Length > 0)
                    {
                        using (var ms = new MemoryStream())
                        {
                            photo.CopyTo(ms);
                            data = ms.ToArray();
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                img.Bytes = new MemoryStream(data);
                recognizeCelebritiesRequest.Image = img;
                RecognizeCelebritiesResponse recognizeCelebritiesResponse = await rekognitionClient.RecognizeCelebritiesAsync(recognizeCelebritiesRequest);

                foreach (Celebrity celebrity in recognizeCelebritiesResponse.CelebrityFaces)
                {
                    CelebrityDetail.Name = celebrity.Name;
                    foreach (string url in celebrity.Urls)
                    {
                        CelebrityDetail.Url = url;
                    }
                    CelebrityDetails.Add(CelebrityDetail);
                    CelebrityDetail = new CelebrityDetail();
                }
                ResponseDetail.CelebrityDetails = CelebrityDetails;
                ResponseDetail.UnMatchCount     = recognizeCelebritiesResponse.UnrecognizedFaces.Count;
                return(ResponseDetail);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        // snippet-start:[Rekognition.dotnetv3.CelebritiesInImageExample]
        public static async Task Main(string[] args)
        {
            string photo = "moviestars.jpg";

            var rekognitionClient = new AmazonRekognitionClient();

            var recognizeCelebritiesRequest = new RecognizeCelebritiesRequest();

            var img = new Amazon.Rekognition.Model.Image();

            byte[] data = null;
            try
            {
                using var fs = new FileStream(photo, FileMode.Open, FileAccess.Read);
                data         = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
            }
            catch (Exception)
            {
                Console.WriteLine($"Failed to load file {photo}");
                return;
            }

            img.Bytes = new MemoryStream(data);
            recognizeCelebritiesRequest.Image = img;

            Console.WriteLine($"Looking for celebrities in image {photo}\n");

            var recognizeCelebritiesResponse = await rekognitionClient.RecognizeCelebritiesAsync(recognizeCelebritiesRequest);

            Console.WriteLine($"{recognizeCelebritiesResponse.CelebrityFaces.Count} celebrity(s) were recognized.\n");
            recognizeCelebritiesResponse.CelebrityFaces.ForEach(celeb =>
            {
                Console.WriteLine($"Celebrity recognized: {celeb.Name}");
                Console.WriteLine($"Celebrity ID: {celeb.Id}");
                BoundingBox boundingBox = celeb.Face.BoundingBox;
                Console.WriteLine($"position: {boundingBox.Left} {boundingBox.Top}");
                Console.WriteLine("Further information (if available):");
                celeb.Urls.ForEach(url =>
                {
                    Console.WriteLine(url);
                });
            });

            Console.WriteLine($"{recognizeCelebritiesResponse.UnrecognizedFaces.Count} face(s) were unrecognized.");
        }
        public async Task <RecognizeCelebritiesResponse> Recognize(MemoryStream data)
        {
            try
            {
                RecognizeCelebritiesRequest request = new RecognizeCelebritiesRequest()
                {
                    Image = new Image()
                    {
                        Bytes = data
                    }
                };

                return(await rekognitionClient.RecognizeCelebritiesAsync(request));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(new RecognizeCelebritiesResponse());
            }
        }
Пример #12
0
        public async Task IdentifyCelebretiesTest()
        {
            var mockClient = new Mock <AmazonRekognitionClient>();

            mockClient.Setup(client => client.RecognizeCelebritiesAsync(
                                 It.IsAny <RecognizeCelebritiesRequest>(),
                                 It.IsAny <CancellationToken>()
                                 )).Returns((RecognizeCelebritiesRequest r, CancellationToken token) =>
            {
                return(Task.FromResult(new RecognizeCelebritiesResponse()
                {
                    HttpStatusCode = System.Net.HttpStatusCode.OK,
                }));
            });

            byte[] data = File.ReadAllBytes(_filename);

            RecognizeCelebritiesRequest request = new RecognizeCelebritiesRequest
            {
                Image = new Amazon.Rekognition.Model.Image
                {
                    Bytes = new MemoryStream(data),
                },
            };

            var client   = mockClient.Object;
            var response = await client.RecognizeCelebritiesAsync(request);

            bool gotResult = response is not null;

            Assert.True(gotResult, "RecognizeCelebritiesAsync returned a response.");

            bool ok = response.HttpStatusCode == System.Net.HttpStatusCode.OK;

            Assert.True(ok, $"Successfully searched image for celebrity faces.");

            Assert.False(response.CelebrityFaces.Count > 0, $"Found {response.CelebrityFaces.Count} celebrities.");
        }
        public string GetImageInfo(ImageData imageData, byte[] imgData = null)
        {
            try
            {
                var path = Path.Combine(
                    Directory.GetCurrentDirectory(), "wwwroot",
                    imageData.fileName);
                imgData    = Convert.FromBase64String(imageData.base64Data);
                _imageData = new MemoryStream(imgData);
                RecognizeCelebritiesRequest recognizeCelebrities = new RecognizeCelebritiesRequest()
                {
                    Image = new Image()
                    {
                        Bytes = _imageData
                    }
                };
                RecognizeCelebritiesResponse celebrity = _rekognitionClient.RecognizeCelebritiesAsync(recognizeCelebrities).Result;

                List <Celebrity> lstCelebrities = celebrity.CelebrityFaces;

                StringBuilder sbCelebrities = new StringBuilder();
                foreach (var item in lstCelebrities)
                {
                    sbCelebrities.Append(item.Name);
                    sbCelebrities.Append(',');
                }
                string Celebrities = sbCelebrities.ToString().TrimEnd(',');

                return(Celebrities);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
Пример #14
0
        /// <summary>
        /// Scans the contents of an image file looking for celebrities. If any
        /// are found, a bounding box will be drawn around the face and the name
        /// of the celebrity drawn under the box.
        /// </summary>
        /// <param name="client">The Rekognition client used to call
        /// RecognizeCelebritiesAsync.</param>
        /// <param name="filename">The name of the file that potentially
        /// contins faces.</param>
        public static async Task IdentifyCelebrityFaces(AmazonRekognitionClient client, string filename)
        {
            // Request needs image bytes, so read and add to request.
            byte[] data = File.ReadAllBytes(filename);

            RecognizeCelebritiesRequest request = new RecognizeCelebritiesRequest
            {
                Image = new Amazon.Rekognition.Model.Image
                {
                    Bytes = new MemoryStream(data),
                },
            };

            RecognizeCelebritiesResponse response = await client.RecognizeCelebritiesAsync(request);

            if (response.CelebrityFaces.Count > 0)
            {
                // Load a bitmap to modify with face bounding box rectangles.
                Bitmap facesHighlighted = new Bitmap(filename);
                Pen    pen      = new Pen(Color.Black, 3);
                Font   drawFont = new Font("Arial", 12);

                // Create a graphics context.
                using (var graphics = Graphics.FromImage(facesHighlighted))
                {
                    foreach (var fd in response.CelebrityFaces)
                    {
                        // Get the bounding box.
                        BoundingBox bb = fd.Face.BoundingBox;
                        Console.WriteLine($"Bounding box = ({bb.Left}, {bb.Top}, {bb.Height}, {bb.Width})");

                        // Draw the rectangle using the bounding box values.
                        // They are percentages so scale them to the picture.
                        graphics.DrawRectangle(
                            pen,
                            x: facesHighlighted.Width * bb.Left,
                            y: facesHighlighted.Height * bb.Top,
                            width: facesHighlighted.Width * bb.Width,
                            height: facesHighlighted.Height * bb.Height);
                        graphics.DrawString(
                            fd.Name,
                            font: drawFont,
                            brush: Brushes.White,
                            x: facesHighlighted.Width * bb.Left,
                            y: (facesHighlighted.Height * bb.Top) + (facesHighlighted.Height * bb.Height));
                    }
                }

                // Save the image with highlights as PNG.
                string fileout = filename.Replace(Path.GetExtension(filename), "_celebrityfaces.png");
                facesHighlighted.Save(fileout, System.Drawing.Imaging.ImageFormat.Png);

                Console.WriteLine($">>> {response.CelebrityFaces.Count} celebrity face(s) highlighted in file {fileout}.");

                Console.WriteLine("Found the following celebritie(s):");
                foreach (var celeb in response.CelebrityFaces)
                {
                    Console.WriteLine($"{celeb.Name}");
                }
            }
            else
            {
                Console.WriteLine(">>> No celebrity faces found");
            }
        }