python - 如何找到图像中的簇数?

标签 python python-2.7 opencv opencv3.0

找出这张图片中的簇数:

我正在尝试查找此图像中的簇数。我尝试了 openCV morphologyEx 和侵 eclipse ,但似乎无法为每个簇获得单个像素。请建议最好在 Python 中使用 openCV 来计算图像中簇数的最佳方法。

--编辑

我尝试了细化、侵 eclipse 和 morphologyEx(closing),但无法将簇聚成单个像素。以下是我尝试过的一些方法。

kernel = np.ones((2, 2), np.uint8) #[[1,1,1],[1,1,1],[1,1,1]
erosion = cv2.erode(img, kernel, iterations=1)
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imwrite('test1.jpg', erosion)
cv2.imwrite('test2.jpg', closing)

img = cv2.imread(file, 0)
size = np.size(img)
skel = np.zeros(img.shape, np.uint8)

#ret, img = cv2.threshold(img, 127, 255, 0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
done = False

while (not done):
    eroded = cv2.erode(img, element)
    temp = cv2.dilate(eroded, element)
    temp = cv2.subtract(img, temp)
    skel = cv2.bitwise_or(skel, temp)
    img = eroded.copy()

    zeros = size - cv2.countNonZero(img)
    if zeros == size:
        done = True

cv2.imwrite('thinning.jpg', skel)

最佳答案

解决方法就这么简单。您应该找到图像的轮廓数并计算它们。为此,您可以使用带有以下参数的 cv2.findContours 方法。有关 cv2.findContours 的更多详细信息,请查看 documentation .

import cv2
img = cv2.imread('test.jpg', 0)
cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU,img)

image, contours, hier = cv2.findContours(img, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
count = len(contours)
print(count)

输出:

973

关于python - 如何找到图像中的簇数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52087533/

相关文章:

Python 2.7 随机码

python-2.7 - 如何使用 boto 使用 SPOT Block 启动 EMR?

c++ - opencv拼接免费dll

c++ - opencv如何用鼠标事件不规则地选择图像区域? C/C++

python - 如何通过 subprocess.Popen Python 将多个 linux 命令作为参数序列运行

Python 跳过数字

python - Python 中缺少动态查找器和方法

algorithm - 我在哪里可以学习/找到使用 OpenCV 从 Kinect 流式传输的手势识别示例?

python - 在 bash 管道中使用时,保留 Jenkins 中 python 脚本的返回代码

python - Pandas : select row where column A does not begin with column B