Пример #1
0
        /// <summary>
        /// 载入已入录人脸模型
        /// </summary>
        private static Dictionary <FaceEncoding, string> GetFaceEncodesList()
        {
            Dictionary <FaceEncoding, string> dictionary = new Dictionary <FaceEncoding, string>();
            string path = @"faces";

            if (!Directory.Exists(path))
            {
                var t = Directory.CreateDirectory(path);
            }
            string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                var      name    = Path.GetFileNameWithoutExtension(file);//取特征的人名
                var      dirPath = Path.GetDirectoryName(file);
                string[] dats    = Directory.GetFiles(dirPath, "*.dat", SearchOption.AllDirectories);
                foreach (var dat in dats)
                {
                    var bf = new BinaryFormatter();
                    using (var fs = new FileStream(dat, FileMode.Open))
                    {
                        FaceEncoding face = bf.Deserialize(fs) as FaceEncoding;
                        dictionary.Add(face, name);
                    }
                }
            }
            return(dictionary);
        }
Пример #2
0
        /// <summary>
        ///辨識人臉
        /// </summary>
        private static void Recognition()
        {
            //將人臉編碼
            FaceEncoding face_encode = null;

            lock (key)
            {
                if (face == null)
                {
                    return;
                }
                face_encode = GetFaceEncoding().FirstOrDefault();
            }
            if (face_encode != null)
            {
                using (face_encode)
                {
                    //尋找使用者
                    int user_enc = FindUser(face_encode);
                    //如果有找到
                    if (user_enc != -1)
                    {
                        string user_name = face_Encs[user_enc].Name.Replace(".enc", "");
                        User.SetName(user_name);
                    }
                    else
                    {
                        User.Reset();
                    }
                }
            }
        }
