OpenCV And Python: Connected Components Analysis
Solution 1:
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)
Solution 2:
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 :-)
Solution 3:
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.FindContours
should work for you :)
Solution 4:
OpenCV 3.0.0-dev has connectedComponents
function but the doc says it is only for C++.
Solution 5:
In addition to Stefan van der Walt answer, here's a bit longer skimage labeling example:
from skimage import morphology
import cv2
import numpy as np
import sys
def get_image():
size = (w, h) = (100, 100)
img = np.zeros(size, np.uint8)
cv2.rectangle(img, (10, 10), (19, 19), (128), -1)
cv2.rectangle(img, (30, 20), (39, 39), (128), -1)
cv2.rectangle(img, (40, 30), (49, 49), (128), -1)
cv2.rectangle(img, (50, 70), (89, 79), (128), -1)
return img
def show_image(img):
cv2.imshow('result', img), cv2.waitKey(0)
if __name__ == '__main__':
img = get_image()
show_image(img)
labels = morphology.label(img, background=0)
label_number = 0
while True:
temp = np.uint8(labels==label_number) * 255
if not cv2.countNonZero(temp):
break
show_image(temp)
label_number += 1
cv2.destroyAllWindows()
Post a Comment for "OpenCV And Python: Connected Components Analysis"