Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't load CascadeClassifier

Tags:

android

opencv

I have tried to load cascade classifier in Android app, but the following condition always returns true and therefore the code can't be executed successfully:

cascadeClassifier.empty()

The code is the following:

try
        {
            InputStream is = getResources().openRawResource(R.raw.cascade);
            File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
            mCascadeFile = new File(cascadeDir, "cascade.xml");
            FileOutputStream os = new FileOutputStream(mCascadeFile);


            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = is.read(buffer)) != -1)
            {
                os.write(buffer, 0, bytesRead);
            }

            is.close();
            os.close();

            // Load the cascade classifier
            cascadeClassifier = new CascadeClassifier(mCascadeFile.getAbsolutePath());
            if (cascadeClassifier.empty()) {
                Log.e(TAG, "Failed to load cascade classifier");
                cascadeClassifier = null;
            }
        }
        catch (Exception e)
        {
            Log.e("OpenCVActivity", "Error loading cascade", e);
        }

The cascade.xml file is stored in raw folder and I have successfully tested it with python script - it successfully detects objects.

If this answer holds true, then I don't know what could be wrong in the code above as the trained cascade has been tested and the input stream is seems to be pointing to correct location (autocomplete lists R.raw.cascade).

I would be very thankful if anyone helped solve the issue.

like image 490
Niko Gamulin Avatar asked Mar 08 '16 11:03

Niko Gamulin


1 Answers

The problem was solved by adding the following line after instantiating CascadeClassifier:

cascadeClassifier.load(mCascadeFile.getAbsolutePath());

The working code is the following:

InputStream is = getResources().openRawResource(R.raw.object_detector);
File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "cascade.xml");
FileOutputStream os = new FileOutputStream(mCascadeFile);


byte[] buffer = new byte[4096];
int bytesRead;

while ((bytesRead = is.read(buffer)) != -1)
{
    os.write(buffer, 0, bytesRead);
    Log.d(TAG, "buffer: " + buffer.toString());
}
is.close();
os.close();
// Load the cascade classifier
cascadeClassifier = new CascadeClassifier(mCascadeFile.getAbsolutePath());
cascadeClassifier.load(mCascadeFile.getAbsolutePath());
if (cascadeClassifier.empty()) {
    Log.e(TAG, "Failed to load cascade classifier");
    cascadeClassifier = null;
}
like image 177
Niko Gamulin Avatar answered Nov 11 '22 01:11

Niko Gamulin