Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Efficient way to find the largest area of a specific value in a 2D numpy array

I have a 2D numpy array where some values are zero, and some are not. I'm trying to find an efficient way to find the biggest clump of zeros in the array (by returning the number of zeros, as well as a rough idea of where the center is)

For example in this array, I would like to find the clump of 9, with the center of (3,4):

[[ 1, 1, 1, 0, 0 ],
 [ 1, 0, 1, 1, 0 ],
 [ 1, 1, 1, 1, 1 ],
 [ 1, 1, 0, 0, 0 ],
 [ 1, 1, 0, 0, 0 ],
 [ 1, 1, 0, 0, 0 ]]

Is there a nice vectorized way to accomplish something like this in numpy or scipy?

The clumps will be roughly circular in shape, and have no holes in them.

ndimage.label() from scipy does something close to this, but isn't quite what I'm after. I have a feeling numpy.where() and numpy.diff() could be helpful, but not sure how to efficiently use them to solve this problem.

like image 963
Brent Avatar asked Nov 21 '13 00:11

Brent


People also ask

How do you find the largest element in a NumPy array?

Now try to find the maximum element. To do this we have to use numpy. max(“array name”) function. For finding the minimum element use numpy.

How do you find the maximum value of a 2D array?

Approach: The idea is to traverse the matrix using two nested loops, one for rows and one for columns, and find the maximum element. Initialize a variable maxElement with a minimum value and traverse the matrix and compare every time if the current element is greater than a maxElement.

How do you find the max and min value of a 2D array in Python?

We can find the minimum and maximum values from the each row of a 2D numpy array by using the "min" and "max" functions available in the Numpy library.

How do you find the index of the maximum value in an array in Python?

Use the enumerate() function to find out the index of the maximum value in a list. Use the numpy. argmax() function of the NumPy library to find out the index of the maximum value in a list.


1 Answers

You're almost there, you just need to combine ndimage.label with numpy.bincount:

import numpy as np
from scipy import ndimage

array = np.random.randint(0, 3, size=(200, 200))

label, num_label = ndimage.label(array == 0)
size = np.bincount(label.ravel())
biggest_label = size[1:].argmax() + 1
clump_mask = label == biggest_label

Once you have clump_mask you can compute the centroid or use some other method to get the center.

like image 86
Bi Rico Avatar answered Oct 31 '22 18:10

Bi Rico