![](/img/trans.png)
[英]finding largest connected component using opencv 2.4 in python 2.7
[英]How to extract the largest connected component using OpenCV and Python?
我在 Python 中使用 OpenCV 来仅识别图像上显示的 Leaf。 我已经能够分割我的图像,现在我目前被困在“如何在检测到所有组件后裁剪最大的组件。下面是代码,请看一看。
使用scipy.ndimage,找到组件后无法前进:
def undesired_objects ( image ): components, n = ndimage.label( image ) components = skimage.morphology.remove_small_objects( components, min_size = 50 ) components, n = ndimage.label( components ) plot.imshow( components ) plot.show()
使用 OpenCV connectedComponentsWithStats:
def undesired_objects ( image ): image = image.astype( 'uint8' ) nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4) sizes = stats[1:, -1]; nb_components = nb_components - 1 min_size = 150 img2 = np.zeros(( output.shape )) for i in range(0, nb_components): if sizes[i] >= min_size: img2[output == i + 1] = 255 plot.imshow( img2 ) plot.show()
然而,在这两种方法中,结果我仍然得到不止一个组件。 在下面,您将找到二进制图像:
我会用这样的东西替换你的代码:
def undesired_objects (image):
image = image.astype('uint8')
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4)
sizes = stats[:, -1]
max_label = 1
max_size = sizes[1]
for i in range(2, nb_components):
if sizes[i] > max_size:
max_label = i
max_size = sizes[i]
img2 = np.zeros(output.shape)
img2[output == max_label] = 255
cv2.imshow("Biggest component", img2)
cv2.waitKey()
组件上的循环现在会找到面积最大的组件并将其显示在循环的末尾。
告诉我这是否适合你,因为我自己还没有测试过。
使用cv2.CC_STAT_AREA
提高可读性:
# Connected components with stats.
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4)
# Find the largest non background component.
# Note: range() starts from 1 since 0 is the background label.
max_label, max_size = max([(i, stats[i, cv2.CC_STAT_AREA]) for i in range(1, nb_components)], key=lambda x: x[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.