Andrew Hundt
Andrew Hundt

Reputation: 2591

Intersect two numpy index arrays

Suppose I have two images that are thresholded differently, and I want to find the set intersection of indexes over both threshold, in other words all the indexes that are in both lists. Assume the dimensions are equal, so there is nothing to worry about for that.

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

How can I do this in a way that is easy to understand and in a way that is efficient?

Upvotes: 1

Views: 2402

Answers (1)

Divakar
Divakar

Reputation: 221524

If you are looking for matching nonzero XY indices pairs, you can use boolean ANDing between the nonzero masks of the input arrays and then use np.nonzero, like so -

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

You can verify these results with np.intersect1d after getting the linear indices of matches from img1 and img2 giving us a second approach to solve the problem at hand , like so -

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

Sample run -

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]))

Upvotes: 2

Related Questions