Search code examples
c#opencvemgucvface-detectionface-recognition

'Emgu.CV.Util.CvException' occurred in 'Emgu.CV.World.dll' - When trying to Predict


I am developing a face recognition application usin EmguCV 3.1. And I am using EigenFaceRecognizer as the recognition algorithm. I tried to train an image using the code below.

    List<Image<Gray, byte>> trainingImages = new List<Image<Gray, byte>>();
    FaceRecognizer recognizer;
    List<Face> faceList = new List<Face>();
        ...
        ...
        recognizer = new EigenFaceRecognizer(80, double.PositiveInfinity);
        ...
        ...            
        Image<Gray, byte> image = new Image<Gray, byte>(imgBox2.DisplayedImage.Bitmap);
        trainingImages.Add(image);
        List<int> trainigLabels = new List<int>();
        recognizer.Train(trainingImages.ToArray(), trainigLabels.ToArray());
        recognizer.Save("TraningData");
        faceList.Add(new Face(image.Bytes.Length, txtName.Text));
        ...
        ...
        Image<Gray, byte> image = new Image<Gray, byte>(imgBox2.DisplayedImage.Bitmap);
            recognizer.Load("TraningData");
            try
            {
                var result = recognizer.Predict(image);
                MessageBox.Show(result.Label.ToString());
            }
            catch (Emgu.CV.Util.CvException ex)
            {
                Console.WriteLine(ex);
            }

But when this code is invoked it gives me following error.

A first chance exception of type 'Emgu.CV.Util.CvException' occurred in Emgu.CV.World.dll
The program '[1136] IPTest.vshost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
The program '[1136] IPTest.vshost.exe: Program Trace' has exited with code 0 (0x0).

It is occurring while trying to use recognizer.Train(). What have I done wrong?

UPDATE
After some trial and error I got to know that problem is with recognizer.Predict() method.
When I used try/catch it shows the following exception

Emgu.CV.Util.CvException: OpenCV: The matrix is not continuous, thus its number of rows can not be changed

Solution

  • Ok I found the solution. Problem isn't with my code. It is thrown when native code is trying to access some memory locations which is corrupted or it doesn't have access to.
    So I found a easy and working solution.

    try
    {
       var result = recognizer.Predict(image);
    }
    catch (System.AccessViolationException)
    {
       recognier =  new EigenFaceRecognizer(80, double.PositiveInfinity);
    }
    

    But you can't catch AccessViolationException in runtime. So you have to change settings so that you can. For that you can follow this question and answers.