如何查找图像中的簇数?

时间:2018-08-29 23:57:57

标签: python python-2.7 opencv opencv3.0

找到此图像中的簇数:

我试图在此图像中找到群集的数量。我尝试过openCV morphologyEx并腐蚀,但似乎无法为每个群集获得单个像素。请建议最好使用Python的openCV来计算图像中簇数的最佳方法。

-编辑

我尝试了细化,腐蚀和morphologyEx(关闭),但是无法将群集收敛到单个像素。以下是我尝试过的一些事情。

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)

2 个答案:

答案 0 :(得分:2)

这怎么样?

import numpy as np
import cv2

img = cv2.imread('points.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh)

print(n_labels)

size_thresh = 1
for i in range(1, n_labels):
    if stats[i, cv2.CC_STAT_AREA] >= size_thresh:
        #print(stats[i, cv2.CC_STAT_AREA])
        x = stats[i, cv2.CC_STAT_LEFT]
        y = stats[i, cv2.CC_STAT_TOP]
        w = stats[i, cv2.CC_STAT_WIDTH]
        h = stats[i, cv2.CC_STAT_HEIGHT]
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), thickness=1)

cv2.imwrite("out.jpg", img)

簇数:974
out.jpg:
enter image description here

答案 1 :(得分:2)

解决方案就是这么简单。您应该找到图像轮廓的数量并计数。为此,您可以使用带有以下参数的f = {} ans = int(input('How many days of data do you have? ')) #figure out how to open certain files for file_num in range(1, (ans+1)): file_name = "temps" + str(file_num) + ".txt" temps = open(file_name) for line in temps: room, num = line.strip('\n').split(',') num = int(num) #may need to be 4* however many times it appears num = num/(4*ans) f[room] = f.get(room, 0) + num print('Average Temperatures:') for x in f: print (x + ':',f[x]) 方法。有关cv2.findContours的更多详细信息,请检查documentation

cv2.findContours

输出:

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)