Can't load CascadeClassifier - android

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.

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

Related

Why Bitmap Factory return null while decoding stream from FileInputStream obj?

I'm hitting an URL and saving the returned image response in cache dir. If I try to save Bitmap from Returned response inputstream then I get correct Bitmap. Now after saving that response inputstream in cache and after fetching it I'm getting null Bitmap
Write inputStream to cache dir -
String root = mContext.getCacheDir().toString();
String path = root + "/tomorrow.jpg";
try {
final File file = new File(path);
final OutputStream output = new FileOutputStream(file);
try {
try {
final byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) != -1)
output.write(buffer, 0, ch);
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}
now I'm reading the file from cache dir -
FileInputStream fin = null;
try {
fin = new FileInputStream(new File(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp1 = BitmapFactory.decodeStream(fin);
I'd like to thanks Dimitri Budiansky for guiding me. Fix as below-
//final byte[] buffer = new byte[1024];
//int ch;
//while ((ch = in.read(buffer)) != -1)
//output.write(buffer, 0, ch);
I commented above lines. Simply add below line.
bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
for clarification u may check this Link

android app connecting to google drive and downloading a file to sd card

My android app connects to google drive and checks for a file on the drive, if the file isn't present then it downloads it to sdcard. the following code does the downloading .
the problem that occurs is that the file which gets downloaded is showing 0 bytes after downloading. please help me locate the error in the code. thanks for helping out .
private void savefile(String filename, InputStream in , Boolean replace ) {
try {
java.io.File f = new java.io.File(filename);
logonscreen("trying to savefile :"+filename);
if(replace) {
showToast("replace:"+replace.toString());
OutputStream stream = new BufferedOutputStream(new FileOutputStream(filename));
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = in.read(buffer)) != -1) {
stream.write(buffer, 0, len);
}
if(stream!=null) {
stream.close();
}
} else {
showToast("replace: "+replace.toString()+" , file exists " + f.exists());
if(f.exists()== false) {
OutputStream stream = new BufferedOutputStream(new FileOutputStream(filename));
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = in.read(buffer)) != -1) {
stream.write(buffer, 0, len);
}
if(stream!=null) {
stream.close();
}
}
}
//Do something
} catch (IOException e) {
// TODO: handle exception
logonscreen("exception at Save File:" +filename + "exception" + e.getMessage());
// showToast("exception:" + e.getMessage());
} catch (Exception e) {
logonscreen("exception at Save File:" + e.getMessage());
// showToast("exception:" + e.getMessage());
e.printStackTrace();
}
}

Read 1mb size of .bin file from Assests folder in android eclipse in linux environment

This is my code for Reading .bin file. name:Testfile.bin location : Assets
In the byteRead(pathtobinfile) function I want to pass bin file path as a String.
how to get the bin file path. Any idea please!!!
public byte[] byteRead(String aInputFileName)
{
File file = new File(aInputFileName);
byte[] result = new byte[(int)file.length()];
try {
InputStream input = null;
try {
int totalBytesRead = 0;
input = new BufferedInputStream(new FileInputStream(file));
while(totalBytesRead < result.length){
int bytesRemaining = result.length - totalBytesRead;
//input.read() returns -1, 0, or more :
int bytesRead = input.read(result, totalBytesRead, bytesRemaining);
if (bytesRead > 0){
totalBytesRead = totalBytesRead + bytesRead;
}
}
}
finally {
//log("Closing input stream.");
input.close();
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
Log.d("File Length", "Total No of bytes"+ result.length);
return result;
}
Any help?
Implement following code, which I modified as per your requirement. I have tested it and working very well.
public byte[] byteRead(String aInputFileName) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
InputStream input = getResources().getAssets().open(aInputFileName);
try {
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) != -1) {
baos.write(buffer, 0, read);
}
} finally {
input.close();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
Log.d("Home", "Total No of bytes : " + baos.size());
return baos.toByteArray();
}
Input
You can use this function like this.
byte[] b = byteRead("myfile.txt");
String str = new String(b);
Log.d("Home", str);
Output
09-16 12:25:34.340: DEBUG/Home(4552): Total No of bytes : 10
09-16 12:25:34.340: DEBUG/Home(4552): hi Chintan
Its a very easy to read bin file from Asset folder.
Hope this will help someone.
InputStream input = context.getAssets().open("Testfile.bin");
// myData.txt can't be more than 2 gigs.
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();

