【问题标题】:Python: Noise RGB 2d array produces columns of colourPython:噪声 RGB 2d 数组产生颜色列
【发布时间】:2019-10-12 05:26:33
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x python-imaging-library noise perlin-noise


    【解决方案1】:

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

    这可能会更有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2015-01-13
      • 2018-09-05
      • 2021-10-21
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      相关资源
      最近更新 更多