基于OPENCV的图像识别(JAVA版本)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

前几天需要开发一款自动化测试工具,需要用到图像识别
但从未接触过图像算法相关知识,无奈只能找轮子
功夫不负有心人,找到大神分享的一遍文章
现分享给大家

一、使用方法

请先在你的电脑上,安装opencv程序,文章末尾有下载地址
我使用的版本是2.4.13
在创建好项目时,请去opencv的安装目录中,找到opencv-2413.jar,引入到你的工程Lib里
如果你是创建的maven项目,可以将jar文件,安装到你的maven仓库中,然后在pom文件中引入
然后将下面代码复制到你的工程里,找二张图片就可以运行起来了
如果有不懂的,请留言,偶尔上来看一下

代码如下(示例):

public class ImageRecognition {

    private float nndrRatio = 0.7f;//这里设置既定值为0.7,该值可自行调整

    private int matchesPointCount = 0;    
   

    public float getNndrRatio() {
        return nndrRatio;
    }

    public void setNndrRatio(float nndrRatio) {
        this.nndrRatio = nndrRatio;
    }

    public int getMatchesPointCount() {
        return matchesPointCount;
    }

    public void setMatchesPointCount(int matchesPointCount) {
        this.matchesPointCount = matchesPointCount;
    }

    public void matchImage(Mat templateImage, Mat originalImage) {
        MatOfKeyPoint templateKeyPoints = new MatOfKeyPoint();
        //指定特征点算法SURF
        FeatureDetector featureDetector = FeatureDetector.create(FeatureDetector.SURF);
        //获取模板图的特征点
        featureDetector.detect(templateImage, templateKeyPoints);
        //提取模板图的特征点
        MatOfKeyPoint templateDescriptors = new MatOfKeyPoint();
        DescriptorExtractor descriptorExtractor = DescriptorExtractor.create(DescriptorExtractor.SURF);
        //System.out.println("提取模板图的特征点");
        descriptorExtractor.compute(templateImage, templateKeyPoints, templateDescriptors);

        //显示模板图的特征点图片
        Mat outputImage = new Mat(templateImage.rows(), templateImage.cols(), Highgui.CV_LOAD_IMAGE_COLOR);
        //System.out.println("在图片上显示提取的特征点");
        Features2d.drawKeypoints(templateImage, templateKeyPoints, outputImage, new Scalar(255, 0, 0), 0);

        //获取原图的特征点
        MatOfKeyPoint originalKeyPoints = new MatOfKeyPoint();
        MatOfKeyPoint originalDescriptors = new MatOfKeyPoint();
        featureDetector.detect(originalImage, originalKeyPoints);
        //System.out.println("提取原图的特征点");
        descriptorExtractor.compute(originalImage, originalKeyPoints, originalDescriptors);

        List<MatOfDMatch> matches = new LinkedList<MatOfDMatch>();
        DescriptorMatcher descriptorMatcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
        //System.out.println("寻找最佳匹配");
        /**
         * knnMatch方法的作用就是在给定特征描述集合中寻找最佳匹配
         * 使用KNN-matching算法,令K=2,则每个match得到两个最接近的descriptor,然后计算最接近距离和次接近距离之间的比值,当比值大于既定值时,才作为最终match。
         */
        descriptorMatcher.knnMatch(templateDescriptors, originalDescriptors, matches, 2);

        //System.out.println("计算匹配结果");
        LinkedList<DMatch> goodMatchesList = new LinkedList<DMatch>();

        //对匹配结果进行筛选,依据distance进行筛选
        matches.forEach(match -> {
            DMatch[] dmatcharray = match.toArray();
            DMatch m1 = dmatcharray[0];
            DMatch m2 = dmatcharray[1];

            if (m1.distance <= m2.distance * nndrRatio) {
                goodMatchesList.addLast(m1);
            }
        });

        matchesPointCount = goodMatchesList.size();
        //当匹配后的特征点大于等于 4 个,则认为模板图在原图中,该值可以自行调整
        if (matchesPointCount >= 4) {
            System.out.println("模板图在原图匹配成功!");
			//如何考虑到执行的性能,那下面的这些代码可以省掉,直接在此处return结果即可
            List<KeyPoint> templateKeyPointList = templateKeyPoints.toList();
            List<KeyPoint> originalKeyPointList = originalKeyPoints.toList();
            LinkedList<Point> objectPoints = new LinkedList<Point>();
            LinkedList<Point> scenePoints = new LinkedList<Point>();
            goodMatchesList.forEach(goodMatch -> {
                objectPoints.addLast(templateKeyPointList.get(goodMatch.queryIdx).pt);
                scenePoints.addLast(originalKeyPointList.get(goodMatch.trainIdx).pt);
            });
            MatOfPoint2f objMatOfPoint2f = new MatOfPoint2f();
            objMatOfPoint2f.fromList(objectPoints);
            MatOfPoint2f scnMatOfPoint2f = new MatOfPoint2f();
            scnMatOfPoint2f.fromList(scenePoints);
            //使用 findHomography 寻找匹配上的关键点的变换
            Mat homography = Calib3d.findHomography(objMatOfPoint2f, scnMatOfPoint2f, Calib3d.RANSAC, 3);

            /**
             * 透视变换(Perspective Transformation)是将图片投影到一个新的视平面(Viewing Plane),也称作投影映射(Projective Mapping)。
             */
            Mat templateCorners = new Mat(4, 1, CvType.CV_32FC2);
            Mat templateTransformResult = new Mat(4, 1, CvType.CV_32FC2);
            templateCorners.put(0, 0, new double[]{0, 0});
            templateCorners.put(1, 0, new double[]{templateImage.cols(), 0});
            templateCorners.put(2, 0, new double[]{templateImage.cols(), templateImage.rows()});
            templateCorners.put(3, 0, new double[]{0, templateImage.rows()});
            //使用 perspectiveTransform 将模板图进行透视变以矫正图象得到标准图片
            Core.perspectiveTransform(templateCorners, templateTransformResult, homography);

            //矩形四个顶点
            double[] pointA = templateTransformResult.get(0, 0);
            double[] pointB = templateTransformResult.get(1, 0);
            double[] pointC = templateTransformResult.get(2, 0);
            double[] pointD = templateTransformResult.get(3, 0);

            //指定取得数组子集的范围
            int rowStart = (int) pointA[1];
            int rowEnd = (int) pointC[1];
            int colStart = (int) pointD[0];
            int colEnd = (int) pointB[0];
            Mat subMat = originalImage.submat(rowStart, rowEnd, colStart, colEnd);
            Highgui.imwrite("E:/1.jpg", subMat);

            //将匹配的图像用用四条线框出来
            Core.line(originalImage, new Point(pointA), new Point(pointB), new Scalar(0, 255, 0), 4);//上 A->B
            Core.line(originalImage, new Point(pointB), new Point(pointC), new Scalar(0, 255, 0), 4);//右 B->C
            Core.line(originalImage, new Point(pointC), new Point(pointD), new Scalar(0, 255, 0), 4);//下 C->D
            Core.line(originalImage, new Point(pointD), new Point(pointA), new Scalar(0, 255, 0), 4);//左 D->A

            MatOfDMatch goodMatches = new MatOfDMatch();
            goodMatches.fromList(goodMatchesList);
            Mat matchOutput = new Mat(originalImage.rows() * 2, originalImage.cols() * 2, Highgui.CV_LOAD_IMAGE_COLOR);
            Features2d.drawMatches(templateImage, templateKeyPoints, originalImage, originalKeyPoints, goodMatches, matchOutput, new Scalar(0, 255, 0), new Scalar(255, 0, 0), new MatOfByte(), 2);

            Highgui.imwrite("E:/proc1.jpg", matchOutput);
            Highgui.imwrite("E:/proc2.jpg", originalImage);
        } else {
            System.out.println("模板图不在原图中!");
        }

        Highgui.imwrite("E:/mobantezhengdian.jpg", outputImage);
    }  
    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        String templateFilePath = "/Users/niwei/Desktop/opencv/模板.jpeg";
        String originalFilePath = "/Users/niwei/Desktop/opencv/原图.jpeg";
        //读取图片文件
        Mat templateImage = Highgui.imread(templateFilePath, Highgui.CV_LOAD_IMAGE_COLOR);
        Mat originalImage = Highgui.imread(originalFilePath, Highgui.CV_LOAD_IMAGE_COLOR);

