opencv android版模板查找
private void test() {
Mat image = bitmapToMat(BitmapFactory.decodeResource(getResources(), R.mipmap.orgin_img));
Mat template = bitmapToMat(BitmapFactory.decodeResource(getResources(), R.mipmap.target_img));
int resultCols = image.cols() - template.cols() + 1;
int resultRows = image.rows() - template.rows() + 1;
Mat result = new Mat(new Size(resultCols, resultRows), CvType.CV_32FC1);
Imgproc.matchTemplate(image, template, result, Imgproc.TM_CCOEFF_NORMED);
Core.MinMaxLocResult mmr = Core.minMaxLoc(result);
Point matchLoc = mmr.maxLoc;
Rect matchRect = new Rect((int) matchLoc.x, (int) matchLoc.y, template.cols(), template.rows());
Mat markedImage = image.clone();
Imgproc.rectangle(markedImage, matchRect.tl(), matchRect.br(), new Scalar(0, 0, 255), 2);
mImage.setImageBitmap(matToBitmap(markedImage));
}
public static Mat bitmapToMat(Bitmap bitmap) {
Mat mat = new Mat(bitmap.getHeight(), bitmap.getWidth(), CvType.CV_8UC4);
Utils.bitmapToMat(bitmap, mat);
return mat;
}
public static Bitmap matToBitmap(Mat mat) {
// 确保Mat中的数据是8位无符号整数
if (mat.channels() == 1) { // 灰度图像
Mat matRGB = new Mat();
Imgproc.cvtColor(mat, matRGB, Imgproc.COLOR_GRAY2BGR);
mat = matRGB;
} else if (mat.channels() == 3) { // BGR图像
Mat matRGB = new Mat();
Imgproc.cvtColor(mat, matRGB, Imgproc.COLOR_BGR2RGB);
mat = matRGB;
}
Bitmap bitmap = Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mat, bitmap);
return bitmap;
}