Python:Noise RGB 2d数组生成colou列

2024-05-19 13:08:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在跟踪this tutorial,必须更新它以使用PIL的Image.fromarray,而不是scipy的toimage。当我运行这个代码(一个小的64^2而不是一个完整的1024^2)时,输出似乎有连续的颜色列。即使在第一个代码集中,我应该得到一个漂亮的黑白斑点,它看起来像一列重复的静态立方体。 为什么会这样

import noise
import numpy as np
from PIL import Image

shape       = (64,64)
scale       = 100.0
octaves     = 6
persistence = 0.5
lacunarity  = 2.0

world = np.zeros(shape)
for i in range(shape[0]):
    for j in range(shape[1]):
        world[i][j] = noise.pnoise2(j/scale, 
                                    i/scale, 
                                    octaves     = octaves, 
                                    persistence = persistence, 
                                    lacunarity  = lacunarity, 
                                    repeatx     = 1024, 
                                    repeaty     = 1024, 
                                    base        = 0)


blue = [65,105,225]
green = [34,139,34]
beach = [238, 214, 175]

def add_color(arr):
    color_world = np.zeros(arr.shape+(3,))
    for i in range(shape[0]):
        for j in range(shape[1]):
            if arr[i][j] < -0.05:
                color_world[i][j] = blue
            elif arr[i][j] < 0:
                color_world[i][j] = beach
            elif arr[i][j] < 1.0:
                color_world[i][j] = green

    return color_world

color_world = add_color(world)

im = Image.fromarray(color_world, "RGB")
im.show()

RGB 2D Perlin Noise Array


Tags: inimageimportforworldpilnprange
1条回答
网友
1楼 · 发布于 2024-05-19 13:08:27

问题是PIL.Image.fromarray期望它的参数是一个整数值数组,但是Numpy默认创建浮点值数组。因此您的color_world数组包含浮点值,因此您的图像被损坏。垂直分带是因为这些浮点值的二进制表示形式相似

要修复此问题,请使用Numpy数组的astype方法强制Image.fromarray参数为uint8数组,因为这是R、G和B组件的适当大小。而不是:

im = Image.fromarray(color_world, "RGB")

执行:

im = Image.fromarray(color_world.astype("uint8"), "RGB")

或者,从一开始就创建color_world作为uint8数组。为此,请更改:

    color_world = np.zeros(arr.shape+(3,))

收件人:

    color_world = np.zeros(arr.shape+(3,), dtype="uint8")

这可能会稍微更有效率

相关问题 更多 >