OpenCV using convexitydefects to calculate contour convex defects

Source: Internet
Author: User

Citation: http://www.xuebuyuan.com/1684976.html

http://blog.csdn.net/lichengyu/article/details/38392473

Http://www.cnblogs.com/yemeishu/archive/2013/01/19/2867286.html Talk about Nite 2 and OpenCV to extract fingertip coordinates

A concept:

Convexity Hull, convexity defects

As shown, the black contour line is convexity hull, while the portion between the convexity hull and the palm is convexity defects. Each convexity defect area has four signatures: the starting point (StartPoint), the end point (EndPoint), the distance from the convexity Hull (FarPoint), and the furthest point to the convexity Hull ( Depth).

Two Correlation functions in the OPENCV

void Convexitydefects (Inputarray contour, Inputarray convexhull, outputarrayconvexitydefects)

Parameters:

Coutour: input parameter, detected contour, can call findcontours function to get;

Convexhull: Input parameters, detected convex hull, can be called convexhull function to get. Note that the Convexhull function can get the results of two types of vector<vector<point>> and vector<vector<int>>, The convexhull here should be the vector<vector<int>> type, otherwise it will not pass the Assert check;

Convexitydefects: The output parameter, the final result detected, should be the vector<vector<vec4i>> type, vec4i stores the starting point (StartPoint), the end point (EndPoint), Distance from convexity hull farthest point (farPoint) and farthest point to convexity hull (depth)

Three Code

http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/hull/hull.html//http://www.codeproject.com/ Articles/782602/beginners-guide-to-understand-fingertips-counting#include "OPENCV2/HIGHGUI/HIGHGUI.HPP" #include "Opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace CV; using namespace Std; Mat src; Mat Src_gray; int thresh = 100; int max_thresh = 255; RNG rng (12345); Function header void Thresh_callback (int, void*);/** @function main */int main (int argc, char** argv) {//Load   Source image and convert it to gray src = imread (argv[1], 1);   Convert image to Gray and blur it Cvtcolor (SRC, Src_gray, cv_bgr2gray);   Blur (Src_gray, Src_gray, Size (3,3));   Create Window char* Source_window = "source";   Namedwindow (Source_window, cv_window_autosize);   Imshow (Source_window, SRC);   Createtrackbar ("Threshold:", "Source", &thresh, Max_thresh, Thresh_callback); Thresh_callback(0, 0);   Waitkey (0); return (0);   }/** @function Thresh_callback */void Thresh_callback (int, void*) {Mat src_copy = Src.clone ();   Mat Threshold_output;   vector<vector<point> > contours;   Vector<vec4i> hierarchy;   Detect edges using Threshold Threshold (Src_gray, Threshold_output, Thresh, 255, thresh_binary);  Find contours findcontours (threshold_output, contours, hierarchy, Cv_retr_tree, Cv_chain_approx_simple, point (0, 0)   );   Find the convex hull object for each contour vector<vector<point> >hull (contours.size ());   Int type Hull vector<vector<int>> Hullsi (Contours.size ());   Convexity defects vector<vector<vec4i>> Defects (contours.size ());    for (size_t i = 0; i < contours.size (); i++) {Convexhull (Mat (Contours[i]), Hull[i], false);    Find int type Hull convexhull (Mat (Contours[i]), Hullsi[i], false); Get convexity defects convexitydefects (Mat (contours[i]), Hullsi[i], defects[i]);   }//Draw contours + hull results Mat drawing = Mat::zeros (Threshold_output.size (), CV_8UC3); for (size_t i = 0; i< contours.size (); i++) {Scalar color = scalar (rng.uniform (0, 255), Rng.uniform (0,25        5), Rng.uniform (0,255));        Drawcontours (drawing, contours, I, color, 1, 8, vector<vec4i> (), 0, point ()); Drawcontours (drawing, Hull, I, color, 1, 8, vector<vec4i> (), 0, point ());//Draw defectssize_t count = Contours[i]        . Size ();        std::cout<< "Count:" <<count<<std::endl;        if (count < continue);        Vector<vec4i>::iterator d =defects[i].begin ();            while (D!=defects[i].end ()) {vec4i& v= (*d);                 if (Indexofbiggestcontour = = i) {int startidx=v[0]; Point Ptstart (Contours[i][startidx]);                 Point of the contour where the defect begins int endidx=v[1]; Point Ptend ( CONTOURS[I][ENDIDX]);                 Point of the contour where the defect ends int faridx=v[2];  Point Ptfar (Contours[i][faridx]);//The farthest from the convex hull point within the defect int depth = V[3]/256;                Distance between the farthest point and the convex hull if (depth > && depth < 80)                {Line (drawing, Ptstart, Ptfar, Cv_rgb (0,255,0), 2); Line (drawing, Ptend, Ptfar, Cv_rgb (0,255,0), 2); Circle (Drawing, Ptstart, 4, Scalar (255,0,100), 2); Circle (drawing, p                TEnd, 4, Scalar (255,0,100), 2);                Circle (Drawing, Ptfar, 4, Scalar (100,0,255), 2);            }/*printf ("Start (%d,%d) End (%d,%d), far (%d,%d) \ n", Ptstart.x, Ptstart.y, Ptend.x, Ptend.y, ptfar.x, PTFAR.Y); */        } d++;   }}///Show in a window Namedwindow ("Hull demo", Cv_window_autosize);   Imshow ("Hull demo", drawing); Imwrite ("Convexity_defeCts.jpg ", drawing); }

Another version of the argument

First introduction of today's protagonist: void convexitydefects(inputarray contour, Inputarray,convexhull, Outputarray convexitydefects)

