cv2.connectedComponents未检测到组件 [英] cv2.connectedComponents not detecting components

查看:94
本文介绍了cv2.connectedComponents未检测到组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ubuntu python 2.7上.使用OpenCV.

I am on Ubuntu, python 2.7. Working with OpenCV.

我试图确切地了解cv2.connectedComponents函数的功能. 这是图像:

I was trying to understand exactly what the function cv2.connectedComponents is doing. This is the image:

代码:

import cv2
import numpy as np

img = cv2.imread('BN.tif', 0)

img = np.uint8(img)
_, markers = cv2.connectedComponents(img)

据我了解,此功能创建的数组大小与提供的图像相同.对于检测到的每个组件,为该组件的所有(y,x)位置分配相同的编号.如果背景全为"0",则圆圈将全为"1",下一个正方形全为"2",依此类推.最后一个成分应全为"19".我正在通过获取定义组件的最高编号来读取组件的数量:

From what I understood, this funtion creates an array with same size than the provided image. For each component detected assign the same number for all the (y,x) positions for that component. If the background is all '0', then the circle would be all '1', the next square all '2', etc. The last component should be all '19'. I am reading the numbers of components by getting the highest number defining a component:

np.amax(markers)

我应该得到19,但是我得到1.

I should get the 19, but I am getting 1.

我的问题:为什么我只得到1个组件?

My question: why I am getting only 1 component?

推荐答案

这是因为cv2.connectedComponents()仅将白色部分视为组件.因此,您将获得一个组件.

This is because cv2.connectedComponents() considers only the white portion as a component. Hence you are getting a single component.

您必须反转图像.您可以使用cv2.bitwise_not()函数来实现.

You have to invert your image. You can do so by using cv2.bitwise_not() function.

代码:

import cv2
import numpy as np

img = cv2.imread('cc.png', 0)
ret, thresh = cv2.threshold(img, 127, 255, 0)

#---- Inverting the image here ----
img = cv2.bitwise_not(thresh)     
_, markers = cv2.connectedComponents(img)
print np.amax(markers)

结果:

19

这篇关于cv2.connectedComponents未检测到组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