首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试用噪声、噪声和图像创建噪声图像

尝试用噪声、噪声和图像创建噪声图像
EN

Stack Overflow用户
提问于 2015-12-17 01:01:21
回答 1查看 5.4K关注 0票数 3

我试图在python中创建一些perlin噪声图像,并遇到了一些问题。当我运行我的小脚本时,我得到了一个例外。显然,我并没有掌握图像模块的使用情况,因为我所尝试的每一件事都会导致出现带有“缓冲区不够大”的ValueError异常。

到目前为止,我得到的是:

代码语言:javascript
复制
import numpy
from noise import pnoise2, snoise2
import Image


octaves = 1
freq = 16.0 * octaves
y_max = 5
x_max = 5
imarray = [[0 for x in range(y_max)] for x in range(x_max)]
totalcount = 0

for y in range(y_max):
    for x in range(x_max):
        val = "%s\n" % int(snoise2(x / freq, y / freq, octaves) * 127.0 + 128.0)
        imarray[y][x] = val
        totalcount += 1

arr = numpy.asarray(imarray).astype('uint8')

im = Image.fromarray(arr, 'RGBA')
im.save('./blah.png')

我得到的例外是:

代码语言:javascript
复制
Connected to pydev debugger (build 143.1184)
Traceback (most recent call last):
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 2407, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1798, in run
    launch(file, globals, locals)  # execute the script
  File "/Users/u4234/source/systools/load/noise_test.py", line 26, in <module>
    im = Image.fromarray(arr, 'RGBA')
  File "/Users/u4234/Library/Python/2.7/lib/python/site-packages/PIL-1.1.7-py2.7-macosx-10.10-x86_64.egg/Image.py", line 1902, in fromarray
    return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
  File "/Users/u4234/Library/Python/2.7/lib/python/site-packages/PIL-1.1.7-py2.7-macosx-10.10-x86_64.egg/Image.py", line 1853, in frombuffer
    core.map_buffer(data, size, decoder_name, None, 0, args)
ValueError: buffer is not large enough

Process finished with exit code 1
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-18 01:28:20

问题是,您要求PIL创建一个新的'RGBA'映像,它需要4个通道,但是您只传递一个二维数组,例如一个通道。

如下所示,考虑到这些数组:

代码语言:javascript
复制
arr1 = numpy.zeros((5, 5), dtype=numpy.uint8)  # A single 5x5 channel
arr2 = numpy.zeros((5, 5, 3), dtype=numpy.uint8)  # 3 5x5 channels

创建一个灰度'L'图像:

代码语言:javascript
复制
im = Image.fromarray(arr1, 'L')  # OK
im = Image.fromarray(arr2, 'L')  # ValueError: Too many dimensions.

创建没有alpha通道'RGB'的彩色图像

代码语言:javascript
复制
im = Image.fromarray(arr1, 'RGB')  # ValueError: not enough image data
im = Image.fromarray(arr2, 'RGB')  # OK

注意RGB模式的使用,因为您可能并不关心alpha通道,否则只需向numpy.zeros构造函数添加其他维度。

你可以重写你的代码

代码语言:javascript
复制
arr = numpy.zeros((5, 5, 1), dtype=numpy.uint8)

y_max, x_max, channels = arr.shape

for y in range(y_max):
    for x in range(x_max):
        val = int(snoise2(x / freq, y / freq, octaves) * 127.0 + 128.0)
        arr[y,x,0] = val

im = Image.fromarray(arr, 'L')
im.save('./blah.png')

生成灰度图像。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34324958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档