首页 > 解决方案 > pygame表面中的numpy数组中除红色、绿色和蓝色之外的不同颜色

问题描述

我正在寻找柏林噪音,因为它对我很感兴趣。

作为在地形生成中了解 perlin 的一种方式,我正在尝试修改以下代码以显示我必须为不同值(0 到 1 之间)显示不同颜色的 numpy 数组。但是,我无法获得我发现使用超过三种颜色或三种 RGB 颜色中每种颜色的不同色调的代码。

我在互联网上尝试了很多东西并查看了文档,但我无法理解它。

def display_map(noise):  # NOTE: I expect noise to be a 2-d np.ndarray
''' Return a surface with terrain mapped onto it. '''

CHANNELS = 3  # use 4 for alpha, I guess
RED = 0
GREEN = 1
BLUE = 2
WATER_LEVEL = 0.20
MOUNTAIN_LEVEL = 0.75

# NOTE: numpy automagically "vectorizes" things like this. 
# array times scalar means a[i,j] * scalar, for all i,j
shade = (noise * 255).astype(np.ubyte)

# NOTE: dstack "stacks" however-many 2d arrays along the "depth" axis
# producing a 3d array where each [i,j] is (X,X,X)
rgb = np.dstack([shade] * 3)

# NOTE: (WATER_LEVEL <= noise) produces a 2d boolean array, where 
# result[i,j] = (WATER_LEVEL <= noise[i,j]), kind of like the scalar
# multiply above. The '&' operator is overloaded for boolean 'and'.
# The upshot is that this assignment only happens where the boolean
# array is 'True'
rgb[(WATER_LEVEL <= noise) & (noise <= MOUNTAIN_LEVEL), GREEN] = 255
rgb[(noise < WATER_LEVEL), BLUE] = 255

# NOTE: pygame.surfarray was added mainly to talk to numpy, I believe.
surf = pygame.surfarray.make_surface(rgb)
return surf

我主要看的是倒数第二个“段落”。

如果不是解决方案,我将非常感谢任何建议,因为这对我来说是一个学习过程。

标签: python-3.x

解决方案


推荐阅读