Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Contour-Detection-using-OpenCV/cpp/contour_approximations/contour_approx.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
// read the image
9
Mat image = imread("../../input/image_1.jpg");
10
// convert the image to grayscale format
11
Mat img_gray;
12
cvtColor(image, img_gray, COLOR_BGR2GRAY);
13
// apply binary thresholding
14
Mat thresh;
15
threshold(img_gray, thresh, 150, 255, THRESH_BINARY);
16
imshow("Binary mage", thresh);
17
waitKey(0);
18
imwrite("image_thres1.jpg", thresh);
19
destroyAllWindows();
20
21
// detect the contours on the binary image using cv2.CHAIN_APPROX_NONE
22
vector<vector<Point>> contours;
23
vector<Vec4i> hierarchy;
24
findContours(thresh, contours, hierarchy, RETR_TREE, CHAIN_APPROX_NONE);
25
// draw contours on the original image
26
Mat image_copy = image.clone();
27
drawContours(image_copy, contours, -1, Scalar(0, 255, 0), 2);
28
imshow("None approximation", image_copy);
29
waitKey(0);
30
imwrite("contours_none_image1.jpg", image_copy);
31
destroyAllWindows();
32
33
34
// Now let's try with CHAIN_APPROX_SIMPLE`
35
// detect the contours on the binary image using cv2.CHAIN_APPROX_NONE
36
vector<vector<Point>> contours1;
37
vector<Vec4i> hierarchy1;
38
findContours(thresh, contours1, hierarchy1, RETR_TREE, CHAIN_APPROX_SIMPLE);
39
// draw contours on the original image
40
Mat image_copy1 = image.clone();
41
drawContours(image_copy1, contours1, -1, Scalar(0, 255, 0), 2);
42
imshow("Simple approximation", image_copy1);
43
waitKey(0);
44
imwrite("contours_simple_image1.jpg", image_copy1);
45
destroyAllWindows();
46
47
// using a proper image for visualizing CHAIN_APPROX_SIMPLE
48
Mat image1 = imread("../../input/image_2.jpg");
49
Mat img_gray1;
50
cvtColor(image1, img_gray1, COLOR_BGR2GRAY);
51
Mat thresh1;
52
threshold(img_gray1, thresh1, 150, 255, THRESH_BINARY);
53
vector<vector<Point>> contours2;
54
vector<Vec4i> hierarchy2;
55
findContours(thresh1, contours2, hierarchy2, RETR_TREE, CHAIN_APPROX_NONE);
56
Mat image_copy2 = image1.clone();
57
drawContours(image_copy2, contours2, -1, Scalar(0, 255, 0), 2);
58
imshow("None approximation", image_copy2);
59
waitKey(0);
60
imwrite("contours_none_image1.jpg", image_copy2);
61
destroyAllWindows();
62
Mat image_copy3 = image1.clone();
63
for(int i=0; i<contours2.size(); i=i+1){
64
for (int j=0; j<contours2[i].size(); j=j+1){
65
circle(image_copy3, (contours2[i][0], contours2[i][1]), 2,
66
Scalar(0, 255, 0), 2);
67
}
68
}
69
imshow("CHAIN_APPROX_SIMPLE Point only", image_copy3);
70
waitKey(0);
71
imwrite("contour_point_simple.jpg", image_copy3);
72
destroyAllWindows();
73
}
74
75