我有一个类似的问题here
这个问题与 tiff 数据类似,我想找到一种更通用的方法来处理它。
我的问题
例如:
- 形状为 200x150 的二维 numpy 数组表示 1 公里 x 1 公里分辨率的人口密度数据。
http://i4.tietuku.com/060fe38e9ccf6daf.png
- 我的目标:改变空间分辨率=> 5 km x 5 km分辨率
this is an example picturefor random distributed data cluster into grid network http://i4.tietuku.com/a4c1355413f8cdbc.png
* the red point: original data
* the blue dot: grid network represent the 2-d array * the green circle: find the nearest blue dot for each red point and sum them.
* In this question, the difference is that the original data is 2-d numpy array too.
我的解决方案
与我的另一个问题类似here我将 2-d 散点聚类到最近的网格点。我感谢@HYRY 支持的答案,它大大改进了我的代码。
在该题中,我使用了KD-tree算法来寻找每个原始点数据的最近网络节点。结果显示在这里:
http://i4.tietuku.com/1a420c48ed7bcb1c.png我认为必须有一些更简单的方法来 reshape 结构化二维 numpy 数组而不是随机二维散点。
添加 2016-01-09
感谢@Praveen 的回答。
我有另一种使用 scipy interpolate 2d 函数的方法。
这是我的代码:
xi = np.linspace(x_map1,x_map2,pop.shape[1])
yi = np.linspace(y_map1,y_map2,pop.shape[0])
hfunc = interpolate.interp2d(xi,yi,pop)
x_grid = np.linspace(x_map1,x_map2,new_shape_x)
y_grid = np.linspace(y_map1,y_map2,new_shape_y)
new_pop = np.zeros(new_shape_x * new_shape_y)
t = 0
for i in range(0,new_shape_y,1):
for j in range(0,new_shape_y,1):
new_pop[t] = hfunc(x_grid[j],y_grid[i])
t+=1
new_pop = new_pop.reshape(new_shape_y,new_shape_x)
plt.pcolormesh(new_pop)
结果如下:
http://i4.tietuku.com/b020db6dc2d75d70.png
- 当我使用插值来粗化数据时是否存在一些问题?
加2
是否有一些有用的函数可以让我按位置(x,y)从原始数组数据集中采样一些数据?
最佳答案
如果我对您的理解是正确的,您有一个非常精细的人口密度 map ,您正试图通过聚合每个 5x5 像素区域内的人口密度来使其变得粗糙。是吗?
因此,当您说要将 1km x 1km 变成 5km x 5km 时,您的意思是每个像素当前代表 1km x 1km 区域内的人口,而您想让它代表人口在 5 公里 x 5 公里的区域内。
如果是这样,请不要使用聚类和 KD 树!这将是一种非常低效的方法来做一些简单得多的事情。
This可能是你想要的。解释一下:
# Suppose the 2D array is pop_density
coarseness = 5
temp = pop_density.reshape((pop_density.shape[0] // coarseness, coarseness,
pop_density.shape[1] // coarseness, coarseness))
coarse_pop_density = np.sum(temp, axis=(1,3))
如另一个答案所述,这仅在 pop_density
的形状是 coarseness
的精确倍数时才有效。我相信您就是这种情况,因为您说您有一张 200x150 的图像,您正试图将其粗糙化 5 倍。
对于不是粗糙度因子倍数的图像
# Suppose the size of pop_density was 198x147 instead of 200x150.
# Start by finding the next highest multiple of 5x5
shape = np.array(pop_density.shape, dtype=float)
new_shape = coarseness * np.ceil(shape / coarseness).astype(int)
# new_shape is now (200, 150)
# Create the zero-padded array and assign it with the old density
zp_pop_density = np.zeros(new_shape)
zp_pop_density[:shape[0], :shape[1]] = pop_density
# Now use the same method as before
temp = zp_pop_density.reshape((new_shape[0] // coarseness, coarseness,
new_shape[1] // coarseness, coarseness))
coarse_pop_density = np.sum(temp, axis=(1,3))
关于python - 如何粗化二维数组数据分辨率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34689519/