1.概述
1.1凸包概念
1.2Graham扫描算法
- 首先选择Y方向最低的点作为起始点p0
- 从p0开始极坐标扫描,一次添加p1...pn(扫描顺序是根据极坐标的角度大小,逆时针方向)
- 对每个点pi来说,如果添加pi点到凸包中导致一个左转向(逆时针方法),则添加该点到凸包,反之如果导致一个右转向(顺时针方向)删除该点从凸包中。
1.3API说明CV::convexHull
convexHull(
inputArray points,//输入候选点,来自findContours
outputArray hull,//凸包
bool clockwise,//default true,顺时针
bool returnPoints//true表示返回点个数,如果第二个参数是vector<Point>则自动忽略
)
1.4操作流程
- 首先把图像从RGB转为灰度
- 然后再转为二值图像
- 再通过发现轮廓得到候选点
- 凸包API调用
- 绘制显示
2.程序设计
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, const char* argv[])
{
Mat src = imread("F:/testImage/hand.png");
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
// ��ֵ��
Mat dst, 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 < hull.size(); i++) {
circle(src, hull[i], 4, Scalar(255, 0, 0), 2, 8, 0);
line(src, hull[i % len], hull[(i + 1) % len], Scalar(0, 0, 255), 2, 8, 0);
}
}
imshow("contours", src);
waitKey(0);
return 0;
}