Search code examples
pythonnumpymachine-learningpython-imaging-library

PIL: fromarray gives a wrong object in P mode


I want to load an image in P mode, transform it into np.array and then transform it back, but I got a wrong Image object which is a gray image, not a color one

label = PIL.Image.open(dir).convert('P')
label = np.asarray(label)
img = PIL.Image.fromarray(label, mode='P')
img.save('test.png')

dir is the path of the original picture; test.png is a gray picture


Solution

  • Images in 'P' mode require a palette that associates each color index with an actual RGB color. Converting the image to an array loses the palette, you must restore it again.

    label = PIL.Image.open(dir).convert('P')
    p = label.getpalette()
    label = np.asarray(label)
    img = PIL.Image.fromarray(label, mode='P')
    img.setpalette(p)
    img.save('test.png')