opencv-055-二值图像分析(凸包检测)

知识点

对二值图像进行轮廓分析之后,对获取到的每个轮廓数据,可以构建每个轮廓的凸包,构建完成之后会返回该凸包包含的点集。根据返回的凸包点集可以绘制该轮廓对应的凸包。OpenCV对轮廓提取凸包的API函数如下:

1
2
3
4
5
6
7
8
9
10
void cv::convexHull(
InputArray points,
OutputArray hull,
bool clockwise = false,
bool returnPoints = true
)
points参数是输入的轮廓点集
hull凸包检测的输出结果,当参数returnPoints为ture的时候返回凸包的顶点坐标是个点集、returnPoints为false的是返回的是一个integer的vector里面是凸包各个顶点在轮廓点集对应的index
clockwise 表示顺时针方向或者逆时针方向
returnPoints表示是否返回点集

OpenCV中的凸包寻找算法是基于Graham’s扫描法。
OpenCV中还提供了另外一个API函数用来判断一个轮廓是否为凸包,该方法如下:

1
2
3
4
bool cv::isContourConvex(
InputArray contour
)
该方法只有一个输入参数就是轮廓点集。

代码(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
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 二值图像分析(凸包检测)
*/
int main() {
Mat src = imread("../images/hand.jpg");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

// 二值化
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);

// 删除干扰块
Mat k = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
morphologyEx(binary, binary, MORPH_OPEN, k);
imshow("binary", binary);

// 轮廓发现与绘制
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++) {
vector<Point> hull;
convexHull(contours[t], hull);
bool isHull = isContourConvex(contours[t]);
printf("test convex of the contours %s", isHull?"y":"n");
int len = hull.size();
for (int i = 0; i < len; ++i) {
circle(src, hull[i], 4, Scalar(255,0,0), 2);
line(src, hull[i%len], hull[(i+1)%len], 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
import cv2 as cv
import numpy as np

src = cv.imread("D:/images/hand.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
k = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
binary = cv.morphologyEx(binary, cv.MORPH_OPEN, k)
cv.imshow("binary", binary)

# 轮廓发现
out, contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for c in range(len(contours)):
ret = cv.isContourConvex(contours[c])
points = cv.convexHull(contours[c])
total = len(points)
for i in range(len(points)):
x1, y1 = points[i%total][0]
x2, y2 = points[(i+1)%total][0]
cv.circle(src, (x1, y1), 4, (255, 0, 0), 2, 8, 0)
cv.line(src, (x1, y1), (x2, y2), (0, 0, 255), 2, 8, 0)
print(points)
print("convex : ", ret)


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

结果

代码地址

github