简体   繁体   中英

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.

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM