Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Template Matching with Multiple Objects for android and java using opencv

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;

}
}

Template Matching with Multiple Objects for android and java using opencv

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;

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