快速的方法来通过上采样近邻瓦片numpy的数组 [英] Quick way to upsample numpy array by nearest neighbor tiling
本文介绍了快速的方法来通过上采样近邻瓦片numpy的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个整数的二维数组,它是的的M×N 的,我想在阵列扩展到的(BM)×(BN)的,其中的乙的是一个正方形瓷砖边的长度从而输入数组中的每个元素被重复作为最终阵列中的一个的 BXB 的块。下面是使用嵌套for循环的例子。是否有一个更快的/内置的方式吗?
导入numpy的是NPA = np.arange(9).reshape([3,3])#输入数组 - 3×3
B = 2。 #块大小 - 2
A = np.zeros([a.shape [0] * B,a.shape [1] * B])#输出数组 - 6x6的#循环,每个指数的瓷砖值填充
为I,L在枚举(一):在一#线
对于j,AIJ在历数(1):#A [I,J]
A [B * I:B *(I + 1),B * Y: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轴= 0).repeat(2轴= 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屋!
查看全文