Error when tring to train image with opencv and android

asked 2016-04-14 05:18:02 -0600

jack1 gravatar image

updated 2016-04-14 06:35:47 -0600

berak gravatar image
  public class MainActivity extends Activity {
Button button;

ImageView res4;
TextView T1;
private static final String TAG = "training";

private BaseLoaderCallback mLoaderCallBack = new BaseLoaderCallback(this) {
    public void onManagerConnected(int status) {
        switch (status) {
        case LoaderCallbackInterface.SUCCESS:
            Log.i(TAG, "Open CV loaded successfully");
            break;

        default:
            super.onManagerConnected(status);
            break;
        }
    };
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.activity_main);
    addListenerOnButton();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onResume() {
    super.onResume();
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this,mLoaderCallBack);

}



public void addListenerOnButton() {

//  imageView = (ImageView) findViewById(R.id.imageView1);

    res4 = (ImageView) findViewById(R.id.imageView2);
    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new OnClickListener() {



        @Override
        public void onClick(View arg0) {


                try {

                train();

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

    });

}
public void train (){
        //Creating Training Data
     String path = Environment.getExternalStorageDirectory().toString();                  
     Mat trainData = new Mat(); 
     Mat response_array = new Mat();
    Mat img =Imgcodecs.imread("/storage/emulated/0/DCIM/Camera/n1.png");
    img.convertTo(img, CvType.CV_32FC1);
     Size dsize = new Size(50, 50); 
     Imgproc.resize(img, img, dsize);  
     img.convertTo(img, CvType.CV_32FC1);
     Mat imgResized = img.reshape(1, 1);   
     trainData.push_back(imgResized);
     Mat response = new Mat();
     Mat tmp; 
     tmp=response_array.reshape(1,1); //make continuous  `
     tmp.convertTo(response,CvType.CV_32FC1); // Convert  to float  
     KNearest knn = KNearest.create();
     knn.train(trainData,Ml.ROW_SAMPLE, response);

     //For Storing training data
    Bitmap bmpOut1 = Bitmap.createBitmap(trainData.cols(), trainData.rows(), Bitmap.Config.ARGB_8888);
    trainData.convertTo(trainData,CvType.CV_8UC1); 
    Utils.matToBitmap(trainData, bmpOut1);
    File file = new File(path);  
    file.mkdirs(); 
    File file1 = new File(path, "train.png"); 
    OutputStream fout = null;
     try {  fout = new FileOutputStream(file1); 
     BufferedOutputStream bos = new BufferedOutputStream(fout); 
     bmpOut1.compress(Bitmap.CompressFormat.PNG, 100, bos);
     bos.flush(); 
     bos.close();  
     bmpOut1.recycle(); 
     }
     catch (FileNotFoundException e) { e.printStackTrace(); }
     catch (IOException e) {e.printStackTrace();}

     //For Accessing training data in BMP file  

     BitmapFactory.Options o = new BitmapFactory.Options(); 
     o.inScaled = false;
     Bitmap blankBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.train,o);
     int trainWidth = blankBitmap.getWidth();
     int trainHeight = blankBitmap.getHeight();
     Mat trainData2 = new Mat();
     Utils.bitmapToMat(blankBitmap,trainData2); 
     Mat trainData3 = new Mat();
     Mat response3 = new Mat();

     Imgproc.cvtColor(trainData2,trainData2,Imgproc.COLOR_BGRA2GRAY); // 1. change the number of channels; 
     trainData2.convertTo(trainData3,CvType.CV_32FC1); 
     KNearest knn2 = KNearest.create();
     knn.train(trainData3,Ml.ROW_SAMPLE, response3);

}
 }

I get these errors .Please help me and also i don't know how can i recognize my code

04-14 11:57:29.550: I/art(7070): Ignoring second debugger -- accepting and dropping
04-14 11:57:43.890: D/PhoneWindow(9670): *FMB* installDecor mIsFloating : false
04-14 11:57:43.890: D/PhoneWindow(9670): *FMB* installDecor flags : 8454400
04-14 11:57:44.040: D/OpenGLRenderer(9670): Render dirty regions requested: true
04-14 11:57:44.100: D/PhoneWindow(9670): *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
04-14 11:57:44.100: D/PhoneWindow(9670): *FMB* isFloatingMenuEnabled return false
04-14 11:57:44.150: D/SRIB_DCS(9670): log_dcs ThreadedRenderer::initialize entered! 
04-14 11:57:44.150: I/Adreno-EGL(9670): <qeglDrvAPI_eglInitialize:379>: EGL 1 ...
(more)
edit retag flag offensive close merge delete

Comments

1

for various reasons, please give us the text version of your logcat output, not a useless screenshot

then,

  • please do not use a hardcoded storage path.
  • please check, if imread actually succeeded. (i guess, not)
  • your responses Mat looks invalid (there is nothing in it)
  • you need more than 1 sample/response to train knn
berak gravatar imageberak ( 2016-04-14 05:39:00 -0600 )edit

I am really sorry but i am confused i don't understand the logic of this algorithm .Where should i put sample /response for training

jack1 gravatar imagejack1 ( 2016-04-14 06:06:01 -0600 )edit

again, please add logcat text output

berak gravatar imageberak ( 2016-04-14 06:13:13 -0600 )edit

I am sorry ,i add it Yes as you said the img is empty :( i will try to solve this error and i will come back with more specific error

jack1 gravatar imagejack1 ( 2016-04-14 06:22:46 -0600 )edit

I am really sorry but i am confused i don't understand the logic of this algorithm --> then why don't you start by reading the paper of this technique first so that you fully understand it?

StevenPuttemans gravatar imageStevenPuttemans ( 2016-04-14 07:04:05 -0600 )edit

tmp=response_array.reshape(1,1); //make continuous
this line still wrong( logCat out put : OpenCV Error: Image step is wrong (The matrix is not continuous, thus its number of rows can not be changed) in cv::Mat cv::Mat::reshape(int, int) const, file /home/maksim/workspace/android-pack/opencv/modules/core/src/matrix.cpp, line 984)

jack1 gravatar imagejack1 ( 2016-04-14 07:18:33 -0600 )edit

@StevenPuttemans I don't find a good java tutorial that makes things clear to me .

jack1 gravatar imagejack1 ( 2016-04-14 07:20:34 -0600 )edit

your response Mat should contain a single integer label per image (yours is still plain empty)

berak gravatar imageberak ( 2016-04-14 07:21:53 -0600 )edit

I don't understand .How can i add this in my response mat .I am really sorry for my stupidity.(in my case i should train letters )

jack1 gravatar imagejack1 ( 2016-04-14 07:31:33 -0600 )edit

@berak

Mat trainData = new Mat(); 

 Mat train_labels = new Mat();

Mat img =Imgcodecs.imread( "/storage/emulated/0/DCIM/Camera/n1.PNG");

 img.convertTo(img, CvType.CV_32FC1);

Size dsize = new Size(50, 50); 

Imgproc.resize(img, img, dsize);

img.convertTo(img, CvType.CV_32FC1);

 Mat imgResized = img.reshape(1, 1);

 trainData.push_back(img);

train_labels.push_back(new Mat (1,1,CvType.CV_32FC1,new Scalar(1)));;

 KNearest knn = KNearest.create();

 knn.train(trainData,Ml.ROW_SAMPLE, train_labels);

I wrote this but i got this error :OpenCV Error: Assertion failed (samples.type() == CV_32F || samples.type() == CV_32S)

jack1 gravatar imagejack1 ( 2016-04-14 09:38:38 -0600 )edit