以下示例清楚地说明了我的问题:
假设他们是一个数组'arr'
>>import numpy as np
>>from skimage.util.shape import view_as_blocks
>>arr=np.array([[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16],[17,18,19,20,21,22,23,24]])
>>arr
array([[ 1, 2, 3, 4, 5, 6, 7, 8],
[ 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16],
[17, 18, 19, 20, 21, 22, 23, 24]])
我使用以下方法将此数组分割为2 * 2块:
>>img= view_as_blocks(arr, block_shape=(2,2))
>>img
array([[[[ 1, 2],
[ 1, 2]],
[[ 3, 4],
[ 3, 4]],
[[ 5, 6],
[ 5, 6]],
[[ 7, 8],
[ 7, 8]]],
[[[ 9, 10],
[17, 18]],
[[11, 12],
[19, 20]],
[[13, 14],
[21, 22]],
[[15, 16],
[23, 24]]]])
我有另一个数组“cor”
>>cor
(array([0, 1, 1], dtype=int64), array([2, 1, 3], dtype=int64))
在“cor”中,第一个数组([0,1,1])给出行的坐标,第二个数组([2,1,3])按顺序给出相应列的坐标。
现在我的工作是访问img的片段,其位置坐标为[0,2],[1,1]和[1,3](取自“cor”.x来自第一个数组,相应的y来自第二个数组)自动读“cor”。
在上面的例子中
img[0,2]= [[ 5, 6], img[1,1]= [[11, 12], img[1,3]=[[15, 16],
[ 5, 6]], [19, 20]] [23, 24]]
然后分别找到每个段的平均值。
ie. img[0,2]=5.5 img[1,1]=15.5 img[1,3]=19.5
现在,检查它的平均值是否小于整个数组“img”的平均值。这里,img的平均值是10.5。因此,只有img [0,2]的平均值小于10.5。因此,如果在任何其他大数组中存在更多段,则最终返回段img [0,2]的坐标,即[0,2]作为顺序输出。
##expected output for above example:
[0,2]
我们只需要用cor
索引并执行那些mean
计算(沿着最后两个轴)并检查 -
# Convert to array format
In [229]: cor = np.asarray(cor)
# Index into `img` with tuple version of `cor`, so that we get all the
# blocks in one go and then compute mean along last two axes i.e. 1,2.
# Then compare against global mean - `img.mean()` to give us a valid
# mask. Then index into columns of `cor with it, to give us a slice of
# valid `cor`. Finally transpose, so that we get per row valid indices set.
In [254]: cor[:,img[tuple(cor)].mean((1,2))<img.mean()].T
Out[254]: array([[0, 2]])
建立它的另一种方法是拆分指数 -
In [235]: r,c = cor
In [236]: v = img[r,c].mean((1,2))<img.mean() # or img[cor].mean((1,2))<img.mean()
In [237]: r[v],c[v]
Out[237]: (array([0]), array([2]))
与第一种方法相同,唯一的区别是使用拆分索引来索引到cor
并获得最终索引。
或紧凑版 -
In [274]: np.asarray(cor).T[img[cor].mean((1,2))<img.mean()]
Out[274]: array([[0, 2]])
在这个解决方案中,我们直接提供cor
的原始元组版本,其余与方法#1相同。