美文网首页Android收藏集
OpenCV使用(二):模板匹配实现人脸识别

OpenCV使用(二):模板匹配实现人脸识别

作者: itfitness | 来源:发表于2019-05-31 16:15 被阅读40次

    目录

    目录

    效果展示


    模板图片

    什么是模板匹配

    模板匹配是最简单的模式识别算法之一,其在图像处理中经常用于从一副未知图像中根据预先定义好的模板图像来寻找与模板图像相同或者高度相似的子图像区域。

    OpenCv的模板匹配函数

    matchTemplate(Mat image, Mat templ, Mat result, int method)

    • image:表示输入图像,大小为 W × H
    • templ :表示模板图像,大小为 w × h
    • result :表示计算输出的结果大小必须为(W - w + 1) × (H - h +1),单通道浮点数(即:CvType.CV_32FC1)
    • method:表示计算方法

    代码实现

    //核心代码
    /**
         * 模板匹配图像
         */
        private void templateImage(Bitmap bitmapSrc) {
            Bitmap bitmapTemplate = BitmapFactory.decodeResource(getResources(), R.drawable.temple3);
    //        获取Bitmap对应的Mat
            Mat img = new Mat();//创建Mat对象用于存放转换后的Bitmap对象
            Mat templ = new Mat();
            Utils.bitmapToMat(bitmapSrc,img);//将Bitmap转化为Mat
            Utils.bitmapToMat(bitmapTemplate,templ);
            int match_method = Imgproc.TM_CCOEFF;//模板匹配的计算方法
            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);//创建模板匹配结果的Mat
            Imgproc.matchTemplate(img, templ, result, match_method);//进行模板匹配
    
            Core.MinMaxLocResult mmr = Core.minMaxLoc(result);//获取匹配结果的区域
            Point matchLoc;
            if (match_method == Imgproc.TM_SQDIFF || match_method == Imgproc.TM_SQDIFF_NORMED) {
                matchLoc = mmr.minLoc;
            } else {
                matchLoc = mmr.maxLoc;
            }
    //        绘制匹配结果区域
            Imgproc.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
                    matchLoc.y + templ.rows()), new Scalar(255, 0, 0),4,8,0);
            Utils.matToBitmap(img,bitmapSrc);//将绘制结果Mat转化为Bitmap
    //        释放资源
            img.release();
            templ.release();
            result.release();
            bitmapTemplate.recycle();
        }
    

    项目源码

    更多具体的细节请看项目源码:https://github.com/myml666/OpenCvTemplate

    相关文章

      网友评论

        本文标题:OpenCV使用(二):模板匹配实现人脸识别

        本文链接:https://www.haomeiwen.com/subject/xxrgtctx.html