Ida*_*n.c 7 python numpy python-imaging-library
我有一个numpy.ndarray
数组,其中包含float32
. 图像尺寸应为 226×226。我试图用来PIL.Image
创建图像,但出现错误。我读了PIL.Image.fromarray
需要的对象和方式,以及浮法我要打电话fromarray
跟'F'
我试过。
这就是我试图做的:
from PIL import Image
img = Image.fromarray(slice56, mode='F')
#type(slice56) = <type 'numpy.ndarray'>
#slice56 = array([ 0., 0., 0., ..., 0., 0., 0.], dtype=float32)
Run Code Online (Sandbox Code Playgroud)
我收到这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1860, in fromarray
return frombuffer(mode, size, obj, "raw", mode, 0, 1)
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1805, in frombuffer
return apply(fromstring, (mode, size, data, decoder_name, args))
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1743, in fromstring
im = new(mode, size)
File "/usr/lib64/python2.6/site-packages/PIL/Image.py", line 1710, in new
return Image()._new(core.fill(mode, size, color))
TypeError: argument 2 must be sequence of length 2, not 1
Run Code Online (Sandbox Code Playgroud)
任何人都可以提出一个想法如何做到这一点?或者如何解决这个错误?
我同意 DavidG 的回答是从 numpy 数组绘制图像的快速解决方案。但是,如果您有充分的理由坚持使用PIL.Image
,那么最接近您已经完成的工作的方法是这样的:
from PIL import Image
import numpy as np
slice56 = np.random.random((226, 226))
# convert values to 0 - 255 int8 format
formatted = (slice56 * 255 / np.max(slice56)).astype('uint8')
img = Image.fromarray(formatted)
img.show()
Run Code Online (Sandbox Code Playgroud)
然后它会产生如下给定的随机数: