Python - 在 2D numpy 数组中查找特定值的最大区域的有效方法 [英] Python - Efficient way to find the largest area of a specific value in a 2D numpy array

查看:34
本文介绍了Python - 在 2D numpy 数组中查找特定值的最大区域的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 2D numpy 数组,其中有些值为零,有些值不是.我试图找到一种有效的方法来找到数组中最大的零块(通过返回零的数量,以及对中心位置的粗略了解)

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)

例如在这个数组中,我想找到以 (3,4) 为中心的 9 块:

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 ]]

在 numpy 或 scipy 中是否有一种很好的矢量化方式来完成这样的事情?

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() 做了一些事情接近这个,但不是我所追求的.我有一种感觉 numpy.where()numpy.diff() 可能会有所帮助,但不确定如何有效地使用它们来解决这个问题.

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.

推荐答案

大功告成,只需要将 ndimage.labelnumpy.bincount 结合起来:

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

一旦你有了 clump_mask,你就可以计算质心或使用其他方法来获得中心.

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

这篇关于Python - 在 2D numpy 数组中查找特定值的最大区域的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