Java Code Examples for org.opencv.imgproc.Imgproc#matchTemplate()

The following examples show how to use org.opencv.imgproc.Imgproc#matchTemplate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TemplateMatching.java    From opencv-object-detection with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	
	System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
	Mat source=null;
	Mat template=null;
	String filePath="Sample Image\\";
	source=Imgcodecs.imread(filePath+"kapadokya.jpg");
	template=Imgcodecs.imread(filePath+"balon.jpg");

	Mat outputImage=new Mat();	
	int machMethod=Imgproc.TM_CCOEFF;
  
       Imgproc.matchTemplate(source, template, outputImage, machMethod);

   
       MinMaxLocResult mmr = Core.minMaxLoc(outputImage);
       Point matchLoc=mmr.maxLoc;

       Imgproc.rectangle(source, matchLoc, new Point(matchLoc.x + template.cols(),
               matchLoc.y + template.rows()), new Scalar(255, 255, 255));

       Imgcodecs.imwrite(filePath+"sonuc.jpg", source);
       System.out.println("��lem tamamland�.");
}
 
Example 2
Source File: LKTracker.java    From OpenTLDAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * @return real similarities errors
 */
private float[] normCrossCorrelation(final Mat lastImg, final Mat currentImg, final Point[] lastPoints, final Point[] currentPoints, final byte[] status){
	final float[] similarity = new float[lastPoints.length];
	
	final Mat lastPatch = new Mat(CROSS_CORR_PATCH_SIZE, CvType.CV_8U);
	final Mat currentPatch = new Mat(CROSS_CORR_PATCH_SIZE, CvType.CV_8U);
	final Mat res = new Mat(new Size(1, 1), CvType.CV_32F);
	
	for(int i = 0; i < lastPoints.length; i++){
		if(status[i] == 1){
			Imgproc.getRectSubPix(lastImg, CROSS_CORR_PATCH_SIZE, lastPoints[i], lastPatch);
			Imgproc.getRectSubPix(currentImg, CROSS_CORR_PATCH_SIZE, currentPoints[i], currentPatch);
			Imgproc.matchTemplate(lastPatch, currentPatch, res, Imgproc.TM_CCOEFF_NORMED);
			
			similarity[i] = Util.getFloat(0, 0, res);
		}else{
			similarity[i] = 0f;
		}
	}
	
	return similarity;
}
 
Example 3
Source File: Image.java    From RobotHelper with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 模板匹配
 *
 * @param srcImg      //源图像
 * @param templateImg //模板图像
 * @param threshold   //相识度阈值,阈值调小可以一定程度解决不同手机分辨率的问题
 * @return //如果没有找到则返回(-1,-1)点
 */
public static Point matchTemplate(Bitmap srcImg, Bitmap templateImg, double threshold) {

    if (threshold <= 0) {
        threshold = 0.5;
    }


    Mat tpl = new Mat();
    Mat src = new Mat();
    Utils.bitmapToMat(srcImg, src);
    Utils.bitmapToMat(templateImg, tpl);


    int height = src.rows() - tpl.rows() + 1;
    int width = src.cols() - tpl.cols() + 1;
    Mat result = new Mat(height, width, CvType.CV_32FC1);
    int method = Imgproc.TM_CCOEFF_NORMED;
    Imgproc.matchTemplate(src, tpl, result, method);
    Core.MinMaxLocResult minMaxResult = Core.minMaxLoc(result);
    org.opencv.core.Point maxloc = minMaxResult.maxLoc;
    if (minMaxResult.maxVal < threshold) {
        return new Point(-1, -1);
    }
    org.opencv.core.Point minloc = minMaxResult.minLoc;
    org.opencv.core.Point matchloc = null;
    matchloc = maxloc;
    return new Point((int) matchloc.x, (int) matchloc.y);

}
 
