如何将PIL图像转换为numpy数组? [英] How to convert a PIL Image into a numpy array?

查看:1488
本文介绍了如何将PIL图像转换为numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正忙着将PIL图像对象来回转换为numpy数组,因此我可以比PIL的 PixelAccess 对象更快地逐像素转换会允许的。我已经想出如何通过以下方式将像素信息放在一个有用的3D numpy数组中:

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)

但在完成所有令人敬畏的变换后,我似乎无法弄清楚如何将其加载回PIL对象。我知道 putdata() 方法,但似乎无法让它表现得好。

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.

推荐答案

你不是说 putdata()的表现如何。我假设你在做什么

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

这是因为 putdata 需要一系列元组,并且你给它一个numpy数组。这

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.

自PIL 1.1.6起,正确的方式在图像和numpy数组之间进行转换只是

As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply

>>> pix = numpy.array(pic)

虽然结果数组的格式与你的格式不同(3在这种情况下,-d数组或rows / columns / rgb。)

although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).

然后,在对数组进行更改后,您应该可以执行 pic.putdata(pix)或使用 Image.fromarray(pix)创建新图像。

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数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