我正在跟踪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()
问题是
PIL.Image.fromarray
期望它的参数是一个整数值数组,但是Numpy默认创建浮点值数组。因此您的color_world
数组包含浮点值,因此您的图像被损坏。垂直分带是因为这些浮点值的二进制表示形式相似要修复此问题,请使用Numpy数组的
astype
方法强制Image.fromarray
参数为uint8
数组,因为这是R、G和B组件的适当大小。而不是:执行:
或者,从一开始就创建
color_world
作为uint8
数组。为此,请更改:收件人:
这可能会稍微更有效率
相关问题 更多 >
编程相关推荐