Train model using android studio and opencv -


i developed app train svm model using opencv app crashes without message , model can not saved while model saved correctly can not test part. note app working correctly , trained model saved without error.

any idea causes this.

this manifest file

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.as9221.svmclassifier">     <uses-permission android:name="android.permission.camera"/>     <uses-feature android:name="android.hardware.camera" android:required="false"/>     <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>     <uses-feature android:name="android.hardware.camera.front" android:required="false"/>     <uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>      <uses-permission android:name="android.permission.read_external_storage" />     <uses-permission android:name="android.permission.write_external_storage" />      <application         android:allowbackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:roundicon="@mipmap/ic_launcher_round"         android:supportsrtl="true"         android:keepscreenon="true"         android:theme="@style/apptheme">         <activity android:name=".mainactivity">             <intent-filter>                 <action android:name="android.intent.action.main" />                  <category android:name="android.intent.category.launcher" />             </intent-filter>         </activity>     </application>  </manifest> 

this activity file

import android.manifest; import android.app.activity; import android.content.context; import android.content.intent; import android.content.pm.packagemanager; import android.os.environment; import android.os.handler; import android.provider.mediastore; import android.support.v4.app.activitycompat; import android.support.v4.content.contextcompat; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.util.log; import android.view.view; import android.widget.button; import android.widget.toast;  import org.opencv.android.baseloadercallback; import org.opencv.android.loadercallbackinterface; import org.opencv.android.opencvloader; import org.opencv.core.cvtype; import org.opencv.core.mat; import org.opencv.core.matoffloat; import org.opencv.core.scalar; import org.opencv.core.termcriteria; import org.opencv.ml.cvsvm; import org.opencv.ml.cvsvmparams;  import java.io.file; import java.io.filenotfoundexception; import java.io.ioexception; import java.util.scanner;  public class mainactivity extends appcompatactivity {     private static context mcontext;     private static handler mhandler;     private static cvsvm classifier;     private static cvsvm svmd;        protected static final string tag = "mainactivity";      static {         if (!opencvloader.initdebug()) {             // handle initialization error         }     }      private baseloadercallback mloadercallback = new baseloadercallback(this) {         @override         public void onmanagerconnected(int status) {             switch (status) {                 case loadercallbackinterface.success: {                     log.i(tag, "opencv loaded successfully");                  }                 break;                 default: {                     super.onmanagerconnected(status);                 }                 break;             }         }     };      @override     public void onresume() {         super.onresume();         opencvloader.initasync(opencvloader.opencv_version_2_4_13, this, mloadercallback);     }      /**      * called when activity first created.      */      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         mcontext = getapplicationcontext();         mhandler = new handler();          setcontentview(r.layout.activity_main);         if (packagemanager.permission_granted == contextcompat.checkselfpermission(this, manifest.permission.camera)) {             log.d(tag, "everything should fine using camera.");         } else {             log.d(tag, "requesting permission use camera.");             string[] camera_permissons = {                     manifest.permission.camera             };             activitycompat.requestpermissions(this, camera_permissons, 0);         }          button buttontrain = (button) findviewbyid(r.id.takepicture);         buttontrain.setonclicklistener(new view.onclicklistener() {              @override             public void onclick(view arg0) {                 boolean result = utility.checkpermission(mainactivity.this);                 if (result) {                     try {                         svmclassifier.svm1classifier();                     } catch (ioexception e) {                         e.printstacktrace();                     }                  }             }         });     }      public static void svm1classifier() throws ioexception {          mat trainingdata = new mat();         mat testingdata = new mat();         mat traininglabels = new mat();         matoffloat v_descriptors = new matoffloat();         matoffloat descriptors = new matoffloat();         mat classes = new mat();         string featurevector = null;         matoffloat v_features = new matoffloat();         file xml = new file(environment.getexternalstoragepublicdirectory(environment.directory_pictures)+ file.separator+"test.xml");          file xml1 = new file(environment.getexternalstoragepublicdirectory(environment.directory_pictures)+ file.separator+"test1.xml");         boolean  done = false;          //matoffloat v_features = new matoffloat();         matoffloat vt_features = new matoffloat();          int trainingrows = 78;         int trainingcols = 18;         mat trainingdatamat = new mat(trainingrows, trainingcols, cvtype.cv_32f);         mat testingdatamat = new mat(1, trainingcols, cvtype.cv_32f);           featurevector = "featurevector";         double[][] traininglist = new double[trainingrows][trainingcols];          traininglist = readfromfile(featurevector, trainingrows, trainingcols);          for(int i=0; i<trainingrows; i++){             mat a_row = new mat(1, trainingcols, cvtype.cv_32f); // **local** mat w. correct size , type             for(int j=0; j<trainingcols; j++) {                 log.i(tag, "data of data" + "[" + + "," + j + "]" + " " + traininglist[i][j]);                 a_row.put(0, j, traininglist[i][j]);                 log.i(tag, "data of a_row" + "[" + + "," + j + "]" + " " + a_row.get(0,j)[0]);             }             v_features.push_back(a_row); // no need reshape, it's row.             log.i(tag, "now push values" + v_features);           }          featurevector = "label";         int[] labellist = new int[trainingrows];         labellist = readfromfile1(featurevector);         for(int i=0;i<trainingrows;i++){             log.i(tag, "data of label " + "[" + + "]" + " " + labellist[i]);             mat labelsmat = new mat(1, 1, cvtype.cv_32s, new scalar(labellist[i]));             traininglabels.push_back(labelsmat);         }          log.i(tag,"training...");         v_features.copyto(trainingdata);         trainingdata.convertto(trainingdata, cvtype.cv_32f);         traininglabels.copyto(classes);         classes.convertto(classes, cvtype.cv_32s);         //correct code.         cvsvm svm = new cvsvm();         cvsvmparams params = new cvsvmparams();         params.set_svm_type(cvsvm.c_svc);         params.set_kernel_type(cvsvm.linear);         //only c considered when use linear , c_svc         params.set_c(100);         params.set_term_crit(new termcriteria(termcriteria.eps, 100, 1e-6));         svm.train(trainingdata, classes, new mat(), new mat(), params);         svm.save(xml.tostring());          /*int kfolds = 10;         cvsvm svm = new cvsvm();         cvsvmparams params = new cvsvmparams();         params.set_svm_type(cvsvm.c_svc);         params.set_kernel_type(cvsvm.linear);         params.set_term_crit(new termcriteria(termcriteria.eps, 100, 1e-12));         cvparamgrid c = new cvparamgrid();         cvparamgrid p = new cvparamgrid();         cvparamgrid nu = new cvparamgrid();         cvparamgrid gamma = new cvparamgrid();         cvparamgrid coeff = new cvparamgrid();         cvparamgrid degree = new cvparamgrid();         p.set_step(0);         nu.set_step(0);         coeff.set_step(0);         degree.set_step(0);         svm.train_auto(trainingdata, classes, new mat() , new mat() , params, kfolds, c, gamma, p, nu, coeff, degree, false);         svm.save(xml.tostring());*/          log.i(tag,"training done & trained model saved");          done = true;          log.i(tag,"testing...");          int testingrow = 10;         mat resultmat = new mat(testingrow, 1, cvtype.cv_32f);          featurevector = "featurevectormixed";         double[][] testinglist = new double[testingrow][trainingcols];         testinglist = readfromfile(featurevector, testingrow, trainingcols);         for(int i=0;i<testingrow;i++) {             mat b_row = new mat(1, trainingcols, cvtype.cv_32f); // **local** mat w. correct size , type             (int j = 0; j < trainingcols; j++) {                 log.i(tag, "data of test" + "[" + + "," + j + "]" + " " + testinglist[i][j]);                 b_row.put(0, j, testinglist[i][j]);                 log.i(tag, "data of b_row" + "[" + + "," + j + "]" + " " + b_row.get(0,j)[0]);              }             vt_features.push_back(b_row); // no need reshape, it's row.         }          vt_features.copyto(testingdata);         testingdata.convertto(testingdata, cvtype.cv_32f);         // test prediction loading classifier         svmd = new cvsvm();         log.i(tag, "test path: " + xml.tostring());         svmd.load( xml.tostring());         //since have more 1 sample         svmd.predict_all(testingdata, resultmat);         //classifier.predict_all(testingdata, resultmat);          for(int i=0;i<testingrow;i++) {             (int j = 0; j < 1; j++) {                 log.i(tag, "data of result " + resultmat.get(i, j)[0]);              }         }         //return done;      }      private static double[][] readfromfile(string filename, int row, int col) {         scanner scan;         int linecount = 0;         double[][] featurevalues = new double[row][col];         try {             final file dir = new file(environment.getexternalstoragedirectory().getabsolutepath() + "/directory_feature/" );             final file myfile = new file(dir, filename + ".txt");             scan = new scanner(myfile);              while (scan.hasnextline()) {                 string[] currentline = scan.nextline().trim().split("\t");                 (int = 0; < currentline.length; i++) {                     featurevalues[linecount][i] = double.parsedouble(currentline[i]);                     //log.i(tag, "data of test " + linecount + " " + + " " + double.parsedouble(currentline[i]));                 }                 linecount++;             }             scan.close();          } catch (filenotfoundexception e1) {             e1.printstacktrace();         }         return featurevalues;     }      private static double[][] readfromfilet(string filename, int row, int col) {         scanner scan;         int linecount = 0;         double[][] featurevalues = new double[row][col];         try {             final file dir = new file(environment.getexternalstoragedirectory().getabsolutepath() + "/directory_feature/" );             final file myfile = new file(dir, filename + ".txt");             scan = new scanner(myfile);              while (scan.hasnextline()) {                 string[] currentline = scan.nextline().trim().split(" ");                 (int = 0; < currentline.length; i++) {                     featurevalues[linecount][i] = double.parsedouble(currentline[i]);                     //log.i(tag, "data of test " + linecount + " " + + " " + double.parsedouble(currentline[i]));                 }                 linecount++;             }             scan.close();          } catch (filenotfoundexception e1) {             e1.printstacktrace();         }         return featurevalues;     }      private static int[] readfromfile1(string filename) {         scanner scan;         int linecount = 0;         // should change variable         int[] labelvalues = new int[78];          try {             final file dir = new file(environment.getexternalstoragedirectory().getabsolutepath() + "/directory_feature/" );             final file myfile = new file(dir, filename + ".txt");             scan = new scanner(myfile);              while (scan.hasnextint()) {                 labelvalues[linecount] = scan.nextint();                 linecount++;             }              scan.close();          } catch (filenotfoundexception e1) {             e1.printstacktrace();         }         return labelvalues;     }       public void showtoast(final string msg) {         final activity = mainactivity.this;         if (a != null ) {             a.runonuithread(new runnable() {                  @override                 public void run() {                     toast.maketext(a, msg, toast.length_short).show();                 }             });         }     }     protected void onhandleintent(intent intent) {         mhandler.post(new runnable() {             @override             public void run() {                 toast.maketext(mcontext, "test", toast.length_long).show();             }         });     }  } 


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -