Canny边缘检测和基于Canny边缘检测的轮廓发现,轮廓最小最大矩形绘制minAreaRect,boundingRect,轮廓面积计算contourArea,轮廓长度计算arcLength
/**
* Canny边缘检测
* 原理:先经过高斯平滑去噪声,然后寻找图像强度梯度,再经过非极大抑制,即将模糊的边界变得清晰,在经过双阈值处理,最后利用滞后的边界跟踪
* Canny(
* Mat src, --输入图像
* Mat dst, --输出图像
*double threshold1, --第一个阈值
*double threshold2, --第二个阈值
*int aperture_size=3 --表示 Sobel 算子的孔径大小
*bool L2gradient --一个计算图像梯度幅值的标识,有默认值false
* );
*
*/
@Test
public void testCanny() {
Mat src = GeneralUtils.converMat("C:\\图片\\test\\0001.jpg");
//Canny边缘检测
Mat canny = new Mat();
Imgproc.Canny(src, canny, 50, 150, 3, false);
GeneralUtils.saveByteImg(canny, "C:\\图片\\test\\canny.jpg");
//轮廓发现
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
Imgproc.findContours(canny, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
for (int i = 0; i < contours.size(); i++) {
//获取轮廓最大外接矩形
Rect rect = Imgproc.boundingRect(contours.get(i));
//把矩形画出来
Imgproc.rectangle(src, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),
new Scalar(0, 0, 255), 2, 8, 0);
//获取轮廓最小外接矩形
MatOfPoint2f matOfPoint2f = new MatOfPoint2f(contours.get(i).toArray());
RotatedRect rotatedRect = Imgproc.minAreaRect(matOfPoint2f);
//获取矩形四个顶点
Point[] points = new Point[4];
rotatedRect.points(points);
//把矩形画出来
for (int j = 0; j < 4; j++) {
Imgproc.line(src, points[j % 4], points[(j + 1) % 4], new Scalar(0, 255, 0), 2, 8, 0);
}
// 轮廓面积计算
double area = Imgproc.contourArea(contours.get(i));
//轮廓长度计算
double curvelen = Imgproc.arcLength(matOfPoint2f, true);
System.out.println("面积:" + area + ",长度:" + curvelen);
}
GeneralUtils.saveByteImg(src, "C:\\图片\\test\\drawContours.jpg");
}
《中医基础理论》