1

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?

1 Answer 1

1

Two approaches could be suggested -

255*(~((A==0) & (B==0))).astype(A.dtype)
255*(((A!=0) | (B!=0))).astype(A.dtype)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.