Example 4
Source File: Finder.java    From SikuliX1 with MIT License 5 votes vote down vote up
private Mat doFindMatch(Mat what, Mat where, FindInput2 findInput) {
  Mat mResult = SXOpenCV.newMat();
  if (what.empty()) {
    log.error("doFindMatch: image conversion to cvMat did not work");
  } else {
    Mat mWhere = where;
    if (findInput.isGray()) {
      Imgproc.cvtColor(where, mWhere, Imgproc.COLOR_BGR2GRAY);
    }
    if (!findInput.isPlainColor()) {
      if (findInput.hasMask()) {
        Mat mask = findInput.getMask();
        Imgproc.matchTemplate(mWhere, what, mResult, Imgproc.TM_CCORR_NORMED, mask);
      } else {
        Imgproc.matchTemplate(mWhere, what, mResult, Imgproc.TM_CCOEFF_NORMED);
      }
    } else {
      Mat wherePlain = mWhere;
      Mat whatPlain = what;
      if (findInput.isBlack()) {
        Core.bitwise_not(mWhere, wherePlain);
        Core.bitwise_not(what, whatPlain);
      }
      if (findInput.hasMask()) {
        Imgproc.matchTemplate(wherePlain, what, mResult, Imgproc.TM_SQDIFF_NORMED, findInput.getMask());
      } else {
        Imgproc.matchTemplate(wherePlain, whatPlain, mResult, Imgproc.TM_SQDIFF_NORMED);
      }
      Core.subtract(Mat.ones(mResult.size(), CvType.CV_32F), mResult, mResult);
    }
  }
  return mResult;
}
 
Example 5
Source File: SXOpenCV.java    From SikuliX1 with MIT License 5 votes vote down vote up
private static Match doFindMatch(Mat where, FindAttributes findAttributes, boolean findAll) {
  Mat result = new Mat();
  Mat finalWhere = where;
  if (findAttributes.gray()) {
    Imgproc.cvtColor(where, finalWhere, Imgproc.COLOR_BGR2GRAY);
  }
  Mat what = findAttributes.what();
  Mat mask = findAttributes.mask();
  if (findAttributes.target().plain()) {
    Mat finalWherePlain = finalWhere;
    Mat finalWhatPlain = what;
    if (findAttributes.target().black()) {
      Core.bitwise_not(finalWhere, finalWherePlain);
      Core.bitwise_not(what, finalWhatPlain);
    }
    if (mask.empty()) {
      Imgproc.matchTemplate(finalWherePlain, finalWhatPlain, result, Imgproc.TM_SQDIFF_NORMED);
    } else {
      Imgproc.matchTemplate(finalWherePlain, what, result, Imgproc.TM_SQDIFF_NORMED, mask);
    }
    Core.subtract(Mat.ones(result.size(), CvType.CV_32F), result, result);
  } else if (mask.empty()) {
    Imgproc.matchTemplate(where, what, result, Imgproc.TM_CCOEFF_NORMED);
  } else {
    Imgproc.matchTemplate(where, what, result, Imgproc.TM_CCORR_NORMED, mask);
  }
  Core.MinMaxLocResult minMax = Core.minMaxLoc(result);
  double maxVal = minMax.maxVal;
  if (maxVal > findAttributes.target().similarity()) {
    Point point = new Point((int) minMax.maxLoc.x, (int) minMax.maxLoc.y);
    if (!findAll) {
      result = null;
    }
    return new Match(point, maxVal, result);
  }
  return null;
}
 
Example 6
Source File: ImageMatchers.java    From onetwo with Apache License 2.0 5 votes vote down vote up
static public Core.MinMaxLocResult matchResult(Mat source, Mat destImage) {
       //创建于原图相同的大小,储存匹配度
       Mat result = Mat.zeros(source.rows() - destImage.rows() + 1, source.cols() - destImage.cols() + 1, CvType.CV_32FC1);
       //调用模板匹配方法
       Imgproc.matchTemplate(source, destImage, result, Imgproc.TM_SQDIFF_NORMED);
       //规格化
       Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1);
       //获得最可能点,MinMaxLocResult是其数据格式,包括了最大、最小点的位置x、y
       Core.MinMaxLocResult mlr = Core.minMaxLoc(result);
       return mlr;
}
 
Example 7
Source File: ImageFinder.java    From opentest with MIT License 4 votes vote down vote up
/**
 * Finds a template image in a source image. Throws an exception when the
 * image wasn't found or the desired accuracy couldn't be met.
 *
 * @param sourceMat The source image.
 * @param templateMat The template image to find in the source image.
 * @param desiredAccuracy The desired accuracy of the find operation as a
 * number between 0 and 1.
 * @return An ImageFinderResult object that stores the rectangle of the
 * found image and desired accuracy.
 */
