Chris
Chris

Reputation: 31246

Numpy: convert 2D array of indices to 1D array for intersection calculation

I have a situation where I need to do the intersection of two binary image arrays in python. Ideally, I do this pretty quickly.


Numpy has the intersect1d function that will do the job, if I can turn my coordinates into single elements.

Right now (since I know the dimensions of my photos), I do the trick by converting everything into integer format using a multiply, sum, intersection...then unpack using similar means.

def npimg_intersection(A,B):
    Aargwhere = np.argwhere(A==0)
    Bargwhere = np.argwhere(B==0)

    Aargwhere[:,0] = Aargwhere[:,0]*1000
    Aargwhere = np.sum(Aargwhere,axis=1)

    Bargwhere[:,0] = Bargwhere[:,0]*1000
    Bargwhere = np.sum(Bargwhere,axis=1)

    Iargwhere0 = np.intersect1d(Aargwhere,Bargwhere)

    Iargwhere = np.zeros(shape=(Iargwhere0.shape[0],2),dtype=Iargwhere0.dtype)
    Iargwhere[:,0] = Iargwhere0[:]/1000
    Iargwhere[:,1] = Iargwhere0[:]%1000


    I = np.zeros(shape = A.shape,dtype=A.dtype)
    I[:,:] = 255
    I[Iargwhere[:,0],Iargwhere[:,1]] = 0
    return I

And it works. Fairly quickly.


But what is the correct (less hack-ish) way to do this using numpy?

Upvotes: 1

Views: 391

Answers (1)

Divakar
Divakar

Reputation: 221604

Two approaches could be suggested -

255*(~((A==0) & (B==0))).astype(A.dtype)
255*(((A!=0) | (B!=0))).astype(A.dtype)

Upvotes: 1

Related Questions