OpenCv-C++-凸包操作
阿新 • • 發佈:2018-12-23
什麼是凸包?簡單點就是在一幅影象裡面有很多點,而有一些點連成的形狀能夠把所有點包圍進去。
使用OpenCv怎麼做?
1、先將圖片轉化為灰度影象;
2、轉化為二值影象;
3、找到圖片的全部輪廓點;
4、使用凸包API從全部輪廓點中找到最優輪廓點;
5、連線凸包輪廓點
凸包使用的API是convexHull()
下面看程式碼:
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
Mat src,dst,gray_src;
int threshold_value = 100;
int threshold_max = 255;
void convexHull(int, void*);
int main(int argc, char** argv)
{
src = imread("D:/test/small_hand.png");
if (!src.data)
{
cout << "圖片為空" << endl;
return -1;
}
blur(src, src, Size(3, 3), Point(-1, -1), BORDER_DEFAULT) ;
cvtColor(src, gray_src, CV_BGR2GRAY);
imshow("input img", gray_src);
namedWindow("convexHull title",CV_WINDOW_AUTOSIZE);
createTrackbar("Move", "convexHull title", &threshold_value, threshold_max, convexHull);
convexHull(0,0);
waitKey(0);
return 0;
}
void convexHull(int, void *)
{
RNG rng (12345);
Mat bin_output;
vector<vector<Point>> contours;//輪廓點
vector<Vec4i> hierarcy;
//轉為二值影象
threshold(gray_src, bin_output, threshold_value, threshold_max, THRESH_BINARY);
findContours(bin_output, contours, hierarcy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
vector<vector<Point>> convex(contours.size());//凸包輪廓點
for (size_t i = 0; i < contours.size(); i++)
{
convexHull(contours[i], convex[i], false, true);
}
//繪製輪廓點
dst = Mat::zeros(src.size(), CV_8UC3);//影象必須是3通道
vector<Vec4i> empty(0);
for (size_t k = 0; k < contours.size(); k++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
//繪製整個影象輪廓
drawContours(dst, contours, (int)k, color, 2, LINE_AA, hierarcy, 0, Point(0, 0));
//繪製凸包點
drawContours(dst, convex, (int)k, color, 2, LINE_AA, empty, 0, Point(0, 0));
}
imshow("convexHull title", dst);
}
執行結果