Пример #1
0
        public long matchFound(string filePath)
        {
            Fingerprint fp2 = new Fingerprint();

            fp2.AsBitmap = new Bitmap(Bitmap.FromFile(filePath));
            Person p2 = new Person();

            p2.Fingerprints.Add(fp2);
            afis.Extract(p2);

            Person ans   = afis.Identify(p2, candidates).FirstOrDefault();
            bool   match = (ans != null);

            if (match)
            {
                DataSet ds = selectClassObj.get_enroll_no_by_id(ans.Id);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    return(Convert.ToInt64(ds.Tables[0].Rows[0]["enroll_no"]));
                }
                else
                {
                    return(0);
                }
            }
            return(0);
        }
            private void ValidateFingerprint(Bitmap bitmap, List <Person> allPersons)
            {
                var unknownPerson = new Person();
                var fingerprint   = new Fingerprint();

                fingerprint.AsBitmap = bitmap;

                unknownPerson.Fingerprints.Add(fingerprint);
                _afis.Extract(unknownPerson);

                var matches = _afis.Identify(unknownPerson, allPersons);

                var persons = matches as Person[] ?? matches.ToArray();

                foreach (var person in persons)
                {
                    var personId = person.Id;

                    var user = GetUsernames().ToList().ElementAt(personId);

                    Output.WriteLine(ConsoleColor.DarkGreen, $"Matched with {user}!");
                }

                if (!persons.Any())
                {
                    Output.WriteLine(ConsoleColor.DarkRed, "No match!");
                }
            }
Пример #3
0
        }//Enroll

        //Match probe with people in the database
        public static Match getMatch(string fpPath, string visitorId, Int32 threshold)
        {
            Match match = new Match();

            // Match visitor with unknown identity
            MyPerson probe = getProbe(fpPath, visitorId);

            if (persons == null)
            {
                DataAccess dataAccess = new DataAccess();
                persons = dataAccess.retrievePersonFingerprintTemplates();
                Console.WriteLine("###-->> Loading persons from DB. Total persons = " + persons.Count());
            }
            else
            {
                Console.WriteLine("###-->> Loading persons from Cache. Total persons = " + persons.Count());
            }


            // Look up the probe using Threshold = 10
            Afis.Threshold = threshold;
            Console.WriteLine("Identifying {0} in database of {1} persons...", probe.Name, persons.Count);
            MyPerson matchedPerson = Afis.Identify(probe, persons).FirstOrDefault() as MyPerson;

            // Null result means that there is no candidate with similarity score above threshold
            if (matchedPerson == null)
            {
                match.setProbe(probe);
                match.setMatchedPerson(matchedPerson);
                match.setStatus(false);
                match.setScore(0.0F);
                return(match);
            }

            // Compute similarity score
            float score = Afis.Verify(probe, matchedPerson);

            match.setProbe(probe);
            match.setMatchedPerson(matchedPerson);
            match.setStatus(true);
            match.setScore(score);

            Console.WriteLine("Similarity score between {0} and {1} = {2:F3}", probe.Name, matchedPerson.Name, score);
            Console.WriteLine("Visitor " + visitorId + " matches with registered person " + matchedPerson.Name + ". Match score = " + score);

            return(match);
        }//getMatch
Пример #4
0
        void StartCore()
        {
            tts.Speak("叮咚", QueueMode.Flush, null);
            if (isIdentify && System.IO.File.Exists(ImagePath + nowLesson + ".dat"))                 //指纹识别
            // Enroll visitor with unknown identity
            //MyPerson probe = Enroll(ImagePath + "t1.BMP", "##Visitor##");
            {
                tv.Text = "开始识别。。。";
                MyPerson probe = Enroll(pics, "##Visitor##");
                Console.WriteLine("Identifying {0} in database of {1} persons...", probe.Name, database.Count);
                MyPerson match = Afis.Identify(probe, database).FirstOrDefault() as MyPerson;
                // Null result means that there is no candidate with similarity score above threshold
                if (match == null)
                {
                    Console.WriteLine("No matching person found.");
                    result.Text = "无匹配指纹!";
                    tts.Speak("不认识你", QueueMode.Flush, null);
                }
                else
                {
                    // Print out any non-null result
                    Console.WriteLine("Probe {0} matches registered person {1}", probe.Name, match.Name);


                    // Compute similarity score
                    float score = Afis.Verify(probe, match);
                    Console.WriteLine("Similarity score between {0} and {1} = {2:F3}", probe.Name, match.Name, score);
                    tv.Text = "识别完成。。。";
                    tts.Speak(match.Name, QueueMode.Flush, null);
                    judgeTime(match.Name);
                    result.Text = "身份:" + match.Name + "\n匹配分数:" + score;
                }
            }
            else if (xuehao != null)                 //指纹录入
            //database.Add(Enroll(ImagePath + "r1.BMP", xuehao));
            {
                database.Add(Enroll(pics, xuehao));
                xuehao = null;

                // Save the database to disk and load it back, just to try out the serialization
                Console.WriteLine("Saving database...");
                BinaryFormatter formatter = new BinaryFormatter();
                using (Stream stream = File.Open(ImagePath + nowLesson + ".dat", FileMode.OpenOrCreate))
                    formatter.Serialize(stream, database);

                isIdentify = true;
                tv.Text    = "指纹已录入,开始识别。。。";
            }
            else
            {
                //Toast.MakeText(Application.Context,"请先录入指纹",ToastLength.Short).Show();
            }
        }
