Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

KNN findNearest() return always 0.0 openCV4Android 3.0.0

I'm writting apk, which recognise hand sign. It's my function to train KNearest model. I'm using 5 images 200x200 px.

   public void train(){
    Mat trainData    = new Mat(0, sizex * sizey, CvType.CV_32FC1); // 0 x 40 000
    Mat trainClasses = new Mat(train_samples, 1, CvType.CV_32FC1); // 5 x 1

    float[] myint = new float[train_samples];
    Mat img = new Mat();

    for (int i = 0; i<train_samples; i++) {

        String photoPath=Environment.getExternalStorageDirectory().toString()+"/frames/frame_"+i+".png";

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
        Utils.bitmapToMat(bitmap, img);

        if (img.channels() == 3) {
            Imgproc.cvtColor(img, img, Imgproc.COLOR_RGB2GRAY);
        } else if (img.channels() == 4) {
            Imgproc.cvtColor(img, img, Imgproc.COLOR_RGBA2GRAY);
        }

        Imgproc.resize(img, img, new Size(sizex, sizey));
        img.convertTo(img, CvType.CV_32FC1);
        img = img.reshape(1, 1); //  1x40 000 ( 200x200 )

        trainData.push_back(img);
        myint[i] = (float) i;
        trainClasses.put(i, 0, myint);
    }

    knn = KNearest.create();
    knn.train(trainData, Ml.ROW_SAMPLE, trainClasses);

    trainClasses.release();
    trainData.release();
}

And my function which test model:

public void test(View view) {
    Mat result = new Mat(1, 1, CvType.CV_8U);

    String photoPath = Environment.getExternalStorageDirectory().toString() + "/frames/frame_3.png";

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
    Utils.bitmapToMat(bitmap, frame_3);

    if (frame_3.channels() == 3) {
        Imgproc.cvtColor(frame_3, frame_3, Imgproc.COLOR_RGB2GRAY);
    } else if (frame_3.channels() == 4) {
        Imgproc.cvtColor(frame_3, frame_3, Imgproc.COLOR_RGBA2GRAY);
    }

    Imgproc.resize(frame_3, frame_3, new Size(sizex, sizey)); // 200x200
    frame_3.convertTo(frame_3, CvType.CV_32FC1);
    frame_3 = frame_3.reshape(1, 1); // 1x40 000  (200x200)
    iv.setImageBitmap(bitmap);

    float f = knn.findNearest(frame_3, 1, result);

    Log.d(TAG, "KNN: " + f);
    result.release();
}

variable f is always 0.0, although I pass the same frame_3 (image in png) in train model and findnearest. I have no idea what I am doing wrong