Niko Gamulin Niko Gamulin - 6 months ago 31
Android Question

Can't load CascadeClassifier

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.

Answer

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;
}