opencv android版模板查找

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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值