File writing in external storage device is not working

I tried writing a file to my android phone using phonegap ui.
I have given the write permission and i tried by using getExternalStorageDirectory() and by giving the absolute path. But still not able to write it.
s1 is the name of the file that i am writing in the external storage
Environment.getExternalStorageState();
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/Android/");
File file = new File("/mnt/sdcard"+ File.separator + "Android" + File.separator);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Folder");
}
}
Environment.getExternalStorageState();
File outputFile = new File(file, s1);
FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
byte abyte0[] = new byte[1024];
for (int i = 0; (i = inputstream.read(abyte0)) > 0;)
fileoutputstream.write(abyte0, 0, i);
fileoutputstream.close();
inputstream.close();
I wrote a quick working demo of writing a file to the external storage.
If this still doesn't work maybe it is a phonegap specific issue.
Hope this helps:
InputStream is = null;
OutputStream os = null;
byte[] buffer = new byte[2048];
int bytes_read = 0;
File inputFile = new File("/init.rc");
File outputFile = new File(Environment.getExternalStorageDirectory() + "/testfile");
try
{
is = new FileInputStream(inputFile);
os = new FileOutputStream(outputFile);
while ((bytes_read = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytes_read);
}
}
catch (Exception ignore) {}
finally
{
try
{
is.close();
}
catch (Exception ignore) {}
try
{
os.close();
}
catch (Exception ignore) {}
}
if (outputFile.exists())
{
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Failure!", Toast.LENGTH_LONG).show();
}

Android - some unzipped files have 0 size (are empty)

i'm facing a problem with unzipping files in Android. Here is the code snippet:
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
BufferedInputStream in = new BufferedInputStream(fin);
ZipInputStream zin = new ZipInputStream(in);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
BufferedOutputStream out = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int length;
while ((length = zin.read(buffer,0,1024)) >= 0) {
out.write(buffer,0,length);
}
/* while ((length = zin.read(buffer))>0) {
out.write(buffer, 0, length);
}*/
/*for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}*/
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
Smaller files (smaller than 10kB) are unzipped like empty - size 0 (html files, .jpg). Other files are ok. If I use this same code, but without buffers all the files are ok - ofcourse, unzipping without buffers is out of the question since it runs too long. Files are stored on SD card on real device. I have already tried setting smaller buffer size ( even new byte[2]). Thanks in advance...
Try this code instead,
public void doUnzip(String inputZipFile, String destinationDirectory)
throws IOException {
int BUFFER = 2048;
List zipFiles = new ArrayList();
File sourceZipFile = new File(inputZip);
File unzipDestinationDirectory = new File(destinationDirectory);
unzipDestinationDirectory.mkdir();
ZipFile zipFile;
// Open Zip file for reading
zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
// Create an enumeration of the entries in the zip file
Enumeration zipFileEntries = zipFile.entries();
// Process each entry
while (zipFileEntries.hasMoreElements()) {
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(unzipDestinationDirectory, currentEntry);
// destFile = new File(unzipDestinationDirectory, destFile.getName());
if (currentEntry.endsWith(".zip")) {
zipFiles.add(destFile.getAbsolutePath());
}
// grab file's parent directory structure
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
try {
// extract file if not a directory
if (!entry.isDirectory()) {
BufferedInputStream is =
new BufferedInputStream(zipFile.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest =
new BufferedOutputStream(fos, BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
zipFile.close();
for (Iterator iter = zipFiles.iterator(); iter.hasNext();) {
String zipName = (String)iter.next();
doUnzip(
zipName,
destinationDirectory +
File.separatorChar +
zipName.substring(0,zipName.lastIndexOf(".zip"))
);
}
}

Categories

Resources