Ask Your Question
1

Template Matching with Multiple Objects for android and java using opencv

asked 2016-04-04 10:47:41 -0600

siline gravatar image

updated 2016-04-04 10:49:06 -0600

I am tring to match multiple object using a single template .I succed to match only one object and this is the code but i don't know how to match multiple objects .I find a lot of resources but they are in c++ language and i need java code

   public class MainActivity extends Activity {

  Button button;
  ImageView imageView;
  ImageView n3;

File cacheDir;

protected static final String TAG = "OpenCV";

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();
    initDir();
}

@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);

}

// ADDED THIS: to create/initialize external file
// Be sure write permissions is enabled in the manifest file
// ie add: <uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE"/>
public void initDir() {
    if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED)) {
        cacheDir = new File(
                android.os.Environment.getExternalStorageDirectory(),"LazyList");

        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
    }
}

// added this to simplify creating full file path
public String getFileAbsPath(String fileName) {
    File f = new File(cacheDir, fileName);
    return f.getAbsolutePath();
}

public void addListenerOnButton() {

    imageView = (ImageView) findViewById(R.id.imageView1);
    n3 = (ImageView) findViewById(R.id.imageView2);

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

        @Override
        public void onClick(View arg0) {
            String infile = "/storage/emulated/0/DCIM/Camera/n2.png";
            String tp = "/storage/emulated/0/DCIM/Camera/n1.png";
            String outFile = "/storage/emulated/0/DCIM/Camera/n3.png";

            try {
                matchTemplate(infile, tp, outFile, Imgproc.TM_CCOEFF);
                Bitmap bm = BitmapFactory.decodeFile(outFile);
                n3.setImageBitmap(bm);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

    });

}

public Mat matchTemplate(String inFile, String templateFile,String outFile, int match_method) {
    Log.i(TAG, "Running Template Matching");

    Mat img = Imgcodecs.imread(inFile);
    Mat templ = Imgcodecs.imread(templateFile);

    // / Create the result matrix
    int result_cols = img.cols() - templ.cols() + 1;
    int result_rows = img.rows() - templ.rows() + 1;
    Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

//  Bitmap inFileBitmap = BitmapFactory.decodeFile(inFile);
//  Bitmap templBitmap = BitmapFactory.decodeFile(templateFile);
    // / Do the Matching and Normalize
    //Utils.bitmapToMat(inFileBitmap, img);
    //Utils.bitmapToMat(templBitmap, templ);
    Imgproc.matchTemplate(img, templ, result, match_method);
    Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());

    // / Localizing the best match with minMaxLoc

    MinMaxLocResult mmr = Core.minMaxLoc(result);

    Point matchLoc;
    double minVal; double maxVal;
    if (match_method == Imgproc.TM_SQDIFF
            || match_method == Imgproc.TM_SQDIFF_NORMED) {
        matchLoc = mmr.minLoc;
    } else {
        matchLoc = mmr.maxLoc;
    }



    // / Show me what you got
    Imgproc.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),matchLoc.y + templ.rows()), new Scalar(0, 0,0));

    // Save the visualized detection.
    Log.i(TAG, "Writing: " + outFile);

    Imgcodecs.imwrite(outFile, img);
    return img;

}
}
edit retag flag offensive close merge delete

Comments

1

Hi Siline, were you able to find the logic for matching a template to multiple objects? I am also struggling with the same thing. Will really appreciate if you post the code.

ankur gravatar imageankur ( 2017-04-13 10:42:28 -0600 )edit

@siline, why is the result matrix the difference between the sizes of the two input images?

sengsational gravatar imagesengsational ( 2017-05-17 11:02:19 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
0

answered 2017-01-12 17:02:45 -0600

can you upload the source project? i have serious problems to get in the correct way in an application like that it could be very helpful :D

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2016-04-04 10:47:41 -0600

Seen: 3,183 times

Last updated: Apr 04 '16