Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Contour-Detection-using-OpenCV/cpp/contour_extraction/contour_extraction.cpp
3150 views
1
#include<opencv2/opencv.hpp>
2
#include <iostream>
3
4
using namespace std;
5
using namespace cv;
6
7
int main() {
8
/*
9
Contour detection and drawing using different extraction modes to complement
10
the understanding of hierarchies
11
*/
12
Mat image2 = imread("../../input/custom_colors.jpg");
13
Mat img_gray2;
14
cvtColor(image2, img_gray2, COLOR_BGR2GRAY);
15
Mat thresh2;
16
threshold(img_gray2, thresh2, 150, 255, THRESH_BINARY);
17
18
vector<vector<Point>> contours3;
19
vector<Vec4i> hierarchy3;
20
findContours(thresh2, contours3, hierarchy3, RETR_LIST, CHAIN_APPROX_NONE);
21
Mat image_copy4 = image2.clone();
22
drawContours(image_copy4, contours3, -1, Scalar(0, 255, 0), 2);
23
imshow("LIST", image_copy4);
24
waitKey(0);
25
imwrite("contours_retr_list.jpg", image_copy4);
26
destroyAllWindows();
27
28
vector<vector<Point>> contours4;
29
vector<Vec4i> hierarchy4;
30
findContours(thresh2, contours4, hierarchy4, RETR_EXTERNAL, CHAIN_APPROX_NONE);
31
Mat image_copy5 = image2.clone();
32
drawContours(image_copy5, contours4, -1, Scalar(0, 255, 0), 2);
33
imshow("EXTERNAL", image_copy5);
34
waitKey(0);
35
imwrite("contours_retr_external.jpg", image_copy4);
36
destroyAllWindows();
37
38
vector<vector<Point>> contours5;
39
vector<Vec4i> hierarchy5;
40
findContours(thresh2, contours5, hierarchy5, RETR_CCOMP, CHAIN_APPROX_NONE);
41
Mat image_copy6 = image2.clone();
42
drawContours(image_copy6, contours5, -1, Scalar(0, 255, 0), 2);
43
imshow("EXTERNAL", image_copy6);
44
waitKey(0);
45
imwrite("contours_retr_ccomp.jpg", image_copy6);
46
destroyAllWindows();
47
48
vector<vector<Point>> contours6;
49
vector<Vec4i> hierarchy6;
50
findContours(thresh2, contours6, hierarchy6, RETR_TREE, CHAIN_APPROX_NONE);
51
Mat image_copy7 = image2.clone();
52
drawContours(image_copy7, contours6, -1, Scalar(0, 255, 0), 2);
53
imshow("EXTERNAL", image_copy7);
54
waitKey(0);
55
imwrite("contours_retr_tree.jpg", image_copy7);
56
destroyAllWindows();
57
}
58
59