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

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

问题描述

我有一个二维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)

例如在此数组中,我想找到簇9,中心为(3,4):

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()

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-在二维numpy数组中查找特定值的最大面积的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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