Path: blob/master/Contour-Detection-using-OpenCV/cpp/contour_extraction/contour_extraction.cpp
3150 views
#include<opencv2/opencv.hpp>1#include <iostream>23using namespace std;4using namespace cv;56int main() {7/*8Contour detection and drawing using different extraction modes to complement9the understanding of hierarchies10*/11Mat image2 = imread("../../input/custom_colors.jpg");12Mat img_gray2;13cvtColor(image2, img_gray2, COLOR_BGR2GRAY);14Mat thresh2;15threshold(img_gray2, thresh2, 150, 255, THRESH_BINARY);1617vector<vector<Point>> contours3;18vector<Vec4i> hierarchy3;19findContours(thresh2, contours3, hierarchy3, RETR_LIST, CHAIN_APPROX_NONE);20Mat image_copy4 = image2.clone();21drawContours(image_copy4, contours3, -1, Scalar(0, 255, 0), 2);22imshow("LIST", image_copy4);23waitKey(0);24imwrite("contours_retr_list.jpg", image_copy4);25destroyAllWindows();2627vector<vector<Point>> contours4;28vector<Vec4i> hierarchy4;29findContours(thresh2, contours4, hierarchy4, RETR_EXTERNAL, CHAIN_APPROX_NONE);30Mat image_copy5 = image2.clone();31drawContours(image_copy5, contours4, -1, Scalar(0, 255, 0), 2);32imshow("EXTERNAL", image_copy5);33waitKey(0);34imwrite("contours_retr_external.jpg", image_copy4);35destroyAllWindows();3637vector<vector<Point>> contours5;38vector<Vec4i> hierarchy5;39findContours(thresh2, contours5, hierarchy5, RETR_CCOMP, CHAIN_APPROX_NONE);40Mat image_copy6 = image2.clone();41drawContours(image_copy6, contours5, -1, Scalar(0, 255, 0), 2);42imshow("EXTERNAL", image_copy6);43waitKey(0);44imwrite("contours_retr_ccomp.jpg", image_copy6);45destroyAllWindows();4647vector<vector<Point>> contours6;48vector<Vec4i> hierarchy6;49findContours(thresh2, contours6, hierarchy6, RETR_TREE, CHAIN_APPROX_NONE);50Mat image_copy7 = image2.clone();51drawContours(image_copy7, contours6, -1, Scalar(0, 255, 0), 2);52imshow("EXTERNAL", image_copy7);53waitKey(0);54imwrite("contours_retr_tree.jpg", image_copy7);55destroyAllWindows();56}575859