Esempio n. 1
0
        public async Task DetectFacesAsync(bool detectFaceAttributes = false, bool detectFaceLandmarks = false)
        {
            try
            {
                if (this.GetImageStreamCallback != null)
                {
                    Stream imageStream = await this.GetImageStreamCallback();

                    string imageUrl = await new AzureStorageUploadFiles().UploadImageStreamAsync(imageStream, "LogAttendance", "jpg");

                    if (imageUrl == null || string.IsNullOrEmpty(imageUrl))
                    {
                        return;
                    }

                    DetectFaceModel detectFaceModel = new DetectFaceModel();
                    detectFaceModel.ImageWidth    = imageWidth;
                    detectFaceModel.ImageHeight   = imageHeight;
                    detectFaceModel.ImageUrl      = imageUrl;
                    detectFaceModel.CameraIPAdres = CameraIPAdres;
                    detectFaceModel.CaptureTime   = CaptureTime;
                    detectFaceModel.ListFaces     = JsonConvert.DeserializeObject <IEnumerable <FaceBox> >(ListDetectedFaceJson);

                    //Gửi Messages lên service bus
                    ServiceBusFuntion <DetectFaceModel> serviceBusSender = new ServiceBusFuntion <DetectFaceModel>();
                    await serviceBusSender.SendMessagesAsync(detectFaceModel);
                }
                return;
            }
            catch (Exception e)
            {
                this.DetectedFaces = Enumerable.Empty <Face>();
            }
        }
