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()
You should take a look at the documentation. As of OpenCV 2.2 there is a complete new interface for Python which covers all C/C++ functions 🙂
cv.FindContoursshould work for you 🙂