【问题标题】:Python: How to check if an array is contained in another array using `numpy.all`and `numpy.any`?Python:如何使用`numpy.all`和`numpy.any`检查一个数组是否包含在另一个数组中?
【发布时间】:2015-09-11 17:37:57
【问题描述】:

我正在使用scikit-image 检测图像上的某些区域。我能够使用blob_doh 函数检测到斑点。我还能够使用Canny edge detector 和标签找到区域。

现在我想检查我之前找到的 blob 是否在这些区域内,并整理出那些不在任何区域内的 blob。然后我只想绘制区域内的斑点。

我试图使用numpy.allnumpy.any 来实现这一点,但我可能误解了这些函数的工作方式。这是我所拥有的:

for region in regions:
    # list of pixels' coords in a region
    pixel_array = region.coords

    # check if a blob is inside the region
    for blob in blobs_doh:
        y, x, r = blob

        if np.any(pixel_array == [x, y]):
            c = plt.Circle((x, y), r, color='red', linewidth=1, fill=False)
            minr, minc, maxr, maxc = region.bbox
            rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='lime', linewidth=1)
            # draw blobs and regtangles
            ax.add_patch(c)
            ax.add_patch(rect)
            break

那么,我要做什么。 region[[a1, b1], [a2, b2], [a3, b3], ..., [an, bn]] 形状的数组,blob[c, d] 形状的数组。我的想法是检查region 中是否有任何子数组等于blob。我当然可以用简单的方式在循环中搜索,但我认为有更有效的方法可以做到这一点,并尝试使用numpy.allnumpy.any。不幸的是,我无法让它正常工作。 np.any(pixel_array == [x, y]) 行仅检查 blob 的第一个元素,但不检查整个子数组 [x, y]。我还使用axis 参数尝试了.any.all 的不同组合:

np.any(pixel_array == [x, y], axis = 1).all(axis = 0)

但无法得到任何可接受的结果。

请帮我完成这项任务。执行此类检查的更好方法是什么?

谢谢。

【问题讨论】:

标签: python arrays python-2.7 numpy scikit-image


【解决方案1】:

如果您将 pixel_array 转换为列表,您可以做到这一点。不知道这会有多有效,但这很有效:

if [x,y] in pixel_array.tolist():

编辑:

看起来有人已经为很多不同的选项计时了in this answer。上面的tolist() 解决方案还不错,但在一系列场景中的最佳选择似乎是:

 if any(np.equal(pixel_array,[x,y]).all(1)):

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 2015-10-28
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多