Imageimg = new Image ("hand.jpg"); Image gray = img.Convert (); VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint(); Mat hierarchy = new Mat(); CvInvoke.FindContours(gray, contours, hierarchy, RetrType.List, ChainApproxMethod.ChainApproxSimple); for (int i = 0; i < contours.Size; i++) { VectorOfPoint contour = contours[i]; VectorOfInt hull = new VectorOfInt(); CvInvoke.ConvexHull(contour, hull, true); if (hull.Size > 2) { VectorOfPoint approxCurve = new VectorOfPoint(); CvInvoke.ApproxPolyDP(contour, approxCurve, 0.02 * CvInvoke.ArcLength(contour, true), true); if (approxCurve.Size > 2) { VectorOfInt defects = new VectorOfInt(); CvInvoke.ConvexityDefects(contour, hull, defects); for (int j = 0; j < defects.Size; j++) { int startIdx = defects[j * 4]; Point startPoint = contour[startIdx]; int endIdx = defects[j * 4 + 1]; Point endPoint = contour[endIdx]; int farthestIdx = defects[j * 4 + 2]; Point farthestPoint = contour[farthestIdx]; float depth = defects[j * 4 + 3] / 256f; if (depth > 10) { CvInvoke.Circle(img, farthestPoint, 10, new MCvScalar(0, 0, 255), 2); } } } } } CvInvoke.Imshow("Hand", img); CvInvoke.WaitKey();
ImageThis code creates a simple triangle shape and uses convexity defects to detect any significant indents in its shape. It then draws circles around any defects and outlines the original shape.img = new Image (800, 600); img.SetZero(); VectorOfPoint contour = new VectorOfPoint(new Point[] { new Point(100, 100), new Point(700, 100), new Point(400, 500) }); VectorOfInt hull = new VectorOfInt(); CvInvoke.ConvexHull(contour, hull, true); VectorOfPoint approxCurve = new VectorOfPoint(); CvInvoke.ApproxPolyDP(contour, approxCurve, 0.02 * CvInvoke.ArcLength(contour, true), true); if (approxCurve.Size > 2) { VectorOfInt defects = new VectorOfInt(); CvInvoke.ConvexityDefects(contour, hull, defects); for (int j = 0; j < defects.Size; j++) { int startIdx = defects[j * 4]; Point startPoint = contour[startIdx]; int endIdx = defects[j * 4 + 1]; Point endPoint = contour[endIdx]; int farthestIdx = defects[j * 4 + 2]; Point farthestPoint = contour[farthestIdx]; float depth = defects[j * 4 + 3] / 256f; if (depth > 10) { CvInvoke.Circle(img, farthestPoint, 10, new MCvScalar(0, 0, 255), 2); } } } CvInvoke.Polylines(img, contour, true, new MCvScalar(255, 0, 0), 2); CvInvoke.Imshow("Triangle", img); CvInvoke.WaitKey();