Пример #5
0
        public async Task <ActionResult> Create([Bind(Include = "logId,mortalId,dateTime_2,areaCode")] log log, FormCollection collection)
        {
            string fileNameInput = collection["filename"];

            AfisEngine Afis = new AfisEngine();

            Afis.Threshold = 10;

            Fingerprint fp1 = new Fingerprint();

            string apppath     = System.IO.Path.Combine(Server.MapPath("~"), "images");
            string pathToImage = (System.IO.Path.Combine(apppath, fileNameInput));

            Bitmap bitmap = fp1.AsBitmap = new Bitmap(Image.FromFile(pathToImage));

            MyPerson personsdk = new MyPerson();

            personsdk.Fingerprints.Add(fp1);

            Afis.Extract(personsdk);

            string          sql           = "Select * from mortal";
            List <mortal>   personListRom = db.mortals.SqlQuery(sql).ToList();
            List <MyPerson> personListRam = new List <MyPerson>();

            foreach (mortal p in personListRom)
            {
                MyPerson      personTemp = new MyPerson();
                MyFingerprint fpTemp     = new MyFingerprint();
                personTemp.Id        = p.mortalId;
                personTemp.Name      = p.name;
                fpTemp.Filename      = p.filename;
                fpTemp.AsXmlTemplate = XElement.Parse(p.template);
                personTemp.Fingerprints.Add(fpTemp);
                personListRam.Add(personTemp);
            }

            MyPerson match = Afis.Identify(personsdk, personListRam).FirstOrDefault() as MyPerson;

            log.mortalId = match.Id;
            if (ModelState.IsValid)
            {
                db.logs.Add(log);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            ViewBag.mortalId = new SelectList(db.mortals, "mortalId", "name", log.mortalId);
            return(View(log));
        }
Пример #6
0
        public void FingerTest()
        {
            AfisEngine afis = new AfisEngine();

            afis.Threshold = 0.0001f;
            Person person1 = new Person(new Fingerprint()
            {
                AsBitmap = Settings.SomeFingerprint
            });

            afis.Extract(person1);
            Person person2 = new Person(new Fingerprint()
            {
                AsBitmap = Settings.MatchingFingerprint
            });

            afis.Extract(person2);

            person1.Fingerprints[0].Finger = Finger.RightThumb;
            Assert.AreEqual(Finger.RightThumb, person1.Fingerprints[0].Finger);
            person2.Fingerprints[0].Finger = Finger.RightThumb;
            Assert.That(afis.Verify(person1, person2) > 0);
            Assert.That(afis.Identify(person1, new[] { person2 }).Count() > 0);

            person2.Fingerprints[0].Finger = Finger.LeftIndex;
            Assert.That(afis.Verify(person1, person2) == 0);
            Assert.That(afis.Identify(person1, new[] { person2 }).Count() == 0);

            person1.Fingerprints[0].Finger = Finger.Any;
            Assert.That(afis.Verify(person1, person2) > 0);
            Assert.That(afis.Verify(person2, person1) > 0);
            Assert.That(afis.Identify(person1, new[] { person2 }).Count() > 0);
            Assert.That(afis.Identify(person2, new[] { person1 }).Count() > 0);

            person2.Fingerprints[0].Finger = Finger.Any;
            Assert.That(afis.Verify(person1, person2) > 0);
            Assert.That(afis.Identify(person1, new[] { person2 }).Count() > 0);

            Person person3 = new Person(new Fingerprint()
            {
                AsBitmap = Settings.MatchingFingerprint
            });

            afis.Extract(person3);
            person1.Fingerprints[0].Finger = Finger.LeftIndex;
            person2.Fingerprints[0].Finger = Finger.LeftIndex;
            person3.Fingerprints[0].Finger = Finger.RightMiddle;
            CollectionAssert.AreEqual(afis.Identify(person1, new[] { person2, person3 }), new[] { person2 });
            person1.Fingerprints[0].Finger = Finger.RightMiddle;
            CollectionAssert.AreEqual(afis.Identify(person1, new[] { person2, person3 }), new[] { person3 });

            Assert.Catch(() => { person1.Fingerprints[0].Finger = (Finger)(-1); });
        }
Пример #7
0
        public void Threshold()
        {
            AfisEngine afis    = new AfisEngine();
            Person     person1 = new Person(new Fingerprint()
            {
                AsBitmap = Settings.SomeFingerprint
            });

            afis.Extract(person1);
            Person person2 = new Person(new Fingerprint()
            {
                AsBitmap = Settings.MatchingFingerprint
            });

            afis.Extract(person2);

            float score = afis.Verify(person1, person2);

            Assert.That(score > 0);

            afis.Threshold = 1.001f * score;
            Assert.That(afis.Verify(person1, person2) == 0);
            Assert.That(afis.Identify(person1, new[] { person2 }).Count() == 0);

            afis.Threshold = 0.999f * score;
            Assert.That(afis.Verify(person1, person2) > 0);
            Assert.That(afis.Identify(person1, new[] { person2 }).Count() > 0);

            afis.Threshold = score;
            Assert.That(afis.Verify(person1, person2) > 0);
            Assert.That(afis.Identify(person1, new[] { person2 }).Count() > 0);

            afis.Threshold = 0;
            Assert.That(afis.Verify(person1, person2) > 0);
            Assert.That(afis.Identify(person1, new[] { person2 }).Count() > 0);

            Assert.Catch(() => { afis.Threshold = -0.001f; });
        }
        static void Main(string[] args)
        {
            Afis = new AfisEngine();
            List <MyPerson> database     = new List <MyPerson>();
            List <byte[]>   ListOfImages = new List <byte[]>();
            string          pathString   = string.Empty;

            byte[] byteArray;
            int    ideal_value = 0;

            pathString = System.IO.Path.Combine(ImagePath, "fingerprint_2_93.tif");
            byteArray  = System.IO.File.ReadAllBytes(pathString);
            database.Add(Enroll(Path.Combine(ImagePath, "fingerprint_2_93.tif"), byteArray));

            pathString = System.IO.Path.Combine(ImagePath, "fingerprint_3_83.tif");
            byteArray  = System.IO.File.ReadAllBytes(pathString);
            database.Add(Enroll(Path.Combine(ImagePath, "fingerprint_3_83.tif"), byteArray));

            pathString = System.IO.Path.Combine(ImagePath, "probe_2_125.tif");
            byteArray  = System.IO.File.ReadAllBytes(pathString);
            MyPerson probe = Enroll(Path.Combine(ImagePath, "probe_2_125.tif"), byteArray);

            Afis.Threshold = 10;
            MyPerson match = Afis.Identify(probe, database).FirstOrDefault() as MyPerson;

            if (match == null)
            {
                //return "No matching person found.";
            }

            float  score        = Afis.Verify(probe, match);
            string matched_user = match.Name;

            if (ideal_value <= 0)
            {
                ideal_value = 60;
            }

            if (score > ideal_value)
            {
                Console.WriteLine("Matched user: "******"Score: " + score);
            }
            else
            {
                Console.WriteLine("No Matched user");
                Console.WriteLine("Score: " + score);
            }
            Console.ReadLine();
        }
Пример #9
0
        public static bool Finger(String candidate_fingerprint, String candidate_name, String probe_fingerprint, String probe_name)
        {
            // Initialize SourceAFIS
            Afis = new AfisEngine();

            // Enroll some people
            List <MyPerson> database = new List <MyPerson>();

            database.Add(Enroll(candidate_fingerprint, candidate_name));

            // Save the database to disk and load it back, just to try out the serialization
            BinaryFormatter formatter = new BinaryFormatter();

            using (Stream stream = File.Open("database.dat", FileMode.Create))
                formatter.Serialize(stream, database);

            //Reloading Database
            using (FileStream stream = File.OpenRead("database.dat"))
                database = (List <MyPerson>)formatter.Deserialize(stream);

            // Enroll visitor with unknown identity
            MyPerson probe = Enroll(probe_fingerprint, probe_name);

            // Look up the probe using Threshold = 10
            Afis.Threshold = 60;

            //TEST CASE
            //MessageBox.Show(String.Format("Identifying {0} in database of {1} persons...", probe.Name, database.Count));

            MyPerson match = Afis.Identify(probe, database).FirstOrDefault() as MyPerson;

            // Null result means that there is no candidate with similarity score above threshold
            if (match == null)
            {
                //TEST CASE
                //MessageBox.Show("No matching person found.");
                return(false);
            }
            // Print out any non-null result
            //TEST CASE
            //MessageBox.Show(String.Format("Probe {0} matches registered person {1}", probe.Name, match.Name));

            // Compute similarity score
            float score = Afis.Verify(probe, match);

            //TEST CASE
            //MessageBox.Show(String.Format("Similarity score between {0} and {1} = {2}", probe.Name, match.Name, score));

            return(true);
        }
Пример #10
0
        private Usuario verificaHuella(Fingerprint fingerPrint)
        {
            Usuario usuarioVerificado = null;

            using (var context = new db_Entidades())
            {
                UsuarioAFIS usuarioABuscar = new UsuarioAFIS();
                usuarioABuscar.Fingerprints.Add(fingerPrint);

                //Creamos Objeto AfisEngine el cual realiza la identificación de usuarios
                AfisEngine Afis = new AfisEngine();
                // Marcamos límite para verificar una huella como encontrada
                Afis.Threshold = 50;
                Afis.Extract(usuarioABuscar);

                //Obtenemos los usuarios registrados en la base de datos
                var usuariosBBDD = context.Usuario.ToList();
                //Lista de tipo UsuarioAFIS, los cuales rellenamos con plantillas de huellas dactilares e id de usuario de la base de datos
                List <UsuarioAFIS> listaUsuariosAFIS = new List <UsuarioAFIS>();

                foreach (var usuario in usuariosBBDD)
                {
                    Fingerprint fingerPrintAUX = new Fingerprint();
                    fingerPrintAUX.AsIsoTemplate = usuario.finger;
                    UsuarioAFIS usuarioAFIS_AUX = new UsuarioAFIS();
                    usuarioAFIS_AUX.id = usuario.id;
                    usuarioAFIS_AUX.Fingerprints.Add(fingerPrintAUX);
                    listaUsuariosAFIS.Add(usuarioAFIS_AUX);
                }
                //Realiza la busqueda
                UsuarioAFIS usuarioEncontrado = Afis.Identify(usuarioABuscar, listaUsuariosAFIS).FirstOrDefault() as UsuarioAFIS;
                if (usuarioEncontrado == null)
                {
                    Console.WriteLine("No se ha encontrado");
                    //cS.enviaCadena("NO IDENTIFICADO");
                    usuarioVerificado = null;
                }
                else
                {
                    //Obtenemos la puntuación de los usuarios identificados
                    float puntuacion = Afis.Verify(usuarioABuscar, usuarioEncontrado);
                    usuarioVerificado = usuariosBBDD.Find(x => x.id == usuarioEncontrado.id);
                    //cS.enviaCadena("IDENTIFICADO");
                    //cS.enviaCadena(usuarioCompleto.username);
                    Console.WriteLine("Encontrado con: {0:F3}, Nombre: {1}", puntuacion, usuarioVerificado.username);
                }
            }
            return(usuarioVerificado);
        }
Пример #11
0
        private void btn_cmp_Click(object sender, EventArgs e)
        {
            Fingerprint fp2 = new Fingerprint();

            fp2.AsBitmap = new Bitmap(Bitmap.FromFile(pictureBox1.ImageLocation));
            Person p2 = new Person();

            p2.Fingerprints.Add(fp2);
            afis.Extract(p2);

            Person ans   = afis.Identify(p2, candidates).FirstOrDefault();
            bool   match = (ans != null);

            if (match)
            {
                DataSet ds = selectClassObj.get_enroll_no_by_id(ans.Id);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    count++;
                    List <Fingerprint> li = ans.Fingerprints;
                    foreach (Fingerprint f in li)
                    {
                        Bitmap bitmp = new Bitmap(f.AsBitmap);
                        pictureBox2.Image    = bitmp;
                        pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
                        pictureBox2.Refresh();
                    }
                    lbl_result.Text      = "Matched";
                    lbl_result.ForeColor = Color.Green;

                    lbl_result.Text += " " + ds.Tables[0].Rows[0]["enroll_no"];
                }
                else
                {
                    pictureBox2.Image    = null;
                    lbl_result.Text      = "Not Matched";
                    lbl_result.ForeColor = Color.Red;
                }
            }
            else
            {
                pictureBox2.Image    = null;
                lbl_result.Text      = "Not Matched";
                lbl_result.ForeColor = Color.Red;
            }
            MessageBox.Show("\nCount: " + count);
        }
