1 | #include <opencv.hpp>
|
2 |
|
3 | using namespace std;
|
4 | using namespace cv;
|
5 |
|
6 | int main(int argc, const char *argv[])
|
7 | {
|
8 | Mat mask = imread("mask.png", -1);
|
9 |
|
10 |
|
11 | vector<Vec4i> hierarchy;
|
12 | vector<vector<Point> > contours;
|
13 | Mat tmp = mask.clone();
|
14 | findContours(tmp, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
|
15 |
|
16 |
|
17 |
|
18 | vector<vector<Point> >::iterator cit;
|
19 | for (cit = contours.begin(); cit < contours.end();)
|
20 | {
|
21 |
|
22 | int contour_area = contourArea(*cit);
|
23 | if (contour_area < 100000)
|
24 | {
|
25 | cit = contours.erase(cit);
|
26 | continue;
|
27 | }
|
28 | cit++;
|
29 | }
|
30 | assert(contours.size() == 1);
|
31 |
|
32 |
|
33 | vector<int> hull;
|
34 | convexHull(contours[0], hull);
|
35 | cout << "Notice that 1010 to 1011 isn't a decrease in indices like the rest\n";
|
36 | for (unsigned int i = 0; i < hull.size(); i++)
|
37 | {
|
38 | cout << hull.at(i) << endl;
|
39 | }
|
40 |
|
41 |
|
42 | {
|
43 | vector<Vec4i> convexity_defects;
|
44 | convexityDefects(contours[0], hull, convexity_defects);
|
45 |
|
46 | int max_depth = 0;
|
47 | int max_index = 0;
|
48 | for (unsigned int i = 0; i < convexity_defects.size(); i++)
|
49 | {
|
50 | int current_depth = convexity_defects[i][3];
|
51 | if (current_depth > max_depth)
|
52 | {
|
53 | max_depth = current_depth;
|
54 | max_index = i;
|
55 | }
|
56 | }
|
57 |
|
58 | Mat color_mask;
|
59 | cvtColor(mask, color_mask, CV_GRAY2BGR);
|
60 | Point start_point = contours[0][convexity_defects[max_index][0]];
|
61 | Point end_point = contours[0][convexity_defects[max_index][1]];
|
62 | Point defect_point = contours[0][convexity_defects[max_index][2]];
|
63 | circle(color_mask, start_point, 26, Scalar(255,255,0), 4);
|
64 | circle(color_mask, end_point, 16, Scalar(0,0,255), 4);
|
65 | circle(color_mask, defect_point, 16, Scalar(0,255,255), 4);
|
66 | namedWindow("defects", CV_WINDOW_NORMAL);
|
67 | imshow("defects", color_mask);
|
68 | waitKey(0);
|
69 | }
|
70 |
|
71 |
|
72 | return 0;
|
73 | }
|