[英]Slicing array in regions - Python
I have to "divide" an nxm
array in regions using a mask input. 我必须使用遮罩输入将nxm
数组“划分”为nxm
区域。
For example, suppose I have a 20 x 20
array. 例如,假设我有一个20 x 20
阵列。 My mask is the following ( 5 x 5
) -- always: 我的面具是以下( 5 x 5
)-始终:
where the numbers represent the regions in which the cells take part. 其中数字代表细胞参与的区域。 This mask is not an input, that is just an ndarray
. 此掩码不是输入,而只是ndarray
。 This mask just represent how I should slice my 20 x 20
at every 5 x 5
neighborhood. 这个面具只代表我应该如何在每5 x 5
邻域中切片20 x 20
。
For example, the first region comprehend the indices: 例如,第一个区域包含索引:
(0,0), (1,0), (1,1), (2,0), (2,1), (2,2) (0,0),(1,0),(1,1),(2,0),(2,1),(2,2)
For each 5 x 5
neighborhood of my 20 x 20
array, I should return the values that are in each of the 8
regions. 对于20 x 20
数组中的每个5 x 5
邻域,我应该返回8
区域中每个区域中的值。
I know how to do that with a "standard code", but I wondering if there is a Pythonic way of do that, possible with a concise code. 我知道如何用“标准代码”来做到这一点,但是我想知道是否有Python的方式可以做到,而用简洁的代码就可以做到。
As a code example, I could do something like: 作为一个代码示例,我可以做类似的事情:
def slice_in_regions(data, x_dim, y_dim):
for x in xrange(0, x_dim, 5):
for y in xrange(0, y_dim, 5):
neighbors = data[x:x+4, y:y+4]
region1 = [neighbors[0,0], neighbors[1,0], neighbors[1,1], neighbors[2,0], neighbors[2,1], neighbors[2,2]]
# region2, region3...
However, that doesn't seem to be a good way to do that. 但是,这似乎不是实现此目的的好方法。 Moreover, I'm counting on that my data will dimension be multiple of 5
. 此外,我指望我的数据将是5
倍数。
Thank you. 谢谢。
It seems you could probably just resize your mask, eg if you're already using numpy
, 看来您可能只是调整了蒙版的大小,例如,如果您已经在使用numpy
,
mask = mask.repeat(4, axis=0).repeat(4, axis=1)
# Then you apply the mask using
values = data[mask]
Otherwise, 除此以外,
import numpy as np
mask = np.repeat(mask, 4, axis=0).repeat(4, axis=1)
# Then you apply the mask using
values = np.array(data)[mask]
Individual regions 个别地区
If you need to access each region individually, you could precede the previous by using a labelled mask; 如果您需要单独访问每个区域,则可以使用标记的掩码在前一个区域之前; as the labels will be grown into labelled regions you can then use, eg 因为标签将长成带标签的区域,您可以使用,例如
values = [ data[mask==l] for l in range(1, mask.max()+1)]
Here values will be a list of arrays where each item corresponds to a labelled region in mask
. 这里的值将是一个数组列表,其中每个项目对应于mask
的标记区域。
Generating the labelled mask 生成标记的蒙版
For completeness, to get from a binary mask to a labelled mask where every on pixel has it's own label you could use scipy.ndimage.label
为了完整scipy.ndimage.label
,要从二进制蒙版scipy.ndimage.label
到每个像素上都有自己的标签的带标签的蒙版,可以使用scipy.ndimage.label
mask = ndimage.label(mask, [[0,0,0],[0,1,0],[0,0,0]])
or if using a region labelling function is overkill, you can achieve a similar result using 或如果使用区域标签功能过大,则可以使用
mask[mask] = range(1,mask.sum()+1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.