Python Numpy:将二维索引数组转换为一维数组以进行交点计算
有一种情况,我需要在python中进行两个二进制图像数组的交集。理想情况下,我会很快做到这一点Python Numpy:将二维索引数组转换为一维数组以进行交点计算,python,arrays,numpy,Python,Arrays,Numpy,有一种情况,我需要在python中进行两个二进制图像数组的交集。理想情况下,我会很快做到这一点 Numpy有intersect1d功能,如果我能将坐标转换成单个元素,它将完成这项工作 现在(因为我知道我照片的尺寸),我通过使用乘法、求和、求交将所有内容转换成整数格式,然后使用类似的方法解包 def npimg_intersection(A,B): Aargwhere = np.argwhere(A==0) Bargwhere = np.argwhere(B==0) A
Numpy有
intersect1d
功能,如果我能将坐标转换成单个元素,它将完成这项工作
现在(因为我知道我照片的尺寸),我通过使用乘法、求和、求交将所有内容转换成整数格式,然后使用类似的方法解包
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
它是有效的。相当快
但是,使用numpy做这件事的正确方法是什么(不太黑客化)?可以建议两种方法-
255*(~((A==0) & (B==0))).astype(A.dtype)
255*(((A!=0) | (B!=0))).astype(A.dtype)