Esempio n. 2
0
        public async Task <HttpResponseMessage> DetectFace()
        {
            string imageLink = string.Empty;

            try
            {
                var                modelJson       = HttpContext.Current.Request.Form["Model"];
                DetectFaceModel    detectFaceModel = JsonConvert.DeserializeObject <DetectFaceModel>(modelJson);
                HttpFileCollection hfc             = HttpContext.Current.Request.Files;
                if (hfc.Count > 0)
                {
                    detectFaceModel.ImageStream  = hfc[0].InputStream;
                    detectFaceModel.LogImageLink = imageLink = UploadFileServer.UploadFileJPG(hfc[0], Constants.FolderLogAttendance);
                }
                var ipClient = GetIpClient.GetClientIpAddress(Request);
                detectFaceModel.ClientIPAddress = ipClient;
                DetectFaceResultModel result = await faceHelperBusiness.DetectFace(detectFaceModel);

                return(Request.CreateResponse(HttpStatusCode.OK, result));
            }
            catch (Exception ex)
            {
                UploadFileServer.DeleteFile(imageLink);
                logger.Error(ex.Message, ex.InnerException);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Esempio n. 3
0
        public async static void Run([ServiceBusTrigger("face-detection", AccessRights.Manage, Connection = "ServiceBusConnection")] string mySbMsg, TraceWriter log)
        {
            string str = "Time Attendance: Queue Receive Face Detection";

            try
            {
                DetectFaceModel detectFaceModel = JsonConvert.DeserializeObject <DetectFaceModel>(mySbMsg);

                FaceHelperBusiness faceHelperBusiness = new FaceHelperBusiness();

                //log.Info($"{"Bat dau ghep Face: "} processed message: {DateTime.Now.ToString("HH:mm:ss:fff")}", null);
                ////Ghép face từ ảnh lớn
                //Stream imageStream = await faceHelperBusiness.MergingImage(detectFaceModel.ImageUrl, detectFaceModel.ImageWidth, detectFaceModel.ImageHeight, detectFaceModel.ListFaces);
                //log.Info($"{"Ket thuc ghep Face: "} processed message: {DateTime.Now.ToString("HH:mm:ss:fff")}", null);

                if (!string.IsNullOrEmpty(detectFaceModel.ImageUrl))
                {
                    //Detect face
                    //imageStream.Position = 0;
                    //log.Info($"{"Bat dau DetectFace Stream: "} processed message: {DateTime.Now.ToString("HH:mm:ss:fff")}", null);
                    //Face[] listFace = await faceHelperBusiness.DetectFaceAsync(imageStream);
                    //log.Info($"{"Ket thuc DetectFace Stream: "} processed message: {DateTime.Now.ToString("HH:mm:ss:fff")}", null);

                    //log.Info($"{"Bat dau DetectFace URL: "} processed message: {DateTime.Now.ToString("HH:mm:ss:fff")}", null);
                    Face[] listFace = await faceHelperBusiness.DetectFaceAsync(ConfigurationManager.AppSettings["UrlHostImage"] + ConfigurationManager.AppSettings["StorageContainer"] + "/" + detectFaceModel.ImageUrl);

                    //log.Info($"{"Ket tuc DetectFace URL: "} processed message: {DateTime.Now.ToString("HH:mm:ss:fff")}", null);

                    if (listFace != null && listFace.Length > 0)
                    {
                        DetectFaceResultModel resultModel = new DetectFaceResultModel()
                        {
                            LogImageLink = detectFaceModel.ImageUrl,
                            CaptureTime  = detectFaceModel.CaptureTime
                        };

                        resultModel.ListIdentifyResult = await faceHelperBusiness.IdentifyPerson(listFace.Select(r => r.FaceId).ToArray());

                        //Đẩy service bus chấm công
                        ServiceBusSetting setting = new ServiceBusSetting()
                        {
                            ConnectionString = ConfigurationManager.AppSettings["ServiceBusConnection"],
                            QueueName        = ConfigurationManager.AppSettings["AttendanceQueueName"],
                        };
                        ServiceBusSender <DetectFaceResultModel> serviceBusSender = new ServiceBusSender <DetectFaceResultModel>(setting);
                        await serviceBusSender.SendMessagesAsync(resultModel);
                    }
                }

                log.Info($"{str} processed message: {mySbMsg}", null);
            }
            catch (Exception exception)
            {
                log.Error($"Failed in {str}: {exception.Message}", exception, null);
            }
        }
Esempio n. 4
0
        public async Task <DetectFaceResultModel> DetectFace(DetectFaceModel detectFaceModel)
        {
            //detectFaceResultModel = new DetectFaceResultModel();
            //try
            //{
            //    DateTime start = DateTime.Now;
            //    List<IdentifiedPerson> resultPersons = new List<IdentifiedPerson>();
            //    modelTransactionLog = new TransactionLog()
            //    {
            //        TransactionLogId = Guid.NewGuid().ToString(),
            //        ClientIPAddress = detectFaceModel.ClientIPAddress,
            //        CameraIPAdress = detectFaceModel.CameraIPAdres,
            //        Date = start,
            //        CallDateTime = start,
            //        ImageLink = detectFaceModel.LogImageLink,
            //    };

            //    if (detectFaceModel.ListFaces != null && detectFaceModel.ListFaces.Count() > 0)
            //    {

            //        List<string> faceImagesUrl = new List<string>();
            //        Bitmap imgCrop = new Bitmap(detectFaceModel.ImageUrl);

            //        List<ImageCropModel> listImageCrop = new List<ImageCropModel>();
            //        foreach (FaceBox face in detectFaceModel.ListFaces)
            //        {
            //            int width, height, xStartPosition, yStartPosition;
            //            EnlargeFaceBoxSize(face, detectFaceModel.ImageWidth, detectFaceModel.ImageHeight, out width, out height, out xStartPosition,
            //                out yStartPosition);

            //            Image imageFace = imgCrop.Clone(new Rectangle(xStartPosition, yStartPosition, width, height), imgCrop.PixelFormat);

            //            listImageCrop.Add(new ImageCropModel()
            //            {
            //                ImageCrop = imageFace,
            //                Width = width,
            //                Height = height
            //            });
            //        }

            //        Bitmap imgMerging = new Bitmap(listImageCrop.Sum(r => r.Width) + (listImageCrop.Count() - 1) * 5, listImageCrop.Max(r => r.Height));
            //        Graphics grpMerging = Graphics.FromImage(imgMerging);
            //        int startPoint = 0;
            //        foreach (var itemImage in listImageCrop)
            //        {
            //            grpMerging.DrawImage(itemImage.ImageCrop, new Point(startPoint, 0));
            //            //Giữa 2 Face cách nhau 5px
            //            startPoint += itemImage.Width + 5;
            //        }
            //        grpMerging.Save();
            //        imgMerging.Save(detectFaceModel.ImageStream, ImageFormat.Bmp);
            //        detectFaceModel.ImageStream.Position = 0;
            //        ////Lưu ảnh để kiểm tra khi Debug
            //        //FaceVipService.CoreUtil.SaveImageStream(imgMerging, Constants.FolderImageFace, "MergingFace_");
            //        //AzureStorageUploadFiles.GetInstance().UploadPhoto(imgMerging, hfc[i].FileName, Constants.FolderEmployee);
            //        detectFaceResultModel.DetectedFaces = Task.Run(async () =>
            //        {
            //            return await FaceServiceHelper.DetectAsync(detectFaceModel.ImageStream, true, false, null);
            //        }).Result;
            //    }

            //    modelTransactionLog.ResponseDateTime = DateTime.Now;
            //    var ss = modelTransactionLog.ResponseDateTime - modelTransactionLog.CallDateTime;
            //    modelTransactionLog.ResponseTime = ss.Value.TotalMilliseconds;
            //    if (detectFaceResultModel.DetectedFaces != null && detectFaceResultModel.DetectedFaces.Count() > 0)
            //    {
            //        Guid[] detectedFaceIds = detectFaceResultModel.DetectedFaces?.Select(f => f.FaceId).ToArray();
            //        if (detectedFaceIds != null && detectedFaceIds.Any())
            //        {

            //            IdentifyResult[] groupResults;
            //            IdentifiedPerson alreadyIdentifiedPerson;
            //            Candidate candidate;
            //            try
            //            {
            //                groupResults = await FaceServiceHelper.IdentifyAsync(FaceServiceHelper.GroupTimeAttendance, detectedFaceIds);
            //                foreach (var match in groupResults)
            //                {
            //                    if (!match.Candidates.Any())
            //                    {
            //                        resultPersons.Add(new IdentifiedPerson
            //                        {
            //                            Confidence = 0,
            //                            FaceId = match.FaceId,
            //                            InfoEmployee = null,
            //                            Note = JsonConvert.SerializeObject(detectFaceResultModel.DetectedFaces.Where(r => r.FaceId.Equals(match.FaceId)).FirstOrDefault())
            //                        });
            //                        continue;
            //                    }

            //                    candidate = match.Candidates[0];
            //                    alreadyIdentifiedPerson = resultPersons.FirstOrDefault(p => p.Person.PersonId == candidate.PersonId);
            //                    //Trường hợp tồn tại cập nhật
            //                    if (alreadyIdentifiedPerson != null)
            //                    {
            //                        // We already tagged this person in another group. Replace the existing one if this new one if the confidence is higher.
            //                        if (alreadyIdentifiedPerson.Confidence < candidate.Confidence)
            //                        {
            //                            alreadyIdentifiedPerson.Confidence = candidate.Confidence;
            //                        }
            //                    }
            //                    //Không tồn tại thêm mới
            //                    else
            //                    {
            //                        alreadyIdentifiedPerson = new IdentifiedPerson
            //                        {
            //                            Confidence = match.Candidates[0].Confidence,
            //                            FaceId = match.FaceId,
            //                            InfoEmployee = TimeAttendanceStatic.ListInfoEmployee.Where(r => r.FaceId.Equals(candidate.PersonId.ToString())).FirstOrDefault(),
            //                            Note = JsonConvert.SerializeObject(detectFaceResultModel.DetectedFaces.Where(r => r.FaceId.Equals(match.FaceId)).FirstOrDefault())
            //                        };
            //                        if (alreadyIdentifiedPerson.InfoEmployee != null)
            //                            alreadyIdentifiedPerson.Person = new Person() { Name = alreadyIdentifiedPerson.InfoEmployee.Name, PersonId = candidate.PersonId };
            //                        else
            //                            alreadyIdentifiedPerson.Person = new Person() { Name = "Unknown", PersonId = candidate.PersonId };

            //                        resultPersons.Add(alreadyIdentifiedPerson);
            //                    }
            //                }
            //            }
            //            catch (Exception e)
            //            {
            //            }

            //            //log chấm công
            //            if (resultPersons != null && resultPersons.Count() > 0)
            //            {
            //                await this.LogTimeAttendance(db, resultPersons.Where(r => r.Confidence >= TimeAttendanceStatic.ConfidenceFix / 100).ToList(), detectFaceModel.CaptureTime, detectFaceModel.LogImageLink);
            //            }
            //            detectFaceResultModel.IdentifiedPersons = resultPersons.Where(r => r.Confidence > 0).ToList();
            //        }
            //    }
            //    else
            //    {
            //        resultPersons.Add(new IdentifiedPerson() { Note = "NotFace" });
            //    }
            //    //log vao Attendance
            //    await this.LogAttendance(db, resultPersons, start, detectFaceModel.LogImageLink);

            //    modelTransactionLog.StatusCode = "200";
            //    db.TransactionLog.Add(modelTransactionLog);
            //    db.SaveChanges();
            //}
            //catch (Exception ex)
            //{
            //    modelTransactionLog.StatusCode = ex.Source;
            //    throw ex;
            //}



            //return detectFaceResultModel;
            return(null);
        }