通过最近邻平铺对 numpy 数组进行上采样的快速方法 [英] Quick way to upsample numpy array by nearest neighbor tiling
本文介绍了通过最近邻平铺对 numpy 数组进行上采样的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 MxN 的二维整数数组,我想将数组扩展为 (BM)x(BN) 其中 B 是正方形图块边的长度,因此输入数组的每个元素在最终数组中作为 BxB 块重复.下面是一个带有嵌套 for 循环的示例.有没有更快/内置的方法?
将 numpy 导入为 npa = np.arange(9).reshape([3,3]) # 输入数组 - 3x3乙=2.# 块大小 - 2A = np.zeros([a.shape[0]*B,a.shape[1]*B]) # 输出数组 - 6x6# 循环,在每个索引处用 a 的平铺值填充 Afor i,l in enumerate(a): # 行 a对于 enumerate(l) 中的 j,aij: # a[i,j]A[B*i:B*(i+1),B*j:B*(j+1)] = aij
结果...
a= [[0 1 2][3 4 5][6 7 8]]A = [[ 0. 0. 1. 1. 2. 2.][ 0. 0. 1. 1. 2. 2. ][ 3. 3. 4. 4. 5. 5. ][ 3. 3. 4. 4. 5. 5. ][ 6. 6. 7. 7. 8. 8. ][ 6. 6. 7. 7. 8. 8. ]]
解决方案
一种选择是
<预><代码>>>>a.repeat(2,axis=0).repeat(2,axis=1)数组([[0, 0, 1, 1, 2, 2],[0, 0, 1, 1, 2, 2],[3, 3, 4, 4, 5, 5],[3, 3, 4, 4, 5, 5],[6, 6, 7, 7, 8, 8],[6, 6, 7, 7, 8, 8]])由于中间数组,这有点浪费,但至少简洁.
I have a 2D array of integers that is MxN, and I would like to expand the array to (BM)x(BN) where B is the length of a square tile side thus each element of the input array is repeated as a BxB block in the final array. Below is an example with a nested for loop. Is there a quicker/builtin way?
import numpy as np
a = np.arange(9).reshape([3,3]) # input array - 3x3
B=2. # block size - 2
A = np.zeros([a.shape[0]*B,a.shape[1]*B]) # output array - 6x6
# Loop, filling A with tiled values of a at each index
for i,l in enumerate(a): # lines in a
for j,aij in enumerate(l): # a[i,j]
A[B*i:B*(i+1),B*j:B*(j+1)] = aij
Result ...
a= [[0 1 2]
[3 4 5]
[6 7 8]]
A = [[ 0. 0. 1. 1. 2. 2.]
[ 0. 0. 1. 1. 2. 2.]
[ 3. 3. 4. 4. 5. 5.]
[ 3. 3. 4. 4. 5. 5.]
[ 6. 6. 7. 7. 8. 8.]
[ 6. 6. 7. 7. 8. 8.]]
解决方案
One option is
>>> a.repeat(2, axis=0).repeat(2, axis=1)
array([[0, 0, 1, 1, 2, 2],
[0, 0, 1, 1, 2, 2],
[3, 3, 4, 4, 5, 5],
[3, 3, 4, 4, 5, 5],
[6, 6, 7, 7, 8, 8],
[6, 6, 7, 7, 8, 8]])
This is slightly wasteful due to the intermediate array but it's concise at least.
这篇关于通过最近邻平铺对 numpy 数组进行上采样的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文