Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to match template using openCV ?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.03k
    Comment on it

    Template matching with openCV basically works on matrix reading of searched image.

    following is the example of Template matching using openCV :

    xml file to show resulting image after image search :

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.devjiva.templatematching.MainActivity">
    
        <EditText
            android:layout_width="match_parent"
            android:id="@+id/etFirst"
            android:hint="enter first image name"
            android:layout_centerInParent="true"
            android:layout_height="wrap_content" />
    
        <EditText
            android:layout_width="match_parent"
            android:id="@+id/etSecond"
            android:hint="enter second image name"
            android:layout_centerInParent="true"
            android:layout_height="wrap_content" />
    
        <Button
            android:layout_width="wrap_content"
            android:id="@+id/btnFind"
            android:text="Check Match"
            android:layout_height="wrap_content" />
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:id="@+id/imgResult"
            android:layout_centerInParent="true"
            android:layout_height="wrap_content" />
    
    </LinearLayout>
    
    public class MainActivity extends AppCompatActivity {
    
        private String mainImgPath, templateImgPath, resultImgPath;
        private EditText etFirst,etSecond;
        private static final String TAG = "MainActivity";
        private Button btnFind;
    
    // static initializer to find wheather openCV loaded in your app or not.
        static {
            if(!OpenCVLoader.initDebug()){
                Log.e(TAG, "OpenCV not loaded");
            } else {
                Log.e(TAG, "OpenCV loaded");
            }
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    // Load open cv .so native library using loadLibrary that exist in jniLibs folder
            System.loadLibrary("opencv_java3");
    
            btnFind = (Button)findViewById(R.id.btnFind);
            etFirst = (EditText)findViewById(R.id.etFirst);
            etSecond = (EditText)findViewById(R.id.etSecond);
    
    // get the absolute path of stored image in DCIM folder.
            final String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    
            resultImgPath = baseDir+"/Download/result.png";
    
    // enter the name of main image and search image.
            btnFind.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mainImgPath = baseDir + "/DCIM/Camera/"+etFirst.getText().toString()+".jpg";
                    templateImgPath = baseDir + "/DCIM/Camera/"+etSecond.getText().toString()+".jpg";
                    matchingDemo(mainImgPath, templateImgPath, resultImgPath, Imgproc.TM_SQDIFF);
    
                }
            });
        }
    
    
        public void matchingDemo(String imgPath,String templatePath,String resPath, int matchType){
    
    // to read the entered image from its path and make a mat object 
            Mat img = Imgcodecs.imread(imgPath);
            Mat templ = Imgcodecs.imread(templatePath);
    
            // 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_8UC3);
    
            // performing matching and do normalization
            Imgproc.matchTemplate(img, templ, result, matchType);
            int type = Imgproc.THRESH_TOZERO;
            Imgproc.threshold(result, result, 0.8, 1., type);
            Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
    
            // / finding the best match from minMaxLoc
            Core.MinMaxLocResult mmr = Core.minMaxLoc(result);
    
            Point matchLoc;
            if (matchType == Imgproc.TM_SQDIFF || matchType == Imgproc.TM_SQDIFF_NORMED) {
                matchLoc = mmr.minLoc;
            } else {
                matchLoc = mmr.maxLoc;
            }
    
            // draw a rectangle on searched object
            Imgproc.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
                    matchLoc.y + templ.rows()), new Scalar(0, 255, 0));
    
            // store the result image here
            Imgcodecs.imwrite(resPath, img);
    
            Mat image = Imgcodecs.imread(resPath);
            Bitmap bm = Bitmap.createBitmap(image.cols(),image.rows(), null);
            Utils.matToBitmap(image, bm);
    
            ImageView iv = (ImageView) findViewById(R.id.imgResult);
            iv.setImageBitmap(bm);
    
        }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: