public void FaceDeleteTest() { var groupId = "EE"; var userId = "HuangGuangyi2"; var jObj = FaceApi.FaceDelete(userId, groupId); }
public void showSingleAlertDialog() { List <Group> groupList = FaceApi.getInstance().getGroupList(0, 1000); if (groupList.Count <= 0) { Toast.MakeText(this, "还没有分组,请创建分组并添加用户", ToastLength.Short).Show(); return; } items = new String[groupList.Count]; for (int i = 0; i < groupList.Count; i++) { Group group = groupList[i]; items[i] = group.getGroupId(); } AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("请选择分组groupID"); // alertBuilder.SetSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() { // public override void OnClick(DialogInterface arg0, int index) // { // Toast.MakeText(this, items[index], ToastLength.Short.Show(); // choiceIdentityType(items[index]); // alertDialog.dismiss(); // } //}); alertDialog = alertBuilder.Create(); alertDialog.Show(); }
public void GetUserInfoTest() { var groupId = "EE"; var userId = "HuangGuangyi2"; var jObj = FaceApi.GetUserInfo(userId, groupId); }
public ActionResult Detect(FaceApi faceApi) { var faces = FaceDetect(faceApi.Url); faceApi.Faces = faces; return(View(faceApi)); }
public void GetGroupsTest() { var options = new GetActionOption() { Start = 0, Length = 100, }; var jObj = FaceApi.GetGroups(options); }
public FaceDetectWindowViewModel() { AbrirFoto1 = new DelegateCommand(AbrirFoto1Async); AbrirFoto2 = new DelegateCommand(AbrirFoto2Async); Comparar = new DelegateCommand(CompararAsync); SubirAlGrupo = new DelegateCommand(SubirAlGrupoAsync); BuscarEnGrupo = new DelegateCommand(BuscarEnGrupoAsync); faceApi = new FaceApi(); }
private void SoundImageButton_Click(object sender, RoutedEventArgs e) { if (_faceLogin) { btnSingle.IsEnabled = false; try { if (faceApi == null) { dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Tick += DispatcherTimer_Tick; dispatcherTimer.Interval = TimeSpan.FromMinutes(1); faceApi = new FaceApi(); ConfigHelper.GetSysConfig(); DBHelper.SetDBSource(); faceApi.Init(ConfigHelper.CameraIndex, ConfigHelper.DetectStyle, ConfigHelper.RecogStyle, ConfigHelper.Similarity, ConfigHelper.Diversity); reader = new SpeechSynthesizer(); reader.SelectVoice(ConfigHelper.Voice); } faceApi.LstFaceInformation = DBHelper.GetLstFaceInformation(); if (faceApi.LstFaceInformation == null) { ModernDialog.ShowMessage("访问数据库异常!", "提示", MessageBoxButton.OK); return; } faceApi.GetImageEvent += FaceApi_GetImageEvent; faceApi.FaceRecogFinishedEvent += FaceApi_FaceRecogFinishedEvent; faceApi.Start(); dispatcherTimer.Start(); ImagePhoto.Visibility = Visibility.Visible; } catch (Exception ee) { ModernDialog.ShowMessage("人脸识别始化失败:" + ee.Message, "提示", MessageBoxButton.OK); if (faceApi != null) { faceApi.Dispose(); } faceApi = null; btnSingle.IsEnabled = true; ImagePhoto.Visibility = Visibility.Collapsed; } } else { ((MainPageViewModel)DataContext).NavigateCommand.Execute("ProgramPage"); } }
public void UploadAndStreamDetectFace() { var imagePath = @"C:\Users\Administrator\Desktop\my.jpg"; //@"E:\Senparc\AzureDemo\WebSite\Senparc.Web\Upload\Emotion\happy.jpg"; var faces = FaceApi.UploadAndStreamDetectFace(imagePath); Assert.IsNotNull(faces); foreach (var item in faces) { Console.WriteLine($"========Face:{item.FaceAttributes.ToJson()}"); } }
public void SearchFaceTest() { var image = Bitmap.FromFile(@"Ego.jpg"); var groupIds = new string[] { "EE" }; var option = new SearchFaceOption() { Max_User_Num = 10, }; var jObj = FaceApi.FaceSearch(new Bitmap(image), groupIds, option); image.Dispose(); }
public void FaceDetectTest() { var image = Bitmap.FromFile(@"Ego.jpg"); var options = new List <FaceDetectOptions>() { }; var jObj = FaceApi.FaceDetect(new Bitmap(image), options, 1); image.Dispose(); }
public void FaceRegisterTest() { var image = Bitmap.FromFile(@"Ego.jpg"); var groupId = "EE"; var userId = "HuangGuangyi3"; var option = new FaceOption() { User_Info = "hhhhhhhhhhhhhhh" }; var jObj = FaceApi.FaceRegister(new Bitmap(image), groupId, userId, option); image.Dispose(); }
public void FaceUpdat2eTest() { var image = Bitmap.FromFile(@"Elise.jpg"); var groupId = "EE"; var userId = "Elise"; var option = new FaceOption() { User_Info = "高小娜 新娘 请就坐1号桌." }; var jObj = FaceApi.FaceUpdate(new Bitmap(image), groupId, userId, option); image.Dispose(); }
private void loadFeature2Memery() { if (identityStatus != FEATURE_DATAS_UNREADY) { return; } es.Submit(new Runnable(() => { Thread.CurrentThread().setPriority(Thread.MaxPriority); // android.os.Process.setThreadPriority (-4); FaceApi.getInstance().loadFacesFromDB(groupId); toast("人脸数据加载完成,即将开始1:N"); int count = FaceApi.getInstance().getGroup2Facesets().get(groupId).size(); displayTip("底库人脸个数:" + count, facesetsCountTv); identityStatus = IDENTITY_IDLE; })); }
public string Post([FromBody] Person person) { string appKey = ConfigurationManager.AppSettings["appKey"]; var faceApi = new FaceApi() { SubscriptionKey = "", GroupName = "", }; var task = Task.Run(() => { var personIdJson = faceApi.createPerson(person.Name).Result; PersonId personId = JsonConvert.DeserializeObject <PersonId>(personIdJson); var res = faceApi.addPersonFace(personId.Id, person.FaceImgUrl); faceApi.trainPersonFace(); return(res); }); return(task.Result); }
private void identity(ImageFrame imageFrame, FaceInfo faceInfo) { float raw = Java.Lang.Math.Abs(faceInfo.HeadPose[0]); float patch = Java.Lang.Math.Abs(faceInfo.HeadPose[1]); float roll = Java.Lang.Math.Abs(faceInfo.HeadPose[2]); // 人脸的三个角度大于20不进行识别 if (raw > 20 || patch > 20 || roll > 20) { return; } identityStatus = IDENTITYING; long starttime = DateTime.Now.Millisecond; int[] argb = imageFrame.getArgb(); int rows = imageFrame.getHeight(); int cols = imageFrame.getWidth(); int[] landmarks = faceInfo.Landmarks.ToArray(); int type = PreferencesUtil.getInt(GlobalFaceTypeModel.TYPE_MODEL, GlobalFaceTypeModel.RECOGNIZE_LIVE); IdentifyRet identifyRet = null; if (type == GlobalFaceTypeModel.RECOGNIZE_LIVE) { identifyRet = FaceApi.getInstance().identity(argb, rows, cols, landmarks, groupId); } else if (type == GlobalFaceTypeModel.RECOGNIZE_ID_PHOTO) { identifyRet = FaceApi.getInstance().identityForIDPhoto(argb, rows, cols, landmarks, groupId); } if (identifyRet != null) { displayUserOfMaxScore(identifyRet.getUserId(), identifyRet.getScore()); } identityStatus = IDENTITY_IDLE; displayTip("特征抽取对比耗时:" + (DateTime.Now.Millisecond - starttime), featureDurationTv); }
private void Button_Start_Click(object sender, EventArgs e) { Settings.Default.apiKey = this.textBox_apiKey.Text.Trim(); Settings.Default.secretKey = this.textBox_secretKey.Text.Trim(); Settings.Default.idCardPath = this.textBox_idCardPath.Text.Trim(); Settings.Default.Save(); FaceApi faceApi = new FaceApi(); faceApi.Init(Settings.Default.apiKey, Settings.Default.secretKey); // 定时截屏比对 Task.Factory.StartNew(() => { LogInvoke li = new LogInvoke(WriteLog); while (true) { if (_cts.IsCancellationRequested) { break; } try { var img = this.VideoPlayer.GetCurrentVideoFrame(); if (img != null) { var image1 = Convert.ToBase64String((byte[])new ImageConverter().ConvertTo(img, typeof(byte[]))); img.Dispose(); var image2 = Convert.ToBase64String(File.ReadAllBytes(Settings.Default.idCardPath)); _detectResult = faceApi.Detect(image1); if (_detectResult.error_code == 0) { BeginInvoke(li, new object[] { $"人脸数量:{_detectResult.result.face_num}" }); var result2 = faceApi.Match(image1, image2); if (result2.error_code == 0) { BeginInvoke(li, new object[] { $"比对分数:{result2.result.score}" }); } else { BeginInvoke(li, new object[] { $"比对分数:{result2.error_msg}" }); } } else { BeginInvoke(li, new object[] { $"人脸数量:{_detectResult.error_msg}" }); } } } catch (Exception ex) { BeginInvoke(li, new object[] { ex.Message }); } finally { Thread.Sleep(100); } } }, _cts.Token); WriteLog("启动完成"); }
private FaceApi PostMethod(string request, IDictionary<string, string> param) { string result; var url = ApiServer + request; var paramQS = HttpBuildQuery(param); var req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; string filename; if (param.TryGetValue("_file", out filename)) { string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); req.ContentType = "multipart/form-data; boundary=" + boundary; req.KeepAlive = true; req.Credentials = System.Net.CredentialCache.DefaultCredentials; var memStream = new MemoryStream(); var boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); var formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; foreach (var formitembytes in param.Select(s => string.Format(formdataTemplate, s.Key, s.Value)).Select(formitem => System.Text.Encoding.UTF8.GetBytes(formitem))) { memStream.Write(formitembytes, 0, formitembytes.Length); } memStream.Write(boundarybytes, 0, boundarybytes.Length); const string headerTemplate = "Content-Disposition: form-data; name=\"_file\"; filename=\"_files\"\r\n Content-Type: application/octet-stream\r\n\r\n"; var header = string.Format(headerTemplate, "file1", filename); var headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); var fileStream = new FileStream(filename.Replace("@", ""), FileMode.Open, FileAccess.Read); var buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } memStream.Write(boundarybytes, 0, boundarybytes.Length); fileStream.Close(); req.ContentLength = memStream.Length; var requestStream = req.GetRequestStream(); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); var response = (HttpWebResponse)req.GetResponse(); var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); response.Close(); reader.Close(); reader.Dispose(); } else { req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = paramQS.Length; req.GetRequestStream().Write(Encoding.UTF8.GetBytes(paramQS), 0, paramQS.Length); req.GetRequestStream().Close(); var response = (HttpWebResponse)req.GetResponse(); var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); response.Close(); reader.Close(); reader.Dispose(); } FaceApi fd = null; if (_format == "json") { var jss = new JavaScriptSerializer(); fd = jss.Deserialize<FaceApi>(result); fd.RawData = result; } if (_format == "xml") { //fd = DeserializeObject<FaceRestAPI.FaceAPI>(result); fd = new FaceApi {RawData = result}; } return fd; }
public void Init() { instance = new FaceApi(); }
public void run() { if (score < 80) { scoreTv.setText(""); matchUserTv.setText(""); matchAvatorIv.setImageBitmap(null); return; } if (userIdOfMaxScore.equals(userId)) { if (score < maxScore) { scoreTv.setText("" + score); } else { maxScore = score; userOfMaxSocre.setText("userId:" + userId + "\nscore:" + score); scoreTv.setText(String.valueOf(maxScore)); } if (matchUserTv.getText().toString().length() > 0) { return; } } else { userIdOfMaxScore = userId; maxScore = score; } scoreTv.setText(String.valueOf(maxScore)); User user = FaceApi.getInstance().getUserInfo(groupId, userId); if (user == null) { return; } matchUserTv.setText(user.getUserInfo()); List <Feature> featureList = user.getFeatureList(); if (featureList != null && featureList.size() > 0) { // featureTv.setText(new String(featureList.get(0).getFeature())); File faceDir = FileUitls.getFaceDirectory(); if (faceDir != null && faceDir.exists()) { File file = new File(faceDir, featureList.get(0).getImageName()); if (file != null && file.exists()) { Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); matchAvatorIv.setImageBitmap(bitmap); } } } // List<Feature> featureList = DBManager.getInstance().queryFeatureByUeserId(userId); // if (featureList != null && featureList.size() > 0) { // File faceDir = FileUitls.getFaceDirectory(); // if (faceDir != null && faceDir.exists()) { // File file = new File(faceDir, featureList.get(0).getImageName()); // if (file != null && file.exists()) { // Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); // testView.setImageBitmap(bitmap); // } // } // } }
public static bool RemoveGuest(string userId) { var jObj = FaceApi.DeleteUser(userId, GlobalConfigs.Configurations.GroupId); return(jObj != null && jObj.error_code == 0); }
public static bool SaveOrUpdateFace(GuestInfo info) { bool success = false; try { if (string.IsNullOrEmpty(info.Id)) { info.Id = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper(); } var guest = GlobalConfigs.Guests.FirstOrDefault(x => x.Id == info.Id); string imageFileName = null; if (!string.IsNullOrEmpty(info.ImagePath) && (info.ImagePath != guest?.ImagePath || guest == null)) { imageFileName = Path.Combine($"GuestImages\\{info.Id}.jpg"); var img = Bitmap.FromFile(info.ImagePath); var option = new FaceOption() { User_Info = $"姓名: {info.Name} \n身份: {info.Labels}\n桌号: {info.TableNo} ", }; var jObj = FaceApi.FaceSaveOrUpdate(new Bitmap(img), GlobalConfigs.Configurations.GroupId, guest != null ? guest.Id : info.Id, option); success = (jObj != null && jObj.error_code == 0); if (success) { var newImage = new Bitmap(img); img.Dispose(); if (File.Exists(imageFileName)) { File.Delete(imageFileName); } newImage.Save(imageFileName, ImageFormat.Jpeg); newImage.Dispose(); } } else { success = true; } if (success) { var entourageText = info.Entourage ?? ""; var entourages = entourageText.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); var entourageNum = entourages.Count(); if (guest == null)//新增 { GlobalConfigs.Guests.Add(new ee.Models.GuestInfo() { Id = info.Id, Name = info.Name, FullName = info.Name, Gender = info.Gender, GuestType = info.GuestType, Entourage = entourageText, EntourageNum = entourageNum, Labels = info.Labels, TableNo = info.TableNo, ImagePath = imageFileName, CashGift = info.CashGift, CreateTime = DateTime.Now, }); if (entourages != null) { foreach (var item in entourages) { GlobalConfigs.Guests.Add(new ee.Models.GuestInfo() { Id = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper(), ParentId = info.Id, Name = $"{item}", FullName = $"{info.Name}_{item}", Gender = 0, GuestType = info.GuestType, Entourage = "", EntourageNum = 0, Labels = $"{info.Name} 随行人员", TableNo = info.TableNo, ImagePath = null, CreateTime = DateTime.Now, }); } } } else { var oldName = guest.Name; guest.Name = info.Name; guest.Gender = info.Gender; guest.GuestType = info.GuestType; guest.Labels = info.Labels; guest.TableNo = info.TableNo; guest.ImagePath = imageFileName; guest.CashGift = info.CashGift; guest.CreateTime = DateTime.Now; if (guest.Entourage != info.Entourage) { GlobalConfigs.Guests.RemoveAll(x => x.ParentId == info.Id); guest.Entourage = entourageText; guest.EntourageNum = entourageNum; if (entourages != null) { foreach (var item in entourages) { GlobalConfigs.Guests.Add(new ee.Models.GuestInfo() { Id = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper(), ParentId = info.Id, Name = $"{item}", FullName = $"{info.Name}_{item}", Gender = 0, GuestType = info.GuestType, Entourage = "", EntourageNum = 0, Labels = $"{info.Name} 随行人员", TableNo = info.TableNo, ImagePath = null, IsAttend = guest.IsAttend, AttendTime = guest.AttendTime, CreateTime = DateTime.Now, }); } } } #region 关联更新 var parent = GlobalConfigs.Guests.FirstOrDefault(x => x.Id == guest.ParentId); if (parent != null && !string.IsNullOrEmpty(parent.Entourage)) { var pEntourages = parent.Entourage.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); for (var i = 0; i < pEntourages.Length; i++) { if (pEntourages[i] == oldName) { pEntourages[i] = guest.Name; } } parent.Entourage = string.Join(",", pEntourages); parent.EntourageNum = pEntourages.Count(); guest.FullName = $"{parent.Name}_{guest.Name}"; } #endregion } GlobalConfigMgr.SaveGuests(); } return(success); } catch (Exception ex) { return(false); } }
private bool?SaveOrUpdate(GuestInfo info) { bool success = false; try { var name = info.Name; var gender = info.Gender; var labels = info.Labels; var tableNo = info.TableNo; var imagePath = info.ImagePath; var entourageText = info.Entourage; var guestType = info.GuestType; var userId = info.Id; if (string.IsNullOrEmpty(userId)) { userId = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper(); } var imageFileName = Path.Combine($"GuestImages\\{userId}.jpg"); var img = Bitmap.FromFile(imagePath); var option = new FaceOption() { User_Info = $"姓名: {name} \n身份: {labels}\n桌号: {tableNo} ", }; var guest = GlobalConfigs.Guests.FirstOrDefault(x => x.Name == name); BaseResponse <FaceRegisterResult> jObj; if (guest == null)//新增 { jObj = FaceApi.FaceSaveOrUpdate(new Bitmap(img), GlobalConfigs.Configurations.GroupId, userId, option); success = (jObj != null && jObj.error_code == 0); if (success) { var entourages = entourageText.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); var entourageNum = entourages.Count(); GlobalConfigs.Guests.Add(new ee.Models.GuestInfo() { Id = userId, Name = name, Gender = gender, GuestType = guestType, Entourage = entourageText, EntourageNum = entourageNum, Labels = labels, TableNo = tableNo, ImagePath = imageFileName, CreateTime = DateTime.Now, }); if (entourages != null) { foreach (var item in entourages) { GlobalConfigs.Guests.Add(new ee.Models.GuestInfo() { Id = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper(), ParentId = userId, Name = $"{name}_{item}", Gender = 0, GuestType = guestType, Entourage = "", EntourageNum = 0, Labels = labels, TableNo = tableNo, ImagePath = null, CreateTime = DateTime.Now, }); } } GlobalConfigMgr.SaveGuests(); } } else { jObj = FaceApi.FaceSaveOrUpdate(new Bitmap(img), GlobalConfigs.Configurations.GroupId, guest.Id, option); success = (jObj != null && jObj.error_code == 0); if (success) { var entourages = entourageText.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); var entourageNum = entourages.Count(); guest.Name = name; guest.Gender = gender; guest.GuestType = guestType; guest.Entourage = entourageText; guest.EntourageNum = entourageNum; guest.Labels = labels; guest.TableNo = tableNo; guest.ImagePath = null; guest.CreateTime = DateTime.Now; for (int i = 0; i < GlobalConfigs.Guests.Count; i++) { if (GlobalConfigs.Guests[i].ParentId == userId) { GlobalConfigs.Guests.Remove(GlobalConfigs.Guests[i]); } } if (entourages != null) { foreach (var item in entourages) { GlobalConfigs.Guests.Add(new ee.Models.GuestInfo() { Id = System.Guid.NewGuid().ToString().ToUpper(), ParentId = userId, Name = $"{name}_{item}", Gender = 0, GuestType = guestType, Entourage = "", EntourageNum = 0, Labels = labels, TableNo = tableNo, ImagePath = null, IsAttend = guest.IsAttend, AttendTime = guest.AttendTime, CreateTime = DateTime.Now, }); } } GlobalConfigMgr.SaveGuests(); } } var newImage = new Bitmap(img); img.Dispose(); if (File.Exists(imageFileName)) { File.Delete(imageFileName); } newImage.Save(imageFileName, ImageFormat.Jpeg); newImage.Dispose(); return(success); } catch (Exception ex) { return(false); } }
public void GetUsersTest() { var groupId = "EE"; var jObj = FaceApi.GetUsers(groupId); }
public Task <string> Post([FromBody] Detect detect) { string appKey = ConfigurationManager.AppSettings["appKey"]; var faceApi = new FaceApi() { SubscriptionKey = "", GroupName = "" }; var task = Task.Run(() => { AppResponse todoList; try{ // 顔検出 var detectResponseJson = faceApi.detectPersonFace(detect.FaceUrl).Result; var detectResponse = JsonConvert.DeserializeObject <List <DetectResponse> >(detectResponseJson); // 顔識別 var identifyResponseJson = faceApi.identifyPersonFace(detectResponse[0].FaceId).Result; var identifyResponse = JsonConvert.DeserializeObject <List <IdentifyResponse> >(identifyResponseJson); //faceRectangleのみ抽出 FaceRectangle faceRectangle = detectResponse[0].FaceRectangle; // PersonIdのみ抽出 var candidates = identifyResponse[0].CandidatesInfo; string personId = candidates[0].PersonId; TodoDetail todo = new TodoDetail() { Title = getTodoTitle(personId).Result, }; if (TodoDbExistPersonId(personId)) { todoList = new AppResponse() { PersonId = personId, FaceRectangleInfo = faceRectangle, TodoList = todo, Show = true, }; } else { todoList = new AppResponse() { PersonId = null, FaceRectangleInfo = null, TodoList = null, Show = false, }; } string json = JsonConvert.SerializeObject(todoList); return(json); } catch (Exception e) { Console.WriteLine(e); todoList = new AppResponse() { PersonId = null, FaceRectangleInfo = null, TodoList = null, Show = false, }; string json = JsonConvert.SerializeObject(todoList); return(json); } }); return(task); }