Пример #12
0
 //Ok 12-400
 /// <summary>
 /// wie is het
 /// </summary>
 /// <param name="_inObject"></param>
 /// <returns></returns>
 public static string wieIsDit(object _inObject)
 {
     try {
         string     wertkWel  = JsonConvert.SerializeObject(_inObject);
         TypeAskID  IDRequest = JsonConvert.DeserializeObject <TypeAskID>(wertkWel);
         SqlCommand command   = new SqlCommand();
         command.CommandText = "SELECT id,fingerprintTemplate FROM " + settings.studentBDTableName;
         DataTable     queryResult = SqlAndWeb.SQLQuery(settings.connectionString, command);
         List <Person> personList  = new List <Person>();
         foreach (DataRow row in queryResult.Rows)
         {
             Person      person      = new Person();
             Fingerprint fingerprint = new Fingerprint();
             person.Id = (int)row["id"];
             string base64FingerTemplate = (string)row["fingerprintTemplate"];
             fingerprint.Template = Convert.FromBase64String(base64FingerTemplate);
             person.Fingerprints.Add(fingerprint);
             personList.Add(person);
         }
         Person      unknowPerson      = new Person();
         Fingerprint unknowFingerprint = new Fingerprint();
         unknowFingerprint.Template = Convert.FromBase64String(IDRequest.base64FingerprintTemplate);
         unknowPerson.Fingerprints.Add(unknowFingerprint);
         Person wieHetIs = afis.Identify(unknowPerson, personList).FirstOrDefault();
         if (wieHetIs != null)
         {
             SqlCommand comond = new SqlCommand();
             comond.CommandText = "select ID,voorNaam,achterNaam,profileImage from " + settings.studentBDTableName + " where ID=" + wieHetIs.Id;
             DataTable    queryResponse = SqlAndWeb.SQLQuery(settings.connectionString, comond);
             DataRow      theRow        = queryResponse.Rows[0];
             TypeReturnID returnType    = new TypeReturnID();
             returnType.ID                 = (int)theRow["id"];
             returnType.voorNaam           = (string)theRow["voorNaam"];
             returnType.achterNaam         = (string)theRow["achterNaam"];
             returnType.base64ProfileImage = (string)theRow["profileImage"];
             return(JsonConvert.SerializeObject(returnType));
         }
         else
         {
             return(JsonConvert.SerializeObject(new TypeReturnID()));
         }
     } catch (Exception ex) {
         TypeReturnError typeForError = new TypeReturnError();
         typeForError.why = "(wieIsDit)" + ex.Message;
         return(JsonConvert.SerializeObject(typeForError));
     }
 }
        static void Main(string[] args)
        {
            // Initialize SourceAFIS
            Afis = new AfisEngine();

            // Enroll some people
            List <MyPerson> database = new List <MyPerson>();

            database.Add(Enroll(Path.Combine(ImagePath, "candidate1.tif"), "Fred Flintstone"));
            database.Add(Enroll(Path.Combine(ImagePath, "candidate2.tif"), "Wilma Flintstone"));
            database.Add(Enroll(Path.Combine(ImagePath, "candidate3.tif"), "Barney Rubble"));

            // Save the database to disk and load it back, just to try out the serialization
            BinaryFormatter formatter = new BinaryFormatter();

            Console.WriteLine("Saving database...");
            using (Stream stream = File.Open("database.dat", FileMode.Create))
                formatter.Serialize(stream, database);
            Console.WriteLine("Reloading database...");
            using (FileStream stream = File.OpenRead("database.dat"))
                database = (List <MyPerson>)formatter.Deserialize(stream);

            // Enroll visitor with unknown identity
            MyPerson probe = Enroll(Path.Combine(ImagePath, "probe.tif"), "Visitor #12345");

            // Look up the probe using Threshold = 10
            Afis.Threshold = 10;
            Console.WriteLine("Identifying {0} in database of {1} persons...", probe.Name, database.Count);
            MyPerson match = Afis.Identify(probe, database).FirstOrDefault() as MyPerson;

            // Null result means that there is no candidate with similarity score above threshold
            if (match == null)
            {
                Console.WriteLine("No matching person found.");
                Console.ReadKey();
                return;
            }
            // Print out any non-null result
            Console.WriteLine("Probe {0} matches registered person {1}", probe.Name, match.Name);

            // Compute similarity score
            float score = Afis.Verify(probe, match);

            Console.WriteLine("Similarity score between {0} and {1} = {2:F3}", probe.Name, match.Name, score);
            Console.ReadKey();
        }
Пример #14
0
        public static void Finger()
        {
            // Initialize SourceAFIS
            Afis = new AfisEngine();

            // Enroll some people
            List <MyPerson> database = new List <MyPerson>();

            database.Add(Enroll(Path.Combine(ImagePath, "candidate1.tif"), "Ankit Balyan"));
            database.Add(Enroll(Path.Combine(ImagePath, "candidate2.tif"), "Gurleen Singh"));
            database.Add(Enroll(Path.Combine(ImagePath, "candidate3.tif"), "Kunal Kholia"));

            // Save the database to disk and load it back, just to try out the serialization
            BinaryFormatter formatter = new BinaryFormatter();

            using (Stream stream = File.Open("database.dat", FileMode.Create))
                formatter.Serialize(stream, database);

            //Reloading Database
            using (FileStream stream = File.OpenRead("database.dat"))
                database = (List <MyPerson>)formatter.Deserialize(stream);

            // Enroll visitor with unknown identity
            MyPerson probe = Enroll(Path.Combine(ImagePath, "probe.tif"), "Visitor #12345");

            // Look up the probe using Threshold = 10
            Afis.Threshold = 60;
            MessageBox.Show(String.Format("Identifying {0} in database of {1} persons...", probe.Name, database.Count));
            MyPerson match = Afis.Identify(probe, database).FirstOrDefault() as MyPerson;

            // Null result means that there is no candidate with similarity score above threshold
            if (match == null)
            {
                MessageBox.Show("No matching person found.");
                return;
            }
            // Print out any non-null result
            MessageBox.Show(String.Format("Probe {0} matches registered person {1}", probe.Name, match.Name));

            // Compute similarity score
            float score = Afis.Verify(probe, match);

            MessageBox.Show(String.Format("Similarity score between {0} and {1} = {2:F3}", probe.Name, probe.Name, score));
        }
Пример #15
0
        private void btnProvjeraPrsta_Click(object sender, EventArgs e)
        {
            List <Otisak_prsta> listaOtisaka = new List <Otisak_prsta>();

            listaOtisaka = Otisak_prsta.DohvatiOtiske();
            foreach (var item in listaOtisaka)
            {
                Fingerprint fp = new Fingerprint();
                fp.AsBitmap = new Bitmap(Bitmap.FromFile(Application.StartupPath + item.Otisak_putanja));
                Person osoba = new Person();
                osoba.Id = item.FK_korisnik;
                osoba.Fingerprints.Add(fp);
                Afis.Extract(osoba);
                ListaOsobaIzBaze.Add(osoba);
            }

            Afis.Threshold = 40;
            Person matchingCandidate = Afis.Identify(NepoznataOsoba, ListaOsobaIzBaze).FirstOrDefault();

            if (matchingCandidate == null)
            {
                MessageBox.Show("Nije pronadena osoba s navedenim otiskom prsta!");
            }
            else
            {
                Korisnik trazeniKorisnik = new Korisnik();
                trazeniKorisnik = Korisnik.DohvatiKorisnika(matchingCandidate.Id);
                float score = Afis.Verify(NepoznataOsoba, matchingCandidate);
                bool  match = (score > 0);
                MessageBox.Show("Pronađen je korisnik: " + trazeniKorisnik.Korisnicko_ime + " s koeficijentom podudranja: " + score.ToString());
                if (trazeniKorisnik.Korisnicko_ime == textBoxKorIme.Text)
                {
                    zastavicaPrst              = true;
                    lblOsobaFinger.Text        = trazeniKorisnik.Korisnicko_ime;
                    lblOsobaFinger.ForeColor   = System.Drawing.Color.Green;
                    lblFingerTocnost.Text      = score.ToString();
                    lblFingerTocnost.ForeColor = System.Drawing.Color.Green;
                }
            }
            ProvjeraPrijave();
        }
Пример #16
0
        static void Identify(string data)
        {
            data = data.Trim();

            string fingerImage = null;

            if (data.Contains('='))
            {
                fingerImage = data.Substring(data.IndexOf('=') + 1).Trim();
            }
            else
            {
                fingerImage = data;
            }

            //incoming finger
            Fingerprint fp = new Fingerprint();

            fp.AsBitmap = new Bitmap(Bitmap.FromFile(fingerImage));
            Person person = new Person();

            person.Fingerprints.Add(fp);
            Afis.Extract(person);

            var testing  = fp.Template;
            var testing2 = person.Fingerprints[0].Template;
            var th       = Afis.Threshold;

            //all candidates
            var       allPersons = db.GetPersons();
            IdpPerson match      = (Afis.Identify(person, allPersons).FirstOrDefault() as IdpPerson);

            if (match != null)
            {
                Console.WriteLine("SourceAFISHelper.exe/identify/success:" + match.ID);
            }
            else
            {
                Console.WriteLine("SourceAFISHelper.exe/identify/failure:Could not retrieve record from the database");
            }
        }