Note that the last parameter convexitydefects is the vector that stores vec4i (vector<varname>), the size of the vector is the number of contour convex defects after the function is calculated successfully. Each element of the vector vec4i stores 4 integer data, because VEC4I implements overloads for [], so you can use _vectername[i][0] to access the first component of the element I elements of a vector _vactername. And the four shaping data stored in the VEC4I,

OPENCV uses these four elements to represent convex defects,

The first name is called a
start_index, which indicates that the defect is at the beginning of the contour, his value is the index of the starting point in the first parameter of the function contour;

VEC4I the name of the second element is called
End_index, as the name implies, its corresponding value is the end of the defect in the contour index;

The third element of VEC4I
Farthest_pt_index Is the furthest point of the defect on the distance contour convex hull (convexhull);

The last element of VEC4I is called
fixpt_depth,fixpt_depth/256 indicates the
The distance, in pixels, of the farthest_pt_index-to-contour convex hull (convexhull) on the contour .

All are so easy! below is a simple code example (first calculating a convex hull of two outlines and then calculating the convex defects of two outlines):

Calculation of convex defect convexitydefect//#include "stdafx.h" #include <opencv.hpp> #include <iostream>using namespace std; Using namespace Cv;int _tmain (int argc, _tchar* argv[]) {Mat *img_01 = new Mat (+, +, CV_8UC3);  Mat *img_02 = new Mat (CV_8UC3), *img_01 = Scalar::all (0), *img_02 = Scalar::all (0);//array of contour points vector<point> points_01,points_02;//assigns the Contour group Points_01.push_back (Point (Ten));p Oints_01.push_back (Point (10,390));p oints_01. Push_back (Point (390, 390));p Oints_01.push_back (at point);p oints_02.push_back (point);p Oints_02.push _back (Point (10,390));p Oints_02.push_back (Point (390, 390));p Oints_02.push_back (at point);vector<int> hull_01,hull_02;//Compute convex hull convexhull (points_01, hull_01, True), Convexhull (points_02, hull_02, true);//Draw outline for (int i=0;i < 4;++i) {circle (*img_01, Points_01[i], 3, Scalar (0,255,255), cv_filled, Cv_aa), Circle (*img_02, Points_02[i], 3, Scalar (0,255,255), cv_filled, CV_AA);} Draw convex hull contour cvpoint poi_01 = points_01[hull_01[hull_01.size ()-1]];for (int i=0;i < hull_01.size (); ++i) {line (*img_01, poi_01, Points_01[i], Scalar (255,255,0), 1, cv_aa);p oi_01 = Points_01[i];} Cvpoint poi_02 = Points_02[hull_02[hull_02.size () -1]];for (int i=0;i < hull_02.size (); ++i) {line (*img_02, poi_02, Points_02[i], Scalar (255,255,0), 1, cv_aa);p oi_02 = Points_02[i];} Vector<vec4i> defects;//If there is a convex defect, draw it out if (Iscontourconvex (points_01)) {cout<< "img_01 contour is convex hull" <<endl ;} else{cout<< "img_01 outline is not convex hull" <<endl;convexitydefects (Points_01,mat (hull_01), defects);//Drawing defects cout< < total <<defects.size () << defect <<endl;for (int i=0;i < defects.size (); ++i) {Circle (*img_01, Points_01[defects[i][0]], 6, scalar (255,0,0), 2, Cv_aa), Circle (*img_01, Points_01[defects[i][1]], 6, Scalar (255,0,0), 2, CV_AA); Circle (*img_01, points_01[defects[i][2]], 6, Scalar (255,0,0), 2, CV_AA); line (*img_01, points_01[defects[i][ 0]], points_01[defects[i][1]], Scalar (255,0,0), 1, CV_AA), line (*IMG_01, points_01[defects[i][1]], points_01[defects[ I][2]], scalar (255,0,0), 1, CV_AA), line (*IMG_01, points_01[defects[i][2]], points_01[defects[i][0]], scalar (255,0,0), 1, Cv_aa);cout<< "<<i<<" Defects < "<<points_01[defects[i][0]].x<<", "<<points_ 01[defects[i][0]].y<< ">,<" <<points_01[defects[i][1]].x<< "," <<points_01[defects[i ][1]].y<< ">,<" <<points_01[defects[i][2]].x<< "," <<points_01[defects[i][2]].y< < "> Distance to Profile:" <<defects[i][3]/256<< "px" &LT;&LT;ENDL;} Defects.clear ();} if (Iscontourconvex (points_02)) {cout<< "img_02 Contour is convex package" &LT;&LT;ENDL;} else{cout<< "img_02 outline is not convex hull" <<endl;vector<Vec4i> defects;convexitydefects (Points_01,mat (hull_01 ), defects);//Draw the outline of the defect for (int i=0;i < defects.size (); ++i) {Circle (*img_02, Points_01[defects[i][0]], 6, Scalar ( 255,0,0), 2, Cv_aa), Circle (*img_02, Points_01[defects[i][1]], 6, Scalar (255,0,0), 2, CV_AA); Circle (*img_02, points_01[ DEFECTS[I][2]], 6, Scalar (255,0,0), 2, CV_AA); line (*img_02, Points_01[defects[i][0]], points_01[defects[i][1], Scalar (255,0,0), 1, CV_AA); line (*img_02, points_01[ DEFECTS[I][1]], points_01[defects[i][2]], Scalar (255,0,0), 1, CV_AA); line (*img_02, points_01[defects[i][2]], points_ 01[defects[i][0]], Scalar (255,0,0), 1, CV_AA);//Because img_02 is not defective, it is lazy to write those output code}defects.clear ();} Imshow ("img_01 Outline and convex hull:", *img_01); Imshow ("img_02 Contour and convex hull:", *img_02); Cvwaitkey (); return 0;}

  

OpenCV using convexitydefects to calculate contour convex defects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.