["python","image","numpy","python-imaging-library","numpy-ndarray"]
How do I convert a PIL Image into a NumPy array?

How do I convert a PIL Image back and forth to a NumPy array so that I can do faster pixel-wise transformations than PIL's PixelAccess allows? I can convert it to a NumPy array via: pic = Image.open("foo.jpg") pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3) But how do I load it back into the PIL Image after I've modified the array? pic.putdata() isn't working well.
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).