gpt4 book ai didi

python - 尝试使用噪声、numpy 和 Image 创建噪声图像

转载 作者:太空宇宙 更新时间:2023-11-03 17:08:54 24 4
gpt4 key购买 nike

我正在尝试在 python 中创建一些柏林噪声图像,但遇到了一些问题。当我运行我的小脚本时出现异常。我显然不了解 Image 模块的使用,因为我尝试的所有操作都会导致 ValueError 异常,并显示消息“缓冲区不够大”

这是我到目前为止所得到的:

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')

我遇到的异常是:

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

最佳答案

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

如下所示,给定这些数组:

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'图像:

im = Image.fromarray(arr1, 'L')  # OK
im = Image.fromarray(arr2, 'L') # ValueError: Too many dimensions.

创建没有 Alpha channel 的彩色图像'RGB':

im = Image.fromarray(arr1, 'RGB')  # ValueError: not enough image data
im = Image.fromarray(arr2, 'RGB') # OK

请注意RGB模式的使用,因为您可能不关心Alpha channel ,否则只需将其他维度添加到numpy.zeros构造函数即可。

<小时/>

您可以将代码重写为,

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')

生成灰度图像。

关于python - 尝试使用噪声、numpy 和 Image 创建噪声图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com