public async Task <string> FaceAnalyzerAsync(IFormFile photoFile, string collectionID)
        {
            MemoryStream memoryStream = new MemoryStream();

            photoFile.CopyTo(memoryStream);

            IndexFacesRequest indexFacesRequest = new IndexFacesRequest
            {
                CollectionId        = collectionID,
                DetectionAttributes = detectionAttributes,
                MaxFaces            = maxFaces,
                QualityFilter       = qualityFilter,
                Image = new Image
                {
                    Bytes = memoryStream,
                }
            };

            IndexFacesResponse indexFacesResponse = await this._amazonRekognition.IndexFacesAsync(indexFacesRequest);

            if (indexFacesResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception(indexFacesResponse.HttpStatusCode.ToString());
            }

            if (indexFacesResponse.UnindexedFaces.Count > 0 || indexFacesResponse.FaceRecords.Count != 1)
            {
                throw new Exception("Unindexed Faces: " + indexFacesResponse.UnindexedFaces.Count + "\nIndexed Faces: " + indexFacesResponse.FaceRecords.Count);
            }

            return(JsonSerializer.Serialize(indexFacesResponse.FaceRecords[0].FaceDetail.Emotions));
        }
示例#2
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            IndexFacesResponse response = new IndexFacesResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("FaceModelVersion", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    response.FaceModelVersion = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("FaceRecords", targetDepth))
                {
                    var unmarshaller = new ListUnmarshaller <FaceRecord, FaceRecordUnmarshaller>(FaceRecordUnmarshaller.Instance);
                    response.FaceRecords = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("OrientationCorrection", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    response.OrientationCorrection = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return(response);
        }
示例#3
0
        /// <summary>
        /// Add All detected faces to a specific collection
        /// </summary>
        /// <param name="collectionId"></param>
        /// <param name="imageId"></param>
        /// <param name="image"></param>
        public FaceRecord AddImageToCollection(string collectionId, Amazon.Rekognition.Model.Image image)
        {
            AmazonRekognitionClient rekognitionClient = AmazonClient.GetInstance();

            //Validate that image contains only one face.
            DetectFacesResponse detectFacesResponse = rekognitionClient.DetectFaces(new Amazon.Rekognition.Model.DetectFacesRequest
            {
                Attributes = new List <string> {
                    "ALL"
                },
                Image = image
            });

            if (null != detectFacesResponse.FaceDetails && detectFacesResponse.FaceDetails.Count > 1)
            {
                throw new ArgumentNullException("Many faces in the image");
            }

            IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
            {
                Image               = image,
                CollectionId        = collectionId,
                DetectionAttributes = new List <String>()
                {
                    "ALL"
                }
            };

            IndexFacesResponse indexFacesResponse = rekognitionClient.IndexFaces(indexFacesRequest);

            return(indexFacesResponse.FaceRecords.FirstOrDefault());
        }
示例#4
0
        private List <FaceRecord> PopulateCollection()
        {
            Console.WriteLine("Populating collection {0}: ", CollectionName);
            List <FaceRecord> result = new List <FaceRecord>();

            foreach (var entry in DataSet.TargetImages)
            {
                Console.WriteLine("Processing image: {0}", entry.Key);
                MemoryStream stream = new MemoryStream();
                entry.Value.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

                Image requestImage = new Image()
                {
                    Bytes = stream
                };

                IndexFacesRequest request = new IndexFacesRequest()
                {
                    Image        = requestImage,
                    CollectionId = CollectionName
                };

                var watch = Stopwatch.StartNew();
                IndexFacesResponse response = Client.IndexFaces(request);
                watch.Stop();
                TimingResults.Add(new TimingModel("PopulateCollection", entry.Key, watch.ElapsedMilliseconds));
                IndexedFaces.Add(response);
                result.AddRange(response.FaceRecords);
            }

            Console.WriteLine("Detected {0} faces in {1} images.", result.Count, DataSet.TargetImages.Count);
            return(result);
        }
示例#5
0
        private static void IndexPhoto(string photo)
        {
            Console.WriteLine("Attempting to index S3 photo file " + photo);

            Image image = new Image()
            {
                S3Object = new S3Object()
                {
                    Bucket = bucket,
                    Name   = photo
                }
            };

            IndexFacesRequest request = new IndexFacesRequest()
            {
                Image               = image,
                CollectionId        = collectionId,
                ExternalImageId     = photo,
                DetectionAttributes = new List <String>()
                {
                    "ALL"
                }
            };

            IndexFacesResponse response = rekognitionClient.IndexFacesAsync(request).Result;

            Console.WriteLine(photo + " added");

            foreach (FaceRecord faceRecord in response.FaceRecords)
            {
                Console.WriteLine("Face detected: Faceid is " +
                                  faceRecord.Face.FaceId);
            }
        }
示例#6
0
        public static void AddFace(string _externalImageId, string _collectionId)
        {
            try
            {
                string photo        = _externalImageId;
                string collectionId = _collectionId;

                using (rekognitionClient = new AmazonRekognitionClient(collectionRegion))
                {
                    AddingFace();
                }

                void AddingFace()
                {
                    Image image = new Image()
                    {
                        S3Object = new S3Object()
                        {
                            Bucket = bucket,
                            Name   = photo
                        }
                    };

                    IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
                    {
                        Image               = image,
                        CollectionId        = collectionId,
                        ExternalImageId     = photo,
                        DetectionAttributes = new List <String>()
                        {
                            "ALL"
                        }
                    };

                    IndexFacesResponse indexFacesResponse = rekognitionClient.IndexFaces(indexFacesRequest);

                    Console.WriteLine(photo + " added");

                    foreach (FaceRecord faceRecord in indexFacesResponse.FaceRecords)
                    {
                        Console.WriteLine("Face detected: Faceid is " +
                                          faceRecord.Face.FaceId);
                    }
                }
            }
            catch (AmazonRekognitionException e)
            {
                Console.WriteLine("AmazonRekognitionException: " + e);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e);
            }
        }
