简体   繁体   English

NumPy 在二维数组中切片正方形

[英]NumPy slicing squares in 2D array

I want to create a heightfield map that consists of squares of random height.我想创建一个由随机高度的正方形组成的高度场 map。 Given an array of NxN, I want that every square of size MxM, where M<N, will be at the same random height, with the height sampled from a uniform distribution.给定一个 NxN 数组,我希望每个大小为 MxM(M<N)的正方形都处于相同的随机高度,高度从均匀分布中采样。 For example, if we have N = 6 and M = 2, we would have:例如,如果我们有 N = 6 和 M = 2,我们将有:

0.2, 0.2, 0.6, 0.6, 0.1, 0.1, 0.2, 0.2, 0.6, 0.6, 0.1, 0.1,
0.2, 0.2, 0.6, 0.6, 0.1, 0.1, 0.2, 0.2, 0.6, 0.6, 0.1, 0.1,
0.5, 0.5, 0.3, 0.3, 0.8, 0.8, 0.5, 0.5, 0.3, 0.3, 0.8, 0.8,
0.5, 0.5, 0.3, 0.3, 0.8, 0.8, 0.5, 0.5, 0.3, 0.3, 0.8, 0.8,
0.6, 0.6, 0.4, 0.4, 0.9, 0.9, 0.6, 0.6, 0.4, 0.4, 0.9, 0.9,
0.6, 0.6, 0.4, 0.4, 0.9, 0.9 0.6, 0.6, 0.4, 0.4, 0.9, 0.9

For now, I've come up with an inefficient way of doing it with 2 nested for loops.现在,我想出了一种使用 2 个嵌套 for 循环的低效方法。 I'm sure there must be an efficient and elegant way to do that with NumPy slicing.我敢肯定,NumPy 切片必须有一种高效而优雅的方法。

This solution using the repeat() method should work for N/M integer.这个使用 repeat() 方法的解决方案应该适用于 N/M integer。

import numpy as np

N = 6
M = 2

values = np.random.random( [N//M, N//M] )
y = values.repeat( M, axis=0 ).repeat( M, axis=1 )
print(y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM