opencv-054-二值图像分析(对轮廓圆与椭圆拟合)

知识点

有时候我们需要对找到的轮廓点进行拟合,生成一个拟合的圆形或者椭圆,以便我们对轮廓进行更进一步的处理,满足我们对最终轮廓形状的判断,OpenCV对轮廓进行圆形或者椭圆拟合的API函数如下:

1
2
3
4
5
6
7
8
9
RotatedRect cv::fitEllipse(
InputArray points
)
参数points是轮廓点,
输出RotatedRect包含下面三个信息
- 拟合之后圆或者椭圆的中心位置、
- 长轴与短轴的直径
- 角度
然后我们就可以根据得到拟合信息绘制椭圆、当长轴与短轴相等的时候就是圆。

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 二值图像分析(对轮廓圆与椭圆拟合)
*/
int main() {
Mat src = imread("../images/stuff.jpg");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

// 去噪声与二值化
Mat dst, gray, binary;
Canny(src, binary, 80, 160);

Mat k = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
dilate(binary, binary, k);

// 轮廓发现与绘制
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
for (size_t t = 0; t < contours.size(); t++) {
// 寻找适配圆
RotatedRect rrt = fitEllipse(contours[t]);
ellipse(src, rrt, Scalar(0,0,255), 2);
}

imshow("contours", src);

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import cv2 as cv
import numpy as np


def canny_demo(image):
t = 80
canny_output = cv.Canny(image, t, t * 2)
cv.imshow("canny_output", canny_output)
cv.imwrite("D:/canny_output.png", canny_output)
return canny_output


src = cv.imread("D:/images/stuff.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
binary = canny_demo(src)
k = np.ones((3, 3), dtype=np.uint8)
binary = cv.morphologyEx(binary, cv.MORPH_DILATE, k)

# 轮廓发现
out, contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for c in range(len(contours)):
# 椭圆拟合
(cx, cy), (a, b), angle = cv.fitEllipse(contours[c])
# 绘制椭圆
cv.ellipse(src, (np.int32(cx), np.int32(cy)),
(np.int32(a/2), np.int32(b/2)), angle, 0, 360, (0, 0, 255), 2, 8, 0)


# 显示
cv.imshow("contours_analysis", src)
cv.imwrite("D:/contours_analysis.png", src)
cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github