问题描述
好吧,我正在尝试将 PIL 图像对象来回转换为 numpy 数组,这样我就可以比 PIL 的 PixelAccess
对象允许的逐个像素转换更快.我已经想出了如何将像素信息放置在一个有用的 3D numpy 数组中:
pic = Image.open("foo.jpg")pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3)
但是在我完成所有很棒的转换之后,我似乎无法弄清楚如何将它加载回 PIL 对象.我知道 putdata()
方法,但似乎无法让它发挥作用.
您并不是在说明 putdata()
的行为究竟如何.我假设你在做
这是因为 putdata
需要一个元组序列,而您给它的是一个 numpy 数组.这个
会工作,但速度很慢.
从 PIL 1.1.6 开始,"正确" 在图像和 numpy 之间转换的方式数组很简单
>>>pix = numpy.array(图片)尽管结果数组的格式与您的格式不同(在这种情况下为 3 维数组或行/列/rgb).
然后,在对数组进行更改后,您应该能够执行 pic.putdata(pix)
或使用 Image.fromarray(pix).
Alright, I'm toying around with converting a PIL image object back and forth to a numpy array so I can do some faster pixel by pixel transformations than PIL's
PixelAccess
object would allow. I've figured out how to place the pixel information in a useful 3D numpy array by way of:
pic = Image.open("foo.jpg")
pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3)
But I can't seem to figure out how to load it back into the PIL object after I've done all my awesome transforms. I'm aware of the
putdata()
method, but can't quite seem to get it to behave.
解决方案
You're not saying how exactly
putdata()
is not behaving. I'm assuming you're doing
>>> pic.putdata(a)
Traceback (most recent call last):
File "...blablabla.../PIL/Image.py", line 1185, in putdata
self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple
This is because
putdata
expects a sequence of tuples and you're giving it a numpy array. This
>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)
will work but it is very slow.
As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply
>>> pix = numpy.array(pic)
although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).
Then, after you make your changes to the array, you should be able to do either
pic.putdata(pix)
or create a new image with Image.fromarray(pix)
.
这篇关于如何将 PIL 图像转换为 numpy 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!