[OpenCV学习日记-java]-14-轮廓分析

轮廓分析

边界框

获取边界框的api如下

public static Rect boundingRect(Mat array){}
  • array:是轮廓所有点的集合对象,通常是MatofPoint对象

该Api会返回一个Rect对象实例,它是Opencv中关于矩形的数据结构,从中可以得到外接矩形(边界框)的宽和高


最小边界框

与上面边界框不同的是,获取到最小边界框有时候不是一个水平或者垂直的矩形,而是一个旋转了一定角度的矩形,但是最小外接矩形(最小边界框)能够更加真实的反应出轮廓的几何大小,而横纵比结果更能反映出轮廓的真实几何特征

他的Api如下

public static RotatedRect minAreaRect(MatOfPoint2f points){}
  • points:是轮廓所有点的集合对象

该api会返回一个RotatedRect对象,他有旋转角度,矩形的宽高还有四个顶点的信息


轮廓的面积和周长

轮廓面积Api

public static double contourArea(Mat contour, boolean oriented)
  • contour:轮廓所有点的集合对象
  • oriented:轮廓的方向,当为true时候,返回的面积是一个有符号的值,默认false返回绝对值

轮廓周长Api

public static double arcLength(MatOfPoint2f curve, boolean closed)
  • curve:轮廓所有点的集合对象
  • closed:表示是否为闭合曲线,一般为true

完整的轮廓分析

获取轮廓、外接轮廓、最小外接轮廓、横纵比、面积和周长的代码如下

Mat m = Imgcodecs.imread("C:\\test\\shape.png");

HighGui.imshow("原始图片",m);

//灰度->二值
Mat m1 = new Mat();
Imgproc.cvtColor(m,m1,Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(m1,m1,0,255,Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);
HighGui.imshow("二值化",m1);

//轮廓发现
List<MatOfPoint> contours = new ArrayList<>();
Mat m2 = new Mat();
Imgproc.findContours(m1,contours,m2,Imgproc.RETR_TREE,Imgproc.CHAIN_APPROX_NONE);

//测量轮廓
Mat m3 = Mat.zeros(m.size(),m.type());
for (int i = 0; i < contours.size(); i++) {

    //外边界
    Rect rect = Imgproc.boundingRect(contours.get(i));
    double w = rect.width;
    double h = rect.height;
    System.out.println("图像"+i+"外边界信息 : 宽"+ w +"高" + h);


    //最小边界框
    RotatedRect minRect = Imgproc.minAreaRect(new MatOfPoint2f(contours.get(i).toArray()));
    w = minRect.size.width;
    h = minRect.size.height;
    double angle = minRect.angle;
    System.out.println("图像"+i+"最小外边界信息 : 宽"+ w +"高" + h+"角度"+angle);


    //周长和面积
    double len = Imgproc.arcLength(new MatOfPoint2f(contours.get(i).toArray()),true);
    double area = Imgproc.contourArea(contours.get(i),false);
	System.out.println("图像"+i+"信息 : 周长"+ len +"面积" + area);

    //绘制边界框
    Imgproc.drawContours(m3,contours,i,new Scalar(0,0,255),1);

}

HighGui.imshow("轮廓",m3);

在这里插入图片描述
输出结果

图像0外边界信息 :108.0111.0
图像0最小外边界信息 :108.18736267089844108.18736267089844角度-45.0
图像0信息 : 周长359.0193328857422面积9238.0
图像1外边界信息 :80.0152.0
图像1最小外边界信息 :151.079.0角度-90.0
图像1信息 : 周长460.0面积11929.0
图像2外边界信息 :124.0104.0
图像2最小外边界信息 :122.99998474121094102.99998474121094角度0.0
图像2信息 : 周长391.66399443149567面积6334.5
图像3外边界信息 :99.0102.0
图像3最小外边界信息 :98.0101.0角度-0.0
图像3信息 : 周长331.22034335136414面积6839.0

上一篇[OpenCV学习日记-java]-13-轮廓发现与绘制

下一篇[OpenCV学习日记-java]-15-图像直方图

发布了45 篇原创文章 · 获赞 42 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_18604209/article/details/104154928
今日推荐