示例#7
0
        public ActionResult Index(ImageTrainModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            try
            {
                using (Stream inputStream = model.File.InputStream)
                {
                    MemoryStream memoryStream = inputStream as MemoryStream;
                    if (memoryStream == null)
                    {
                        memoryStream = new MemoryStream();
                        inputStream.CopyTo(memoryStream);
                    }

                    var collectionsList = client.ListCollections(new ListCollectionsRequest {
                        MaxResults = 10
                    });
                    //client.CreateCollection(new CreateCollectionRequest
                    //{
                    //    CollectionId = "TrainedImages"
                    //});

                    IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
                    {
                        Image = new Image
                        {
                            Bytes = memoryStream
                        },
                        CollectionId        = "TrainedImages",
                        ExternalImageId     = model.Name,
                        DetectionAttributes = new List <String>()
                        {
                            "ALL"
                        }
                    };

                    IndexFacesResponse indexFacesResponse = client.IndexFaces(indexFacesRequest);
                    if (indexFacesResponse.HttpStatusCode == System.Net.HttpStatusCode.OK)
                    {
                        ViewBag.Message = "Image trained successfully";
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message.ToString();
            }
            return(View());
        }
示例#8
0
        /// <summary>
        /// This function add images to the dyFace Collection
        /// Function Name: "dyFaceRekognitionAddToCollection"
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <List <string> > AddToCollection(string input, ILambdaContext context)
        {
            AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();

            String        collectionId  = "dyFaceCollection";
            List <string> collectionIds = await GetCollections(rekognitionClient);

            List <string> reasons = new List <string>();

            //error handling
            if (!collectionIds.Contains(collectionId))
            {
                int createCollectionResponse = await CreateCollection(rekognitionClient, collectionId);

                if (createCollectionResponse < 200 || createCollectionResponse > 299)
                {
                    reasons.Add("Failure Creating Collection = " + createCollectionResponse);
                    return(reasons);
                }
            }

            IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
            {
                Image =
                {
                    S3Object   = new S3Object()
                    {
                        Bucket = "dyface-test-bucket",
                        Name   = input
                    }
                },
                CollectionId        = collectionId,
                ExternalImageId     = input,
                DetectionAttributes = new List <String>()
                {
                    "ALL"
                }
            };

            IndexFacesResponse indexFacesResponse = await rekognitionClient.IndexFacesAsync(indexFacesRequest);

            foreach (UnindexedFace unindexedFace in indexFacesResponse.UnindexedFaces)
            {
                reasons.Add(unindexedFace.Reasons.ToString());
            }

            return(reasons);
        }
示例#9
0
        public List <FaceRecord> Recognize(string collectionId, Amazon.Rekognition.Model.Image image)
        {
            //1- Detect faces in the input image and adds them to the specified collection.
            AmazonRekognitionClient rekognitionClient = AmazonClient.GetInstance();

            IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
            {
                Image               = image,
                CollectionId        = collectionId,
                DetectionAttributes = new List <String>()
                {
                    "DEFAULT"
                }
            };

            IndexFacesResponse indexFacesResponse = rekognitionClient.IndexFaces(indexFacesRequest);

            //2- Search all detected faces in the collection
            SearchFacesResponse searchFacesResponse = null;

            List <FaceRecord> matchedFaces = new List <FaceRecord>();

            if (null != indexFacesResponse && null != indexFacesResponse.FaceRecords && 0 != indexFacesResponse.FaceRecords.Count)
            {
                foreach (FaceRecord face in indexFacesResponse.FaceRecords)
                {
                    searchFacesResponse = rekognitionClient.SearchFaces(new SearchFacesRequest
                    {
                        CollectionId       = collectionId,
                        FaceId             = face.Face.FaceId,
                        FaceMatchThreshold = 70F,
                        MaxFaces           = 2
                    });

                    if (searchFacesResponse.FaceMatches != null && searchFacesResponse.FaceMatches.Count != 0)
                    {
                        matchedFaces.Add(face);
                    }
                }

                //Remove newly added faces to the collection

                _collectionService.RemoveFacesFromCollection(collectionId, indexFacesResponse.FaceRecords.Select(x => x.Face.FaceId).ToList());
            }

            return(matchedFaces);
        }
示例#10
0
        public async void Addface()
        {
            String collectionId = "faceCollection";
            String bucket       = "face-identify";
            String photo        = "BrotherP.jpg";

            string accessKey = "AKIAST4HFDODRNXMOAPJ";
            string secretKey = "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";

            AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(accessKey, secretKey, Amazon.RegionEndpoint.APSoutheast1);

            Image image = new Image()
            {
                S3Object = new S3Object()
                {
                    Bucket = bucket,
                    Name   = photo
                }
            };

            IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
            {
                Image               = image,
                CollectionId        = collectionId,
                ExternalImageId     = photo,
                DetectionAttributes = new List <String>()
                {
                    "ALL"
                }
            };

            IndexFacesResponse indexFacesResponse = await rekognitionClient.IndexFacesAsync(indexFacesRequest);

            Console.WriteLine(photo + " added");
            foreach (FaceRecord faceRecord in indexFacesResponse.FaceRecords)
            {
                Console.WriteLine("Face detected: Faceid is " +
                                  faceRecord.Face.FaceId);
            }
        }
示例#11
0
    public static void Example()
    {
        String collectionId = "MyCollection";
        String bucket       = "bucket";
        String photo        = "input.jpg";

        AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();

        Image image = new Image()
        {
            S3Object = new S3Object()
            {
                Bucket = bucket,
                Name   = photo
            }
        };

        IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
        {
            Image               = image,
            CollectionId        = collectionId,
            ExternalImageId     = photo,
            DetectionAttributes = new List <String>()
            {
                "ALL"
            }
        };

        IndexFacesResponse indexFacesResponse = rekognitionClient.IndexFaces(indexFacesRequest);

        Console.WriteLine(photo + " added");
        foreach (FaceRecord faceRecord in indexFacesResponse.FaceRecords)
        {
            Console.WriteLine("Face detected: Faceid is " +
                              faceRecord.Face.FaceId);
        }
    }
示例#12
0
        // snippet-start:[Rekognition.dotnetv3.AddFacesExample]
        public static async Task Main()
        {
            string collectionId = "MyCollection2";
            string bucket       = "doc-example-bucket";
            string photo        = "input.jpg";

            var rekognitionClient = new AmazonRekognitionClient();

            var image = new Image
            {
                S3Object = new S3Object
                {
                    Bucket = bucket,
                    Name   = photo,
                },
            };

            var indexFacesRequest = new IndexFacesRequest
            {
                Image               = image,
                CollectionId        = collectionId,
                ExternalImageId     = photo,
                DetectionAttributes = new List <string>()
                {
                    "ALL"
                },
            };

            IndexFacesResponse indexFacesResponse = await rekognitionClient.IndexFacesAsync(indexFacesRequest);

            Console.WriteLine($"{photo} added");
            foreach (FaceRecord faceRecord in indexFacesResponse.FaceRecords)
            {
                Console.WriteLine($"Face detected: Faceid is {faceRecord.Face.FaceId}");
            }
        }
示例#13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task FunctionHandler(S3Event input, ILambdaContext context)
        {
            // Initialize the Amazon Cognito credentials provider
            CognitoAWSCredentials credentials = new CognitoAWSCredentials(
                "us-east-1:6d711ae9-1084-4a71-9ef6-7551ca74ad0b", // Identity pool ID
                RegionEndpoint.USEast1                            // Region
                );

            dynamoDbClient = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1);
            Table customersTbl = Table.LoadTable(dynamoDbClient, "Customer");


            AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
            IAmazonS3 s3Client = new AmazonS3Client(RegionEndpoint.USEast2);

            //Debug.WriteLine("Creating collection: " + FACE_COLLECTION_ID);
            //CreateCollectionRequest createCollectionRequest = new CreateCollectionRequest()
            //{
            //    CollectionId = FACE_COLLECTION_ID
            //};

            //CreateCollectionResponse createCollectionResponse = rekognitionClient.CreateCollectionAsync(createCollectionRequest).Result;
            //Debug.WriteLine("CollectionArn : " + createCollectionResponse.CollectionArn);
            //Debug.WriteLine("Status code : " + createCollectionResponse.StatusCode);


            foreach (var record in input.Records)
            {
                //if(!SupportedImageTypes.Contains(Path.GetExtension(record.S3.Object.Key)))
                //{
                //    Debug.WriteLine($"Object {record.S3.Bucket.Name}:{record.S3.Object.Key} is not a supported image type");
                //    continue;
                //}

                Image image = new Image()
                {
                    S3Object = new Amazon.Rekognition.Model.S3Object
                    {
                        Bucket = record.S3.Bucket.Name,
                        Name   = record.S3.Object.Key
                    }
                };

                GetObjectTaggingResponse taggingResponse = s3Client.GetObjectTaggingAsync(
                    new GetObjectTaggingRequest
                {
                    BucketName = record.S3.Bucket.Name,
                    Key        = record.S3.Object.Key
                }
                    ).Result;

                Tag customerID = taggingResponse.Tagging[0];//TODO: HARDCODING!!


                IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
                {
                    Image               = image,
                    CollectionId        = FACE_COLLECTION_ID,
                    ExternalImageId     = record.S3.Object.Key,
                    DetectionAttributes = new List <String>()
                    {
                        "ALL"
                    }
                };

                IndexFacesResponse indexFacesResponse = rekognitionClient.IndexFacesAsync(indexFacesRequest).Result;

                Debug.WriteLine(record.S3.Object.Key + " added");
                foreach (FaceRecord faceRecord in indexFacesResponse.FaceRecords)
                {
                    Debug.WriteLine("Face detected: Faceid is " + faceRecord.Face.FaceId);

                    Console.WriteLine("\nAfter Indexing, Updating FaceID of the Customer....");
                    string partitionKey = customerID.Value;

                    var customer = new Document();
                    customer["Id"] = Int32.Parse(partitionKey);
                    // List of attribute updates.
                    // The following replaces the existing authors list.
                    customer["FaceId"] = faceRecord.Face.FaceId;

                    // Optional parameters.
                    UpdateItemOperationConfig config = new UpdateItemOperationConfig
                    {
                        // Get updated item in response.
                        ReturnValues = ReturnValues.AllNewAttributes
                    };
                    Document updatedCustomer = customersTbl.UpdateItemAsync(customer, config).Result;
                    Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ...");
                    PrintDocument(updatedCustomer);
                }
            }
            return;
        }
示例#14
0
        public ActionResult IndexFaceUpload(Arquivo arquivo, string Nome)
        {
            try
            {
                string Semelhanca = string.Empty;
                string input      = string.Empty;

                HttpPostedFileBase arquivoPostado = null;
                foreach (string fileInputName in Request.Files)
                {
                    var nome = arquivo.NomeLocal;

                    arquivoPostado = Request.Files[fileInputName];


                    var target = new MemoryStream();
                    arquivoPostado.InputStream.CopyTo(target);
                    arquivo.Conteudo        = target.ToArray();
                    arquivo.UsuarioInclusao = CustomAuthorizationProvider.UsuarioAutenticado.Login;
                    arquivo.DataInclusao    = DateTime.Now;
                    arquivo.Extensao        = Path.GetExtension(arquivoPostado.FileName);
                    arquivo.NomeLocal       = arquivoPostado.FileName;

                    byte[] inputImageData   = arquivo.Conteudo;
                    var    inputImageStream = new MemoryStream(inputImageData);

                    var item = arquivo.Conteudo;

                    input = Nome.Trim().Replace(" ", "") + ".jpg";


                    var rekognitionClient = new AmazonRekognitionClient("AKIAIBLZ7KFAN6XG3NNA", "2nukFOTDN0zv/y2tzeCiLrAHM5TwbFgvEqqZA9zn", RegionEndpoint.USWest2);

                    Image image = new Image()
                    {
                        Bytes = inputImageStream
                    };

                    IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
                    {
                        Image               = image,
                        CollectionId        = "Encel",
                        ExternalImageId     = input,
                        DetectionAttributes = new List <String>()
                        {
                            "ALL"
                        }
                    };

                    try
                    {
                        IndexFacesResponse indexFacesResponse = rekognitionClient.IndexFaces(indexFacesRequest);
                    }
                    catch (Exception)
                    {
                        throw new Exception("Imagem não Indexada!");
                    }
                }

                if (input != null)
                {
                    return(Json(new { sucesso = "O Empregado '" + input + "' foi analisado com êxito." }));
                }
                else
                {
                    return(Json(new { sucesso = "Empregado não encontrado!" }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { erro = ex.Message }));
            }
        }