Numpy阵列的元组到PIL图像

问题描述 投票:0回答:1

我目前有一个numpy数组或RBG元组,我想转换为PIL图像并保存。目前我正在做以下事情:final = Image.fromarray(im_arr, mode='RGB')。这里im_arr(R, G, B)形式的numpy元组。它似乎最终会在创建图像时将元组分开,如下所示。

enter image description here

python arrays image numpy python-imaging-library
1个回答
0
投票

尝试使用这些功能:

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()

图片来源:http://code.activestate.com/recipes/577591-conversion-of-pil-image-and-numpy-array/

附加信息:http://www.imagexd.org/tutorial/lessons/0_images_are_arrays.html

如果它不起作用,可能您的阵列没有适当的形状。

© www.soinside.com 2019 - 2024. All rights reserved.