Python:Noise RGB 2d阵列产生颜色的列

问题描述 投票:0回答:1

我正在关注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

python python-3.x python-imaging-library noise perlin-noise
1个回答
0
投票

问题在于,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")

这可能会更有效率。

© www.soinside.com 2019 - 2024. All rights reserved.