gpt4 book ai didi

Python 2D 簇查找器

转载 作者:行者123 更新时间:2023-11-30 23:39:08 26 4
gpt4 key购买 nike

我得到了一个由 0 和 1 组成的数组。如图所示,1 形成连续的簇。

Clustering

事先不知道簇的数量。

是否有某种方法可以创建一个包含所有簇位置的列表,或者为每个簇创建一个包含其所有成员位置的列表。例如:

cluster_list = continuous_cluster_finder(data_array)
cluster_list[0] = [(pixel1_x, pixel1_y), (pixel2_x, pixel2_y),...]

最佳答案

从描述中并不清楚问题的确切约束是什么。假设您可以通过左、右、上、下的零来区分簇,那么以下解决了问题...

#!/usr/bin/env python

data = [ #top-left
[0,0,1,1,0,0],
[0,0,1,1,0,0],
[1,1,0,0,1,1],
[1,1,0,0,1,1],
[0,0,1,1,0,0],
[0,0,1,1,0,0],
[1,1,0,0,1,1],
[1,1,0,0,1,1],
] # bottom-right

d = {} # point --> clid
dcl = {} # clid --> [point1,point2,...]

def process_point(t):
global clid # cluster id
val = data[t[0]][t[1]]
above = (t[0]-1, t[1])
abovevalid = 0 <= above[0] < maxX and 0 <= above[1] < maxY
#below = (t[0]+1, t[1]) # We do not need that because we scan from top-left to bottom-right
left = (t[0], t[1]-1)
leftvalid = 0 <= left[0] < maxX and 0 <= left[1] < maxY
#right = (t[0], t[1]+1) # We do not need that because we scan from top-left to bottom-right

if not val: # for zero return
return
if left in d and above in d and d[above] != d[left]:
# left and above on different clusters, merge them
prevclid = d[left]
dcl[d[above]].extend(dcl[prevclid]) # update dcl
for l in dcl[d[left]]:
d[l] = d[above] # update d
del dcl[prevclid]
dcl[d[above]].append(t)
d[t] = d[above]
elif above in d and abovevalid:
dcl[d[above]].append(t)
d[t] = d[above]
elif left in d and leftvalid:
dcl[d[left]].append(t)
d[t] = d[left]
else: # First saw this one
dcl[clid] = [t]
d[t] = clid
clid += 1

def print_output():
for k in dcl: # Print output
print k, dcl[k]

def main():
global clid
global maxX
global maxY
maxX = len(data)
maxY = len(data[0])
clid = 0
for i in xrange(maxX):
for j in xrange(maxY):
process_point((i,j))
print_output()

if __name__ == "__main__":
main()

它打印...

0 [(0, 2), (0, 3), (1, 2), (1, 3)]
1 [(2, 0), (2, 1), (3, 0), (3, 1)]
2 [(2, 4), (2, 5), (3, 4), (3, 5)]
3 [(4, 2), (4, 3), (5, 2), (5, 3)]
4 [(6, 0), (6, 1), (7, 0), (7, 1)]
5 [(6, 4), (6, 5), (7, 4), (7, 5)]

关于Python 2D 簇查找器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13832083/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com