private ImageFinderResult findImage(Mat sourceMat, Mat templateMat, double desiredAccuracy) {
    if (sourceMat.width() < templateMat.width() || sourceMat.height() < templateMat.height()) {
        throw new UnsupportedOperationException("The template image is larger than the source image. Ensure that the width and/or height of the image you are trying to find do not exceed the dimensions of the source image.");
    }

    Mat result = new Mat(sourceMat.rows() - templateMat.rows() + 1, sourceMat.rows() - templateMat.rows() + 1, CvType.CV_32FC1);
    int intMatchingMethod;

    switch (this.matchingMethod) {
        case MM_CORELLATION_COEFF:
            intMatchingMethod = Imgproc.TM_CCOEFF_NORMED;
            break;
        case MM_CROSS_CORELLATION:
            intMatchingMethod = Imgproc.TM_CCORR_NORMED;
            break;
        default:
            intMatchingMethod = Imgproc.TM_SQDIFF_NORMED;
    }

    Imgproc.matchTemplate(sourceMat, templateMat, result, intMatchingMethod);
    MinMaxLocResult minMaxLocRes = Core.minMaxLoc(result);

    double accuracy = 0;
    Point location = null;

    if (this.matchingMethod == MatchingMethod.MM_SQUARE_DIFFERENCE) {
        accuracy = 1 - minMaxLocRes.minVal;
        location = minMaxLocRes.minLoc;
    } else {
        accuracy = minMaxLocRes.maxVal;
        location = minMaxLocRes.maxLoc;
    }

    if (accuracy < desiredAccuracy) {
        throw new ImageNotFoundException(
                String.format(
                        "Failed to find template image in the source image. The accuracy was %.2f and the desired accuracy was %.2f",
                        accuracy,
                        desiredAccuracy),
                new Rectangle((int) location.x, (int) location.y, templateMat.width(), templateMat.height()),
                accuracy);
    }

    if (!minMaxLocResultIsValid(minMaxLocRes)) {
        throw new ImageNotFoundException(
                "Image find result (MinMaxLocResult) was invalid. This usually happens when the source image is covered in one solid color.",
                null,
                null);
    }

    Rectangle foundRect = new Rectangle(
            (int) location.x,
            (int) location.y,
            templateMat.width(),
            templateMat.height());

    return new ImageFinderResult(foundRect, accuracy);
}
 
Example 8
Source File: NNClassifier.java    From OpenTLDAndroid with Apache License 2.0 4 votes vote down vote up
/**
 * INPUTs : pExamples, nExamples
 * @param example NN patch
 * @return Relative Similarity (rsconf), Conservative Similarity (csconf), In pos. set|Id pos set|In neg. set (isin)
 */
NNConfStruct nnConf(final Mat example) {
	if(example == null){
		Log.e(Util.TAG, "NNClass.nnConf() - Null example received, stop here");
		return new NNConfStruct(null, 0, 0);
	}
	if(pExamples.isEmpty()){
		// IF positive examples in the model are not defined THEN everything is negative
		return new NNConfStruct(null, 0, 0);
	}
	
	if(nExamples.isEmpty()){
		// IF negative examples in the model are not defined THEN everything is positive
		return new NNConfStruct(null, 1, 1);
	}
	
	final Mat ncc = new Mat(1, 1, CvType.CV_32F);
	float nccP=0, csmaxP=0, maxP=0;
	boolean anyP = false;
	int maxPidx = 0;
	final int validatedPart = (int) Math.ceil(pExamples.size() * params.valid);
	for(int i = 0; i < pExamples.size(); i++){
		Imgproc.matchTemplate(pExamples.get(i), example, ncc, Imgproc.TM_CCORR_NORMED);  // measure NCC to positive examples
		nccP = (Util.getFloat(0, 0, ncc) + 1) * 0.5f;
		if(nccP > params.ncc_thesame){
			anyP = true;
		}
		if(nccP > maxP){
			maxP = nccP;
			maxPidx = i;
			if(i < validatedPart){
				csmaxP = maxP;
			}
		}
	}
	
	float nccN=0, maxN = 0;
	boolean anyN = false;
	for(int i = 0; i < nExamples.size(); i++){
		Imgproc.matchTemplate(nExamples.get(i), example, ncc, Imgproc.TM_CCORR_NORMED);  //measure NCC to negative examples
		nccN = (Util.getFloat(0, 0, ncc) + 1) * 0.5f;
		if(nccN > params.ncc_thesame){
			anyN = true;
		}
		if(nccN > maxN){
			maxN = nccN;
		}
	}
	
	
	//Log.i(Util.TAG, "nccP=" + nccP + ", nccN=" + nccN + ", csmaxP=" + csmaxP + ", maxP="+ maxP + ", maxN=" + maxN);
	
	// put together the result
	final float dN = 1 - maxN;
	final float dPrelative = 1 - maxP;
	final float dPconservative = 1 - csmaxP;
	return new NNConfStruct(new IsinStruct(anyP, maxPidx, anyN), dN / (dN + dPrelative), dN / (dN + dPconservative));
}