Пример #17
0
        public async Task <ActionResult> Verify([Bind(Include = "Filename")] mortal mortal)
        {
            if (ModelState.IsValid & mortal.filename != null)
            {
                AfisEngine Afis = new AfisEngine();
                Afis.Threshold = 10;

                Fingerprint fp1 = new Fingerprint();

                string apppath     = System.IO.Path.Combine(Server.MapPath("~"), "images");
                string pathToImage = (System.IO.Path.Combine(apppath, mortal.filename));

                Bitmap bitmap = fp1.AsBitmap = new Bitmap(Image.FromFile(pathToImage));

                MyPerson personsdk = new MyPerson();
                personsdk.Fingerprints.Add(fp1);

                Afis.Extract(personsdk);

                string          sql           = "Select * from mortal";
                List <mortal>   personListRom = db.mortals.SqlQuery(sql).ToList();
                List <MyPerson> personListRam = new List <MyPerson>();
                foreach (mortal p in personListRom)
                {
                    MyPerson      personTemp = new MyPerson();
                    MyFingerprint fpTemp     = new MyFingerprint();
                    personTemp.Id        = p.mortalId;
                    personTemp.Name      = p.name;
                    fpTemp.Filename      = p.filename;
                    fpTemp.AsXmlTemplate = XElement.Parse(p.template);
                    personTemp.Fingerprints.Add(fpTemp);
                    personListRam.Add(personTemp);
                }

                MyPerson match = Afis.Identify(personsdk, personListRam).FirstOrDefault() as MyPerson;
                Response.Write("<script>alert('" + match.Name + "');</script>");
                return(View());
            }
            Response.Write("<script>alert('Please Enter Filename');</script>");
            return(View());
        }
Пример #18
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            byte[] imageBytes = Convert.FromBase64String(img_val.Value);

            fp.AsBitmap = CreateBmpImage(imageBytes);
            probe.Fingerprints.Add(fp);
            afis.Extract(probe);
            Person matchingCandidate = afis.Identify(probe, users).FirstOrDefault() as Person;
            bool   match             = (matchingCandidate != null);

            if (match == true)
            {
                float score = afis.Verify(probe, matchingCandidate);
                //Response.Write("<br><br>Score=" + score.ToString() + "<br><br>ID=" + matchingCandidate.Id.ToString());
                CheckAccountStatus(matchingCandidate.Id);
            }
            else
            {
                Response.Write("No user Found");
            }
        }
Пример #19
0
        public MemberFingerprint BatchIdentify(MatchRequest toMatch)
        {
            _toMatch = new MemberPerson();
            Fingerprint f = new Fingerprint();

            f.AsIsoTemplate = toMatch.Fingerprint;
            //_toMatch.Member = toMatch;

            Afis.Threshold = 10;
            //Console.WriteLine("Identifying {0} in database of {1} persons...", probe.Name, database.Count);
            var match = Afis.Identify(_toMatch, _persons).FirstOrDefault() as MemberPerson;

            // Null result means that there is no candidate with similarity score above threshold
            if (match == null)
            {
                //Console.WriteLine("No matching person found.");
                return(match.Member);
            }

            return(null);
        }
Пример #20
0
        private void btnComparar_Click(object sender, EventArgs e)
        {
            Fingerprint fpBase     = new Fingerprint();
            Person      pessoaBase = new Person();

            List <Person> candidatos = new List <Person>();

            string diretorio;

            openFile.ShowDialog();
            openFile.Filter          = "Image Files(*.JPG;*.PNG)|*.JPG;*.PNG";
            openFile.CheckFileExists = true;
            openFile.CheckPathExists = true;
            openFile.OpenFile();
            diretorio = openFile.FileName;

            fpBase.AsBitmap = new Bitmap(Bitmap.FromFile(diretorio));
            pessoaBase.Fingerprints.Add(fpBase);
            for (i = 0; i < 4; i++)
            {
                fpBd[i]          = new Fingerprint();
                fpBd[i].AsBitmap = new Bitmap(Bitmap.FromFile(diretorio));
            }

            for (i = 0; i < 4; i++)
            {
                pessoaBd[i] = new Person();
                pessoaBd[i].Fingerprints.Add(fpBd[i]);
                candidatos.Add(pessoaBd[i]);
                Afis.Extract(pessoaBd[i]);
            }

            var pessoasMatchs = Afis.Identify(pessoaBase, candidatos).ToList();
            var textoMatchs   = pessoasMatchs.Select(p => p.Id);

            foreach (var texto in textoMatchs)
            {
                MessageBox.Show(texto.ToString());
            }
        }
Пример #21
0
        public static Usuario CompararDigital(string nome, string digital, List <string> comparar)
        {
            var Afis = new AfisEngine();

            Fingerprint Digital_Usuario = new Fingerprint();


            Digital_Usuario.AsBitmap = CriaImagem(digital);
            Person Usuario = new Person();

            Usuario.Fingerprints.Add(Digital_Usuario);
            Afis.Extract(Usuario);


            List <Person> Comparadores = new List <Person>();

            foreach (var item in comparar)
            {
                Fingerprint Digital = new Fingerprint();
                Digital.AsBitmap = CriaImagem(digital);
                Person Comparador = new Person();
                Comparador.Fingerprints.Add(Digital);
                Afis.Extract(Comparador);

                Comparadores.Add(Comparador);
            }

            Person Match = Afis.Identify(Usuario, Comparadores).FirstOrDefault();

            if (Match != null)
            {
                var _repo = new Usuario_Service();
                return(_repo.CarregarUsuario(nome));
            }
            else
            {
                return(null);
            }
        }