Пример #3
0
        /// <summary>
        /// 新增使用者
        /// </summary>
        public static void AddUser(string user_name)
        {
            lock (key)
            {
                //尋找臉
                if (face != null)
                {
                    try
                    {
                        //將人臉編碼
                        FaceEncoding face_encode = null;
                        face_encode = GetFaceEncoding().FirstOrDefault();

                        //將編碼完成的人臉寫入成enc檔案放到數據庫
                        var bf = new BinaryFormatter();
                        using (var fs = new FileStream("encs/" + user_name + ".enc", FileMode.OpenOrCreate))
                        {
                            bf.Serialize(fs, face_encode);
                        }

                        //重新載入人臉數據庫
                        LoadFace();
                        MessageBox.Show("User addition successfully!");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("User addition failed,Please try again!" + ex.Message + "\n" + ex.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("Can't find face,Please try again!");
                }
            }
        }
        public static byte[] Serialize(FaceEncoding faceEncoding)
        {
            var bf = new BinaryFormatter();

            using var stream = new MemoryStream();
            bf.Serialize(stream, faceEncoding);
            var bytes = stream.ToArray();

            return(bytes);
        }
Пример #5
0
        private byte[] SerializeFace(FaceEncoding faceEncoding)
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();

            using (var stream = new MemoryStream())
            {
                binaryFormatter.Serialize(stream, faceEncoding);
                return(stream.ToArray());
            }
        }
Пример #6
0
 public FaceEncodingData(FaceEncoding value)
 {
     if (value == null)
     {
         throw new NullReferenceException("Null faceEncoding");
     }
     if (value.IsDisposed || value.Size <= 0)
     {
         throw new ArgumentException($"Invalid faceEncoding");
     }
     Value = value;
 }
Пример #7
0
        public void TestFaceDistanceEmptyLists()
        {
            using (var img = FaceRecognition.LoadImageFile(Path.Combine("TestImages", "biden.jpg")))
            {
                var encoding = this._FaceRecognition.FaceEncodings(img).ToArray()[0];

                // empty list
                var facesToCompare = new FaceEncoding[0];

                var distanceResult = FaceRecognition.FaceDistances(facesToCompare, encoding).ToArray();
                Assert.IsTrue(distanceResult.Length == 0);
            }
        }
Пример #8
0
        public async Task <string> GetNewPhotoDescriptror([FromForm] IFormCollection form)
        {
            string uploadedFilePath = await GetUploadedFacePhotoPathAsync(form);

            // загружаем изображение из файла
            FaceEncoding encoding = CreateImageDescriptor(uploadedFilePath);

            string descriptor = encoding != null
                ? JsonConvert.SerializeObject(encoding)
                : "";

            DeleteUploadedFacePhoto(uploadedFilePath);

            return(descriptor);
        }
Пример #9
0
        private bool IsEqualFaceDescriptros(FaceEncoding uploadedImageEncoding, PhotoFaceDescriptor databasePhoto)
        {
            bool result = false;
            // определяем порог допустимой точности
            const double precision = 0.6d;

            if (databasePhoto != null)
            {
                FaceEncoding imageEncodingToCompare =
                    JsonConvert.DeserializeObject <FaceEncoding>(databasePhoto.Descriptor);
                result = FaceRecognition.CompareFace(
                    uploadedImageEncoding, imageEncodingToCompare, precision);
            }

            return(result);
        }
Пример #10
0
        private async Task <IEnumerable <Guid> > GetEqualFacePhotosAsync(string uploadedFilePath)
        {
            FaceEncoding uploadedImageEncoding = CreateImageDescriptor(uploadedFilePath);

            var photoIdList          = new List <Guid>();
            var photoFaceDescriptors = await _context.LoadPhotoDescriptorsTest();

            foreach (var desc in photoFaceDescriptors)
            {
                if (IsEqualFaceDescriptros(uploadedImageEncoding, desc))
                {
                    photoIdList.Add(desc.PhotoFaceId);
                }
            }

            return(photoIdList);
        }
Пример #11
0
        public async Task PopulateDescriptors()
        {
            var wantedPhotosFolderPath = String.Concat(
                _appEnvironment.WebRootPath, "\\WantedFacePhotos\\", "photoCollection");

            if (!Directory.Exists(wantedPhotosFolderPath))
            {
                Directory.CreateDirectory(wantedPhotosFolderPath);
            }

            var    wantedFacePhotos = _context.LoadPhotoFilesTest();
            string filePath         = "";

            foreach (var photo in wantedFacePhotos)
            {
                string photoName = string.Concat("\\photo.", photo.Mime);
                filePath = string.Concat(wantedPhotosFolderPath, photoName);
                await System.IO.File.WriteAllBytesAsync(filePath, photo.Photo);

                Image photoImage = FaceRecognition.LoadImageFile(filePath);
                IEnumerable <Location> faceLocations = _fr.FaceLocations(photoImage);
                FaceEncoding           faceEncoding  = CreateImageDescriptor(filePath);
                string encodingSerialized            = faceEncoding != null
                    ? JsonConvert.SerializeObject(faceEncoding)
                    : "";

                PhotoFaceDescriptor desc;

                if (!string.IsNullOrEmpty(encodingSerialized))
                {
                    desc = new PhotoFaceDescriptor()
                    {
                        Id          = Guid.NewGuid(),
                        PhotoFaceId = photo.PhotoId,
                        Descriptor  = encodingSerialized
                    };

                    _context.PhotoFaceDescriptors.Add(desc);
                    _context.SaveChanges();
                }

                System.IO.File.Delete(filePath);
            }
        }
Пример #12
0
        //判別使用者
        private static int FindUser(FaceEncoding face_encode)
        {
            int result = -1;

            double[] distances    = FaceRecognition.FaceDistances(encodings, face_encode).ToArray();
            double   min_distance = 1;

            //跟資料庫裡的使用者作比對
            for (int i = 0; i < distances.Length; i++)
            {
                if (distances[i] < min_distance && distances[i] < 0.4)
                {
                    min_distance = distances[i];
                    result       = i;
                }
            }

            return(result);
        }
Пример #13
0
        private FaceEncoding CreateImageDescriptor(string filePath)
        {
            FaceEncoding uploadedImageEncoding = null;

            try
            {
                // создаём образ фотографии
                Image uploadedImage = FaceRecognition.LoadImageFile(filePath);
                // находим лицо на фотографии
                IEnumerable <Location> uploadedLocations = _fr.FaceLocations(uploadedImage);
                // кодируем изображение найденного лица
                uploadedImageEncoding = _fr.FaceEncodings(uploadedImage, uploadedLocations).First();
            }
            catch (Exception)
            {
                return(null);
            }

            return(uploadedImageEncoding);
        }
Пример #14
0
        /// <summary>
        /// 保存人脸模型
        /// </summary>
        private static void SaveFaceEncodes(byte[] imageBytes, FaceEncoding encoding, string name)
        {
            var dest = $"faces/{name}/";

            if (!Directory.Exists(dest))
            {
                Directory.CreateDirectory(dest);
                File.Create(Path.Combine(dest, name + ".txt"));
            }
            string[] files = Directory.GetFiles(dest);
            //imageBytes
            string ts = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + encoding.Size;
            //格式 日期加上特征数
            string datFilePath = $"{dest}/{ts}.dat";
            string jpgFilePath = $"{dest}/{ts}.jpg";

            var bf = new BinaryFormatter();

            using (var fs = new FileStream(datFilePath, FileMode.OpenOrCreate))
            {
                bf.Serialize(fs, encoding);
            }
            File.WriteAllBytes(jpgFilePath, imageBytes);
        }
Пример #15
0
 private static string GetDistance(FaceEncoding a, FaceEncoding b)
 {
     return(a == null || b == null ? "N/A" : FaceRecognition.FaceDistance(a, b).ToString());
 }