'Numpy array of tuples to PIL image

I currently have a numpy array or RBG tuples that I want to convert to a PIL image and save. Currently I'm doing the following: final = Image.fromarray(im_arr, mode='RGB'). Here im_arr is the numpy array of tuples in the form (R, G, B). It seems to end up keeping the tuples separate when it creates the image as shown below.

enter image description here



Solution 1:[1]

Try using these functions:

import numpy
import Image

def PIL2array(img):
    return numpy.array(img.getdata(),
                    numpy.uint8).reshape(img.size[1], img.size[0], 3)

def array2PIL(arr, size):
    mode = 'RGBA'
    arr = arr.reshape(arr.shape[0]*arr.shape[1], arr.shape[2])
    if len(arr[0]) == 3:
        arr = numpy.c_[arr, 255*numpy.ones((len(arr),1), numpy.uint8)]
    return Image.frombuffer(mode, size, arr.tostring(), 'raw', mode, 0, 1)

def main():
    img = loadImage('foo.jpg')
    arr = PIL2array(img)
    img2 = array2PIL(arr, img.size)
    img2.save('out.jpg')

if __name__ == '__main__':
    main()

Credit: http://code.activestate.com/recipes/577591-conversion-of-pil-image-and-numpy-array/

Additional Information: http://www.imagexd.org/tutorial/lessons/0_images_are_arrays.html

In case it doesn't work, maybe your array does not have the appropriate shape.

Solution 2:[2]

If your array is an array of form width, height and filled with tuples, this code converts it to an array of arrays, which can be read by Image.fromarray.

import numpy as np
from PIL import Image


arr = np.array(
    [
        [(178, 158, 165), (185, 196, 191), (207, 222, 226)],
        [(202, 184, 176), (68, 58, 66), (69, 57, 60)],
        [(194, 158, 179), (109, 119, 116), (70, 64, 57)]
    ]
)           # a small example array

shape = arr.shape
new_arr = np.empty((shape[0], shape[1], 3), dtype=np.uint8)
for y, row in enumerate(arr):
    for x, color in enumerate(row):
        new_arr[y, x] = np.array(color)

Image.fromarray(new_arr, "RGB").show()

This is probably slow for larger images compared to the other answer, but that one didn't work for me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonathan DEKHTIAR
Solution 2 Rik Mulder