Пример #22
0
        //public object Get(Files request)
        //{
        //    var targetFile = GetAndValidateExistingPath(request);

        //    var isDirectory = Directory.Exists(targetFile.FullName);

        //    if (!isDirectory && request.ForDownload)
        //        return new HttpResult(targetFile, asAttachment: true);

        //    var response = isDirectory
        //        ? new FilesResponse { Directory = GetFolderResult(targetFile.FullName) }
        //        : new FilesResponse { File = GetFileResult(targetFile) };

        //    return response;
        //}

        //		[AddHeader(ContentType = "text/json")]
        public object Post(Files request)
        {
            //var container = ServiceStackHost.Instance.Container;

            //			var response = new MyPerson { };
            var response  = "";
            var message   = "";
            var uuid      = "";
            var token     = "";
            var targetDir = GetPath(request);

            var isExistingFile = targetDir.Exists &&
                                 (targetDir.Attributes & FileAttributes.Directory) != FileAttributes.Directory;

            if (isExistingFile)
            {
                throw new NotSupportedException(
                          "POST only supports uploading new files. Use PUT to replace contents of an existing file");
            }

            if (!Directory.Exists(targetDir.FullName))
            {
                Directory.CreateDirectory(targetDir.FullName);
            }

            if (base.Request.Files.Length == 0)
            {
                //				message = "No files uploaded.";
            }

            foreach (var key in base.Request.FormData.AllKeys)
            {
                foreach (var val in base.Request.FormData.GetValues(key))
                {
                    if (key == "uuid")
                    {
                        uuid = val;
                        Console.WriteLine(string.Format("{0}: {1}", key, val) + " uuid set to: " + uuid);
                    }
                    else if (key == "key")
                    {
                        token = val;
                        Console.WriteLine(string.Format("{0}: {1}", key, val) + " token set to: " + token);
                    }
                }
            }

            Response jsonResponse = new Response();

            if (token == "noel.honeybee.galvanic")
            {
                foreach (var uploadedFile in base.Request.Files)
                {
                    var newFilePath = Path.Combine(targetDir.FullName, uploadedFile.FileName) + ".png";
                    //					if (uploadedFile.StartsWith("verify") {
                    //					}
                    uploadedFile.SaveTo(newFilePath);

                    // Enroll visitor with unknown identity
                    Guid g;
                    // Create and display the value of two GUIDs.
                    g = Guid.NewGuid();
                    DateTime date1 = DateTime.Now;
                    Console.WriteLine("Starting Enroll:  " + date1);
                    MyPerson probe = SourceAfisIdentify.Enroll(newFilePath, g.ToString(), Afis);
                    // Look up the probe using Threshold = 10
                    Afis.Threshold = 10;
                    DateTime date2 = DateTime.Now;
                    var      list  = FingerprintDatabase.people;
                    //Console.WriteLine("Identifying {0} in Database of {1} persons...", probe.Name, list.Count + " at " + date2);
                    Console.WriteLine("{0} : Identifying {1} in Database of {2} persons...", date2, probe.Name, list.Count);

                    MyPerson match = Afis.Identify(probe, list).FirstOrDefault() as MyPerson;

                    DateTime date3         = DateTime.Now;
                    var      diffInSeconds = (date3 - date2).TotalSeconds;
                    Console.WriteLine("Enroll time:  " + diffInSeconds + " seconds");
                    diffInSeconds = (date2 - date1).TotalSeconds;
                    Console.WriteLine("Total enroll + match time:  " + diffInSeconds + " seconds");


                    // Null result means that there is no candidate with similarity score above threshold
                    if (match == null)
                    {
                        message = "NoMatch";
                        jsonResponse.StatusCode = 4;
                        jsonResponse.Error      = message;
                        jsonResponse.UID        = g.ToString();
                        Console.WriteLine(message);
                        //Database.Add (probe);
                        FingerprintDatabase.AddData(probe);
                        String url = "http://localhost:5984/prints/" + g.ToString();
                        //					String data = "{_id: " + "\"" + g.ToString ()  + "\"" + ", fileName:" + "\""  + uploadedFile.FileName + "\""  + "}";
                        var person = new MyPerson();
                        //					person.Filename = uploadedFile.FileName;
                        person.Uuid = g.ToString();
                        List <Fingerprint>       probleFingerprints = probe.Fingerprints;
                        List <SimpleFingerprint> fingerprints       = new List <SimpleFingerprint>();

                        foreach (var print in probleFingerprints)
                        {
                            byte[] template = print.Template;
                            // Convert the binary input into Base64 UUEncoded output.
                            string base64String = null;
                            try
                            {
                                base64String = System.Convert.ToBase64String(template, 0, template.Length);
                            }
                            catch (System.ArgumentNullException)
                            {
                                System.Console.WriteLine("Binary data array is null.");
                            }

                            SimpleFingerprint fprint = new SimpleFingerprint();
                            fprint.Base64Template = base64String;
                            fprint.Filename       = uploadedFile.FileName;
                            DateTime dateUploaded = DateTime.Now;
                            string   isoJson      = JsonConvert.SerializeObject(dateUploaded, Formatting.None, new IsoDateTimeConverter()
                            {
                                DateTimeFormat = "yyyy-MM-dd hh:mm:ss"
                            });
                            fprint.DateUploaded = isoJson;
                            //fingerprints.Add (fprint);
                            person.simpleFingerprint = fprint;
                        }

                        person.SimpleFingerprints = fingerprints;

                        var json = NServiceKit.Text.JsonSerializer.SerializeToString(person);
                        Console.WriteLine(json);
                        WebClient client = new WebClient();
                        try
                        {
                            client.UploadString(url, "PUT", json);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                        string jsonString = JsonConvert.SerializeObject(jsonResponse);
                        response = jsonString;
                    }
                    else
                    {
                        // Print out any non-null result
                        Console.WriteLine("Probe {0} matches registered person {1}", probe.Uuid, match.Uuid);

                        // Compute similarity score
                        DateTime date4 = DateTime.Now;
                        float    score = Afis.Verify(probe, match);
                        Console.WriteLine("Similarity score between {0} and {1} = {2:F3}", probe.Uuid, match.Uuid, score);
                        DateTime date5 = DateTime.Now;
                        diffInSeconds = (date5 - date4).TotalSeconds;
                        Console.WriteLine("Verify time:  " + diffInSeconds + " seconds");
                        message = "Match: " + probe.Name + " matches " + match.Name + " Score: " + score;

                        jsonResponse.StatusCode = 1;
                        jsonResponse.Error      = null;
                        jsonResponse.UID        = match.Uuid;
                        jsonResponse.Threshold  = score;

                        string jsonString = JsonConvert.SerializeObject(jsonResponse);
                        response = jsonString;
                    }
                }
            }
            else
            {
                jsonResponse.Error = "Auth error.";
                string jsonString = JsonConvert.SerializeObject(jsonResponse);
                response = jsonString;
            }
            return(response);
        }
Пример #23
0
 public tbFingerprint Identify(tbFingerprint probe)
 {
     Afis.Extract(probe);
     return(Afis.Identify(probe, database).FirstOrDefault() as tbFingerprint);
 }
Пример #24
0
        public void SkipBestMatches()
        {
            AfisEngine afis = new AfisEngine();

            Fingerprint[] fps = new[] {
                new Fingerprint()
                {
                    AsBitmap = Settings.SomeFingerprint
                },
                new Fingerprint()
                {
                    AsBitmap = Settings.MatchingFingerprint
                },
                new Fingerprint()
                {
                    AsBitmap = Settings.NonMatchingFingerprint
                }
            };
            foreach (Fingerprint fp in fps)
            {
                afis.Extract(new Person(fp));
            }

            Person person1 = new Person(fps[0]);
            Person person2 = new Person(fps[1], fps[2]);
            Person person3 = new Person(fps[2], fps[1]);
            Person person4 = new Person(fps[1]);
            Person person5 = new Person(fps[1], fps[2], fps[1]);
            Person person6 = new Person(fps[2], fps[1], fps[2]);
            Person person7 = new Person(fps[1], fps[1], fps[1]);
            Person person8 = new Person(fps[2], fps[2]);

            foreach (Person person in new[] { person2, person3, person4, person5, person6, person7 })
            {
                Assert.That(afis.Verify(person1, person) > 0);
            }
            Assert.That(afis.Verify(person1, person8) == 0);
            foreach (Person person in new[] { person2, person3, person4, person5, person6, person7 })
            {
                Assert.That(afis.Identify(person1, new[] { person }).Count() > 0);
            }
            Assert.That(afis.Identify(person1, new[] { person8 }).Count() == 0);

            afis.MinMatches = 2;
            foreach (Person person in new[] { person2, person3, person6, person8 })
            {
                Assert.That(afis.Verify(person1, person) == 0);
            }
            foreach (Person person in new[] { person4, person5, person7 })
            {
                Assert.That(afis.Verify(person1, person) > 0);
            }
            Assert.That(afis.Identify(person1, new[] { person2, person3, person6, person8 }).Count() == 0);
            foreach (Person person in new[] { person4, person5, person7 })
            {
                Assert.That(afis.Identify(person1, new[] { person }).Count() > 0);
            }

            afis.MinMatches = 3;
            foreach (Person person in new[] { person2, person3, person5, person6, person8 })
            {
                Assert.That(afis.Verify(person1, person) == 0);
            }
            Assert.That(afis.Verify(person1, person4) > 0);
            Assert.That(afis.Verify(person1, person7) > 0);
            Assert.That(afis.Identify(person1, new[] { person2, person3, person5, person6, person8 }).Count() == 0);
            Assert.That(afis.Identify(person1, new[] { person4 }).Count() > 0);
            Assert.That(afis.Identify(person1, new[] { person7 }).Count() > 0);

            afis.MinMatches = 4;
            foreach (Person person in new[] { person2, person3, person5, person6, person8 })
            {
                Assert.That(afis.Verify(person1, person) == 0);
            }
            Assert.That(afis.Verify(person1, person4) > 0);
            Assert.That(afis.Verify(person1, person7) > 0);
            Assert.That(afis.Identify(person1, new[] { person2, person3, person5, person6, person8 }).Count() == 0);
            Assert.That(afis.Identify(person1, new[] { person4 }).Count() > 0);
            Assert.That(afis.Identify(person1, new[] { person7 }).Count() > 0);

            Person person9  = new Person(fps[0], fps[0]);
            Person person10 = new Person(fps[1], fps[1], fps[2]);

            afis.MinMatches = 1;
            Assert.That(afis.Verify(person9, person10) > 0);
            afis.MinMatches = 2;
            Assert.That(afis.Verify(person9, person10) > 0);
            afis.MinMatches = 3;
            Assert.That(afis.Verify(person9, person10) > 0);
            afis.MinMatches = 4;
            Assert.That(afis.Verify(person9, person10) > 0);
            afis.MinMatches = 5;
            Assert.That(afis.Verify(person9, person10) == 0);
            afis.MinMatches = 6;
            Assert.That(afis.Verify(person9, person10) == 0);
            afis.MinMatches = 7;
            Assert.That(afis.Verify(person9, person10) == 0);
        }
Пример #25
0
        public void Identify()
        {
            AfisEngine afis    = new AfisEngine();
            Person     person1 = new Person(new Fingerprint()
            {
                AsBitmap = Settings.SomeFingerprint
            });

            afis.Extract(person1);
            Person person2 = new Person(new Fingerprint()
            {
                AsBitmap = Settings.MatchingFingerprint
            });

            afis.Extract(person2);
            Person person3 = new Person(new Fingerprint()
            {
                AsBitmap = Settings.NonMatchingFingerprint
            });

            afis.Extract(person3);

            CollectionAssert.AreEqual(afis.Identify(person1, new[] { person2, person3 }), new[] { person2 });
            CollectionAssert.AreEqual(afis.Identify(person1, new[] { person3, person2 }), new[] { person2 });
            CollectionAssert.AreEqual(afis.Identify(person1, new[] { person3 }), new Person[0]);
            CollectionAssert.AreEqual(afis.Identify(person1, new[] { person2, person3, person1 }), new[] { person1, person2 });

            Person person4 = new Person(person2.Fingerprints[0], person3.Fingerprints[0]);

            CollectionAssert.AreEqual(afis.Identify(person1, new[] { person4 }), new[] { person4 });

            var bigArray = Enumerable.Repeat(person3, 100).Concat(new[] { person2 }).Concat(Enumerable.Repeat(person3, 100));

            CollectionAssert.AreEqual(afis.Identify(person1, bigArray), new[] { person2 });

            CollectionAssert.AreEqual(afis.Identify(person1, new Person[] { }), new Person[0]);
            CollectionAssert.AreEqual(afis.Identify(person1, new[] { new Person() }), new Person[0]);
            CollectionAssert.AreEqual(afis.Identify(new Person(), new[] { person2, person3 }), new Person[0]);

            Assert.Catch(() => { afis.Identify(null, new[] { person2, person3 }); });
            Assert.Catch(() => { afis.Identify(new Person(null), new[] { person2, person3 }); });
            Assert.Catch(() => { afis.Identify(person1, null); });
            Assert.Catch(() => { afis.Identify(person1, new[] { person2, null }); });
            Assert.Catch(() => { afis.Identify(person1, new[] { person2, new Person(null) }); });
        }
        private void btnAutenticar_Click(object sender, EventArgs e)
        {
            List <Person> candidatos = new List <Person>();

            string diretorio;

            try
            {
                SqlCommand cmd = new SqlCommand();
                Conexao    con = new Conexao();


                cmd.Connection  = con.Conectar();
                cmd.CommandText = "SELECT * FROM Usuario";
                SqlDataReader  rd        = cmd.ExecuteReader();
                ImageConverter converter = new ImageConverter();

                if (rd.HasRows)
                {
                    while (rd.Read())
                    {
                        if (Convert.ToInt32(rd["ID_Usuario"]) != 1)
                        {
                            Bitmap bmp;
                            var    img = (byte[])rd["Biometria"];
                            using (var ms = new MemoryStream(img))
                                bmp = new Bitmap(ms);
                            pessoasBd.Add(new Person
                            {
                                Id           = Convert.ToInt32(rd["ID_Usuario"]),
                                Fingerprints = new List <Fingerprint> {
                                    new Fingerprint {
                                        AsBitmap = bmp
                                    }
                                }
                            });
                        }
                    }
                }
                afis.Extract(pessoaBase);
                foreach (var p in pessoasBd)
                {
                    afis.Extract(p);
                }

                var matches = afis.Identify(pessoaBase, pessoasBd);
                if (matches.Any(x => x.Id == pessoaBase.Id))
                {
                    TelaInicio telaInicio = new TelaInicio();
                    telaInicio.Show();
                    this.Hide();
                }
                else
                {
                    MessageBox.Show("Acesso não autorizado, tente novamente!");
                }

                con.desconectar();
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Erro");
            }
        }
Пример #27
0
        public async Task <ActionResult> BulkCreate([Bind(Include = "")] mortal mortal /*, HttpPostedFileBase file*/)
        {
            AfisEngine Afis = new AfisEngine();

            Afis.Threshold = 60;
            //List<MyPerson> personsdks = new List<MyPerson>();
            string    AppPath    = System.IO.Path.Combine(Server.MapPath("~"), "images");
            Stopwatch stopwatch0 = Stopwatch.StartNew(); //creates and start the instance of Stopwatch
            long      range      = Int64.Parse(mortal.nic);

            for (int i = 0; i < range; i++)
            {
                int         imgnumber    = i + 1;
                string      imgval       = "(" + imgnumber.ToString() + ").jpg";
                string      pathtoimages = (System.IO.Path.Combine(AppPath, imgval));
                Fingerprint fp0          = new Fingerprint();
                MyPerson    myperson     = new MyPerson();
                Bitmap      bitmap0      = fp0.AsBitmap = new Bitmap(Image.FromFile(pathtoimages));
                myperson.Fingerprints.Add(fp0);
                Afis.Extract(myperson);
                string str_Template = fp0.AsXmlTemplate.ToString();
                mortal.template = str_Template;
                mortal.name     = (i + 1).ToString();
                mortal.filename = pathtoimages;
                mortal.nic      = (i + 1).ToString();

                //Code to count number of Minutae
                string pattern = "<Minutia";
                int    count   = 0;
                int    a       = 0;
                while ((a = str_Template.IndexOf(pattern, a)) != -1)
                {
                    a += pattern.Length;
                    count++;
                }

                mortal.no_of_minutaes = count;

                db.mortals.Add(mortal);
                //db.Entry(person).State = EntityState.Modified;
                await db.SaveChangesAsync();
            }

            stopwatch0.Stop();
            Stopwatch stopwatch1 = Stopwatch.StartNew(); //creates and start the instance of Stopwatch

            //Verification segment



            string          sql           = "Select * from mortal";
            List <mortal>   personListRom = db.mortals.SqlQuery(sql).ToList();
            List <MyPerson> personListRam = new List <MyPerson>();

            foreach (mortal p in personListRom)
            {
                MyPerson      personTemp = new MyPerson();
                MyFingerprint fpTemp     = new MyFingerprint();
                personTemp.Id        = p.mortalId;
                personTemp.Name      = p.name;
                fpTemp.Filename      = p.filename;
                fpTemp.AsXmlTemplate = XElement.Parse(p.template);
                personTemp.Fingerprints.Add(fpTemp);
                personListRam.Add(personTemp);
            }
            stopwatch1.Stop();
            //verify at 1 index
            Stopwatch stopwatch2 = Stopwatch.StartNew(); //creates and start the instance of Stopwatch

            Fingerprint fp1 = new Fingerprint();

            string apppath     = System.IO.Path.Combine(Server.MapPath("~"), "images");
            string pathToImage = (System.IO.Path.Combine(apppath, "(1).jpg"));

            Bitmap bitmap = fp1.AsBitmap = new Bitmap(Image.FromFile(pathToImage));

            MyPerson personsdk = new MyPerson();

            personsdk.Fingerprints.Add(fp1);
            Afis.Extract(personsdk);

            MyPerson match = Afis.Identify(personsdk, personListRam).FirstOrDefault() as MyPerson;

            stopwatch2.Stop();

            //verify at mid index
            Stopwatch stopwatch3 = Stopwatch.StartNew(); //creates and start the instance of Stopwatch

            Fingerprint fp2 = new Fingerprint();

            string apppath2     = System.IO.Path.Combine(Server.MapPath("~"), "images");
            string pathToImage2 = (System.IO.Path.Combine(apppath, "(" + (range / 2).ToString() + ").jpg"));

            Bitmap bitmap2 = fp2.AsBitmap = new Bitmap(Image.FromFile(pathToImage2));

            MyPerson personsdk2 = new MyPerson();

            personsdk2.Fingerprints.Add(fp2);
            Afis.Extract(personsdk2);

            MyPerson match2 = Afis.Identify(personsdk2, personListRam).FirstOrDefault() as MyPerson;

            stopwatch3.Stop();

            Stopwatch stopwatch4 = Stopwatch.StartNew(); //creates and start the instance of Stopwatch

            Fingerprint fp3          = new Fingerprint();
            Random      rand         = new Random();
            int         num          = rand.Next(3);
            string      apppath3     = System.IO.Path.Combine(Server.MapPath("~"), "images");
            string      pathToImage3 = (System.IO.Path.Combine(apppath, "(" + num.ToString() + ").jpg"));

            Bitmap bitmap3 = fp3.AsBitmap = new Bitmap(Image.FromFile(pathToImage3));

            MyPerson personsdk3 = new MyPerson();

            personsdk3.Fingerprints.Add(fp3);
            Afis.Extract(personsdk3);

            MyPerson match3 = Afis.Identify(personsdk3, personListRam).FirstOrDefault() as MyPerson;

            stopwatch4.Stop();

            string stopwatchtime0 = stopwatch0.ElapsedMilliseconds.ToString();
            string stopwatchtime1 = stopwatch1.ElapsedMilliseconds.ToString();
            string stopwatchtime2 = stopwatch2.ElapsedMilliseconds.ToString();
            string stopwatchtime3 = stopwatch3.ElapsedMilliseconds.ToString();
            string stopwatchtime4 = stopwatch4.ElapsedMilliseconds.ToString();


            Response.Write("<script>alert('Enrollment time in database is:" + stopwatchtime0 + "');</script>");
            Response.Write("<script>alert('Enrollment time in ram is:" + stopwatchtime1 + "');</script>");
            Response.Write("<script>alert('Verification time for index 1:" + stopwatchtime2 + "');</script>");
            Response.Write("<script>alert('Verification time for index mid:" + stopwatchtime3 + "');</script>");
            Response.Write("<script>alert('Verification time for index last:" + stopwatchtime4 + "');</script>");

            return(View(mortal));
        }