2016-02-23 3 views
-1

Я иду в приложение-приложение для примера sourceAFIS, оно отлично работает. Я пытаюсь адаптировать образец для чтения изображений отпечатков пальцев из формы окна и получал исключение NullReferenceException в методе extract.Я получаю исключение Null Pointer Exception при извлечении «Afis.Extract()» извлечения отпечатка пальца с использованием sourceAFIS

Я включил отладку повсюду, но не смог увидеть, откуда это происходит.

class FingerprintProcessor 
{ 
    // Shared AfisEngine instance (cannot be shared between different threads though) 
    static AfisEngine Afis; 
    public static MyPerson EnrollCustomer(string fileName, Customer cust) 
    //static CustomerBio EnrollCustomer(Customer cust, FingerprintData custFingerprint) 
    { 
     Console.WriteLine("Enrolling {0}...", cust.FirstName); 

     // Initialize empty fingerprint object and set properties 
     CustomerFingerprint fp = new CustomerFingerprint(); 
     fp.Filename = fileName; 
     // Load image from the file 
     Console.WriteLine(" Loading image from {0}...", fileName); 
     BitmapImage image = new BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute)); 
     fp.AsBitmapSource = image; 
     // Above update of fp.AsBitmapSource initialized also raw image in fp.Image 
     // Check raw image dimensions, Y axis is first, X axis is second 
     MessageBox.Show(fp.Image.GetLength(1) +" "+ fp.Image.GetLength(0)); 

     // Initialize empty person object and set its properties 
     MyPerson customer = new MyPerson(); 
     customer.Name = cust.FirstName; 
     // Add fingerprint to the person 
     customer.Fingerprints.Add(fp); 

     // Execute extraction in order to initialize fp.Template 
     Console.WriteLine(" Extracting template..."); 
     try 
     { 
       Afis.Extract(customer); This is where the NullReference is thrown. 
     catch (Exception e1) { 
      MessageBox.Show(e1.ToString()); 
     } 
     // Check template size 
     Console.WriteLine(" Template size = {0} bytes", fp.Template.Length); 

     return customer; 
    } 




class MyPerson :Person 
{ 
    public string Name { get; set; } 

    public MyPerson processCustomer(Customer aCust) 
    { 
     return new MyPerson 
     { 
      Name = aCust.FirstName + " " + aCust.LastName, 
     }; 
    } 
} 




    private void btnSaveCustomer_Click(object sender, EventArgs e) 
    { 
     // Initialize SourceAFIS 
     Afis = new AfisEngine(); 
     try 
     { 
      FaceRecEntities custEnt = new FaceRecEntities(); 

      var allCustomers=custEnt.Customers.Select(theCusts=> new MyPerson{Name=theCusts.FirstName, 
      /*CFingerprint=theCusts.FingerprintImage*/}).AsEnumerable(); 

      Customer cust = new Customer(); 

      cust.FirstName = txtFirstName.Text; 
      cust.LastName = txtLastName.Text; 
      cust.PhoneNo = textBox1.Text; 
      cust.Email = txtPhone.Text; 
      cust.Picture = imgConversion.ConvertFileToByte(this.pictureBoxPhoto.ImageLocation); 
      cust.FingerprintImage = imgConversion.ConvertFileToByte(this.pictureBoxFingerPrint1.ImageLocation); 

      //MyPerson customerBio=new MyPerson().processCustomer(cust); 

      MyPerson customerBio = new MyPerson(); 

      try 
      { 
       FingerprintProcessor.EnrollCustomer(this.pictureBoxFingerPrint1.ImageLocation, cust); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.ToString(),"The Enroll Not Working"); 
      } 
      Afis.Threshold = 10; 

      MyPerson match = Afis.Identify(customerBio, allCustomers).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."); 
       MessageBox.Show("No matching person found."); 

       return; 
      } 
      MessageBox.Show("Probe " +customerBio.Name+ " matches registered person "+ match.Name); 

      // Compute similarity score 
      float score = Afis.Verify(customerBio, match); 
      Console.WriteLine("Similarity score between {0} and {1} = {2:F3}", customerBio.Name, match.Name, score); 

      custEnt.Customers.Add(cust); 
      custEnt.SaveChanges(); 
      MessageBox.Show("Customer Save Success"); 

     } 
     catch(Exception ex) 
     { 
      MessageBox.Show(ex.ToString(),"Can't add customer"); 
     } 
    } 
+2

* Я включил отладку повсюду, но не смог увидеть, откуда это происходит. * Прочитайте трассировку стека. Проводя его в ваш вопрос, также будет хорошей идеей, если его чтение не сразу решит вашу проблему. –

ответ

0

static AfisEngine Afis не инициализирован в вашем классе. Либо вы должны инициализировать его в статическом классе -

class FingerprintProcessor 
{ 
    static AfisEngine Afis = new AfisEngine(); 
} 

И не инициализировать статическую переменную внутри btnSaveCustomer_Click.

private void btnSaveCustomer_Click(object sender, EventArgs e) 
{ 
    // Initialize SourceAFIS 
    Afis = new AfisEngine(); // this is wrong if its static variable. 
} 

Предполагая, что если вы хотели АДИС быть переменной экземпляра, то вам нужно передать его в качестве параметра для статического класса, как это.

public static MyPerson EnrollCustomer(string fileName, Customer cust, AfisEngine Afis) 
{ 
... 
} 
+0

Это сработало. Был запас этот момент в течение многих дней. Интересно, почему ошибка не могла быть более объяснительной. – user1823354

+0

NullReferenceException самоочевидно! Вам просто нужно найти, было ли оно инициализировано или нет – CarbineCoder