Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV and Python: Connected components analysis

I have a working connected components analysis code working in C. It's actually a copy from the book "Learning Opencv".

Now I am rewriting all that code to Python and I cannot find some of that function in the Python API, like cvStartFindContours.

I am wondering is somebody has a basic connected components analysis function implemented in Python. I know there are some libraries, but I am searching for something simpler, just a function or a piece of code.

I don't need anything "big" because I have a plain black image with 2 or 3 white circles, and I want to find the number of circles and its center.

I know I can probably code on myself but I prefer to use somebody's function or simple library.

EDIT: I solved it the following way.

def find_connected_components(img):
    """Find the connected components in img being a binary image.
    it approximates by rectangles and returns its centers
    """

    storage = cv.CreateMemStorage(0)
    contour = cv.FindContours(img, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE)
    centers = []

    while contour:
        # Approximates rectangles
        bound_rect = cv.BoundingRect(list(contour))

        centers.append(bound_rect[0] + bound_rect[2] / 2, bound_rect[1] + bound_rect[3] / 2)

        contour = contour.h_next()
like image 265
Dr Sokoban Avatar asked Dec 02 '25 05:12

Dr Sokoban


2 Answers

There is BSD license connected components code (in Cython) as part of scikit-image:

https://github.com/scikit-image/scikit-image/blob/master/skimage/measure/_ccomp.pyx

If you have the package installed, it is as simple as

from skimage import measure
import numpy as np

L = measure.label(image)
print "Number of components:", np.max(L)
like image 191
Stefan van der Walt Avatar answered Dec 03 '25 21:12

Stefan van der Walt


a bit dated of a reply but there's also this patch: http://code.opencv.org/attachments/467/opencv-connectedcomponents.patch

should be one of the faster implementations out there and still easy to call. should be integrated into mainline sometime in the future...

edit: it's been in mainline for sometime waiting on 3.0 to release. Don't ask me why they didn't release it earlier!

disclaimer - I'm the author :-)

like image 36
Jason Newton Avatar answered Dec 03 '25 20:12

Jason Newton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!