【问题标题】:Intersect two numpy index arrays相交两个 numpy 索引数组
【发布时间】:2015-09-22 18:33:27
【问题描述】:

假设我有两个阈值不同的图像,并且我想找到超过两个阈值的索引的集合交集,换句话说,两个列表中的所有索引。假设尺寸是相等的,所以没有什么可担心的。

img1 = #something
img2 = #something slightly different
indexes1 = np.nonzero(img1)
indexes2 = np.nonzero(img2)
index_intersection = #???

我怎样才能以易于理解且高效的方式做到这一点?

【问题讨论】:

  • 假设img1img2 的样本数据并向我们展示预期的输出?
  • @AGML 这个问题是关于几何(也属于无限集)交集的,而这个问题是关于有限集交集的。相似,但不同!

标签: python numpy indexing set-intersection


【解决方案1】:

如果您正在寻找匹配的非零 XY 索引对,您可以在输入数组的非零掩码之间使用布尔与运算,然后使用 np.nonzero,就像这样 -

out = np.nonzero((img1!=0) & (img2!=0))

在从 img1img2 获得匹配的线性索引后,您可以使用 np.intersect1d 验证这些结果,这为我们提供了解决手头问题的第二种方法,就像这样 -

l_intsct = np.intersect1d(np.nonzero(img1.ravel())[0],np.nonzero(img2.ravel())[0])
out = np.unravel_index(l_intsct,img1.shape)

示例运行 -

In [127]: img1
Out[127]: 
array([[3, 2, 3, 1, 0],
       [3, 1, 1, 2, 2],
       [0, 2, 3, 2, 1],
       [0, 0, 0, 4, 2]])

In [128]: img2
Out[128]: 
array([[1, 1, 4, 0, 0],
       [0, 0, 0, 0, 2],
       [4, 1, 0, 3, 1],
       [1, 0, 4, 1, 4]])

In [129]: np.nonzero(img1)
Out[129]: 
(array([0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3]),
 array([0, 1, 2, 3, 0, 1, 2, 3, 4, 1, 2, 3, 4, 3, 4]))

In [130]: np.nonzero(img2)
Out[130]: 
(array([0, 0, 0, 1, 2, 2, 2, 2, 3, 3, 3, 3]),
 array([0, 1, 2, 4, 0, 1, 3, 4, 0, 2, 3, 4]))

In [131]: np.nonzero((img1!=0) & (img2!=0))
Out[131]: (array([0, 0, 0, 1, 2, 2, 2, 3, 3]), array([0, 1, 2, 4, 1, 3, 4, 3, 4]))

In [132]: l_intsct = np.intersect1d(np.nonzero(img1.ravel())[0],np.nonzero(img2.ravel())[0])

In [133]: np.unravel_index(l_intsct,img1.shape)
Out[133]: (array([0, 0, 0, 1, 2, 2, 2, 3, 3]), array([0, 1, 2, 4, 1, 3, 4, 3, 4]))

【讨论】:

  • 有趣!如果每个都有 (0,0) 怎么办?
  • @AndrewHundt 如果 R1,C1 = np.nonzero(img1)R2,C2 = np.nonzero(img2) 并且您的意思是 (0,0) 作为一对 RC,这已经在列出的示例中发生,然后查看列出的解决方案中的输出:R,C = np.nonzero((img1!=0) & (img2!=0)) 为您提供了那对,对吗?或者你还有什么意思?
  • 在我的用例中,我尝试了该命令,但它似乎不起作用。我不知道为什么。
猜你喜欢
  • 1970-01-01
  • 2019-05-26
  • 2017-05-04
  • 2012-08-03
  • 1970-01-01
  • 2022-01-09
  • 2012-07-14
  • 1970-01-01
  • 2019-05-02
相关资源
最近更新 更多