【发布时间】:2020-11-08 19:30:36
【问题描述】:
请多多包涵,因为这是我在长期(未注册)网站用户之后的第一篇文章。
我有一个图像文件,其中感兴趣的图像中有特定区域。这些区域已通过单独测试每个像素/单元并确定它是否感兴趣 - 将感兴趣的区域附加到新列表中来识别。
所以我有一个表格列表:
[[22,25], [22,29], [23,24], ...]
它包含我所有特殊像素的索引,如果我要将这些图像绘制为黑色图像上的白色,则在宏观尺度上;我基本上会有两个连续的白色块。我想将此列表排序到另一个嵌套列表中,其中它们按连续性分组。也就是说,所有与白色块相关联的像素都将组合在一个嵌套列表中
我的想法是只抓取第一个点 (fpoint),然后通过测试 x 和 y 索引来测试所有其他点 (pts),以查看这两个点的差异是否不大于x 和 y 都有一个。所以每个测试都是这样的:
if ( (np.absolute(fpoint[0] - pts[0]) <= 1) and (np.absolute(fpoint[1] - pts[1]) <= 1) ):
#add this point to the same nested list as my fpoint
#remove this point from the initial list and continue to chisel down the original list until it is all sorted into my new list
鉴于此方法一次通过,我可能会获得多达 8 个相邻点,我需要跟踪这些点以单独测试每个点,因为我已将它们从旧列表中删除。
所以到最后我希望有这样的东西:
groupedList = [[[22,23], [21,24], [20,24], ...], [[102, 51], [102, 50], [100, 55]...]]
重申一维情况:
假设我有一个清单:
[1, 22, 5, 20, 3, 4, 21, 2]
在我的函数结束时,我希望有一个类似的列表:
[ [1, 5, 3, 4, 2], [22, 20, 21] ]
因为作为一个集合,1、5、3、4 和 2 与 22、20 和 21 一样是“连续的”。 我不关心数字的顺序,只要它们是分开的。
一些关于递归代码的东西听起来像是解决我的问题的一个优雅的解决方案,但我只是无法生成它。 感谢您的时间, 希思 M.
解决方案
授权给Anders Munch
凭借安德斯·蒙克给我的东西,我能够走到这一步,证明是令人满意的!
def candidate_neighbors(node):
return ((node[0]-1, node[1]-1), (node[0]-1, node[1]), (node[0]-1, node[1]+1), (node[0], node[1]-1),
(node[0], node[1]+1), (node[0]+1, node[1]-1), (node[0]+1, node[1]), (node[0]+1, node[1]+1))
def neighboring_groups(nodes):
remain = set(nodes)
while len(remain) > 0:
visit = [remain.pop()]
group = []
while len(visit) > 0:
node = visit.pop()
group.append(node)
for nb in candidate_neighbors(node):
if nb in remain:
remain.remove(nb)
visit.append(nb)
yield tuple(group)
nodes = ((22, 23), (22, 24), (21, 23), (1, 5), (2, 6), (21, 22), (3, 5))
print(tuple(neighboring_groups(nodes)))
(((1, 5), (2, 6), (3, 5)), ((22, 24), (22, 23), (21, 22), (21, 23)))
【问题讨论】:
标签: python sorting cell pixel contiguous