        ImageRecognition imageRecognition = new ImageRecognition();
        imageRecognition.matchImage(templateImage, originalImage);

        System.out.println("匹配的像素点总数:" + imageRecognition.getMatchesPointCount());
    } 

提示:
1、OPENCV下载地址:https://opencv.org/releases/,下载完成后,安装到你的电脑本机中
2、安装完成后,根据你的安装路径,依次找到如下目录opencv\build\java\x86,将其中的opencv_java2413.dll文件,配置到环境变量中,或者直接复制到C:\Windows\System32目录下也可以(因为这个目录默认已配置过环境变量)
3、github:https://github.com/justin-zhu/adbAndOpencv/tree/androidTestTools,这是之前自己开发的一个Swing工具
注意:我在该项目中引用了一个opencv提供的jar包,需要将这个Jar包安装到你本地的maven环境中:mvn install:install-file -Dfile=“D:\mydown\adbAndOpencv-androidTestTools\src\main\resources\opencv-2413.jar” -DgroupId=opencv2413 -DartifactId=opencv2413 -Dversion=0.1 -Dpackaging=jar
(这个jar包是安装opencv时提供的,我的项目工程中也有这个jar包,所以你可以直接下载我的代码,找到这个jar包,因为我本机下载的代码放D盘了,所以指定的是D盘的目录,根据实际情况改一下路径,但名称不要改,因为我pom文件中引用的是opencv2413这个名字 )另外不会使用maven的请去搜索一下如何安装maven及如何安装jar到你的本地仓库中。

转载地址

https://www.jianshu.com/p/13d94f2a8f64

  • 1
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值