/// <summary> /// computes the connected components labeled image of boolean image. /// image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 /// represents the background label. ltype specifies the output label image type, an important /// consideration based on the total number of labels or alternatively the total number of /// pixels in the source image. /// </summary> /// <param name="image">the image to be labeled</param> /// <param name="connectivity">8 or 4 for 8-way or 4-way connectivity respectively</param> /// <returns></returns> public static ConnectedComponents ConnectedComponentsEx( InputArray image, PixelConnectivity connectivity = PixelConnectivity.Connectivity8) { using (var labelsMat = new MatOfInt()) using (var statsMat = new MatOfInt()) using (var centroidsMat = new MatOfDouble()) { int nLabels = ConnectedComponentsWithStats( image, labelsMat, statsMat, centroidsMat, connectivity, MatType.CV_32S); var labels = labelsMat.ToRectangularArray(); var stats = statsMat.ToRectangularArray(); var centroids = centroidsMat.ToRectangularArray(); var blobs = new ConnectedComponents.Blob[nLabels]; for (int i = 0; i < nLabels; i++) { blobs[i] = new ConnectedComponents.Blob { Label = i, Left = stats[i, 0], Top = stats[i, 1], Width = stats[i, 2], Height = stats[i, 3], Area = stats[i, 4], Centroid = new Point2d(centroids[i, 0], centroids[i, 1]), }; } return new ConnectedComponents(blobs, labels, nLabels); } }