Python: how to check if an array is contained in another array using `numpy.all` and` numpy.any`?

I am working on defining specific areas of an image with scikit-image

. I was able to detect blobs using a function blob_doh

. Also I was able to find areas using Canny edge detector

and labeling.

Now I want to check if the blobs I found earlier are inside these regions and sort those blobs that are not in any of the regions. Then I want to draw only the blobs that are inside the areas.

I've tried to implement this with numpy.all

and numpy.any

, but I'm probably misunderstanding how these functions work. Here's what I have:

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

      

So what am I doing. region

is a shape array [[a1, b1], [a2, b2], [a3, b3], ..., [an, bn]]

, a blob

is a shape array [c, d]

. My idea was to check if there is any submatrix in region

, equal blob

. I could do this, of course, trivially using loop search, but I thought there was a more efficient way to do this and tried using numpy.all

and numpy.any

. Unfortunately, I cannot get it to work correctly. The string np.any(pixel_array == [x, y])

only checks the first element blob

, not the [x, y]

whole submatrix . I have also tried various combinations .any

and .all

with an argument axis

:

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

      

but couldn't get an acceptable result.

Please help me with this task. What is the best way to perform such a check?

Thank.

+3


source to share


1 answer


You can do this by converting pixel_array to a list. Not sure how efficient it would be, but this works:

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

      

EDIT:



It looks like someone has timed a lot of different options in this answer already. The above solution is tolist()

not that bad, but the best option in multiple scenarios looks like this:

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

      

0


source







All Articles