Path: blob/master/Contour-Detection-using-OpenCV/cpp/contour_approximations/contour_approx.cpp
3150 views
#include<opencv2/opencv.hpp>1#include <iostream>23using namespace std;4using namespace cv;56int main() {7// read the image8Mat image = imread("../../input/image_1.jpg");9// convert the image to grayscale format10Mat img_gray;11cvtColor(image, img_gray, COLOR_BGR2GRAY);12// apply binary thresholding13Mat thresh;14threshold(img_gray, thresh, 150, 255, THRESH_BINARY);15imshow("Binary mage", thresh);16waitKey(0);17imwrite("image_thres1.jpg", thresh);18destroyAllWindows();1920// detect the contours on the binary image using cv2.CHAIN_APPROX_NONE21vector<vector<Point>> contours;22vector<Vec4i> hierarchy;23findContours(thresh, contours, hierarchy, RETR_TREE, CHAIN_APPROX_NONE);24// draw contours on the original image25Mat image_copy = image.clone();26drawContours(image_copy, contours, -1, Scalar(0, 255, 0), 2);27imshow("None approximation", image_copy);28waitKey(0);29imwrite("contours_none_image1.jpg", image_copy);30destroyAllWindows();313233// Now let's try with CHAIN_APPROX_SIMPLE`34// detect the contours on the binary image using cv2.CHAIN_APPROX_NONE35vector<vector<Point>> contours1;36vector<Vec4i> hierarchy1;37findContours(thresh, contours1, hierarchy1, RETR_TREE, CHAIN_APPROX_SIMPLE);38// draw contours on the original image39Mat image_copy1 = image.clone();40drawContours(image_copy1, contours1, -1, Scalar(0, 255, 0), 2);41imshow("Simple approximation", image_copy1);42waitKey(0);43imwrite("contours_simple_image1.jpg", image_copy1);44destroyAllWindows();4546// using a proper image for visualizing CHAIN_APPROX_SIMPLE47Mat image1 = imread("../../input/image_2.jpg");48Mat img_gray1;49cvtColor(image1, img_gray1, COLOR_BGR2GRAY);50Mat thresh1;51threshold(img_gray1, thresh1, 150, 255, THRESH_BINARY);52vector<vector<Point>> contours2;53vector<Vec4i> hierarchy2;54findContours(thresh1, contours2, hierarchy2, RETR_TREE, CHAIN_APPROX_NONE);55Mat image_copy2 = image1.clone();56drawContours(image_copy2, contours2, -1, Scalar(0, 255, 0), 2);57imshow("None approximation", image_copy2);58waitKey(0);59imwrite("contours_none_image1.jpg", image_copy2);60destroyAllWindows();61Mat image_copy3 = image1.clone();62for(int i=0; i<contours2.size(); i=i+1){63for (int j=0; j<contours2[i].size(); j=j+1){64circle(image_copy3, (contours2[i][0], contours2[i][1]), 2,65Scalar(0, 255, 0), 2);66}67}68imshow("CHAIN_APPROX_SIMPLE Point only", image_copy3);69waitKey(0);70imwrite("contour_point_simple.jpg", image_copy3);71destroyAllWindows();72}737475