Numpy:将索引的二维数组转换为一维数组以进行交集计算

2024-05-19 15:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个情况,我需要在python中做两个二进制图像数组的交集。理想情况下,我做得很快。在


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的正确方法是什么?在


Tags: 方法np二进制zeros情况sumshapedtype