Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/ConvexHull/example.cpp
3118 views
1
#include "opencv2/highgui/highgui.hpp"
2
#include "opencv2/imgproc/imgproc.hpp"
3
#include <iostream>
4
#include <cstdlib>
5
6
using namespace cv;
7
using namespace std;
8
9
int main(int argc, char** argv) {
10
string image_path; // image path for input image
11
12
if(argc < 2)
13
image_path = "sample.jpg";
14
else
15
image_path = argv[1];
16
17
// declare images
18
Mat src, gray, blur_image, threshold_output;
19
20
// take input image
21
src = imread(image_path, 1);
22
23
// convert to grayscale
24
cvtColor(src, gray, COLOR_BGR2GRAY);
25
26
// add blurring to the input image
27
blur(gray, blur_image, Size(3, 3));
28
29
// binary threshold the input image
30
threshold(gray, threshold_output, 200, 255, THRESH_BINARY);
31
32
// show source image
33
namedWindow("Source", WINDOW_AUTOSIZE);
34
imshow("Source", src);
35
36
// Convex Hull implementation
37
Mat src_copy = src.clone();
38
39
// contours vector
40
vector< vector<Point> > contours;
41
vector<Vec4i> hierarchy;
42
43
// find contours for the thresholded image
44
findContours(threshold_output, contours, hierarchy, RETR_TREE,
45
CHAIN_APPROX_SIMPLE, Point(0, 0));
46
47
// create convex hull vector
48
vector< vector<Point> > hull(contours.size());
49
50
// find convex hull for each contour
51
for(int i = 0; i < contours.size(); i++)
52
convexHull(Mat(contours[i]), hull[i], false);
53
54
// create empty black image
55
Mat drawing = Mat::zeros(threshold_output.size(), CV_8UC3);
56
57
// draw contours and convex hull on the empty black image
58
for(int i = 0; i < contours.size(); i++) {
59
Scalar color_contours = Scalar(0, 255, 0); // color for contours : blue
60
Scalar color = Scalar(255, 255, 255); // color for convex hull : white
61
// draw contours
62
drawContours(drawing, contours, i, color_contours, 2, 8, vector<Vec4i>(), 0, Point());
63
// draw convex hull
64
drawContours(drawing, hull, i, color, 2, 8, vector<Vec4i>(), 0, Point());
65
}
66
67
namedWindow("Output", WINDOW_AUTOSIZE);
68
imshow("Output", drawing);
69
70
waitKey(0);
71
return 0;
72
}
73
74