1

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

2 Answers2

2

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')
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
-1

(I cannot comment, on the above post) Small correction on the above code: img.putpalette(p) (instead of setpalette)

mespinosa
  • 7
  • 2
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34627377) – Koedlt Jul 06 '23 at 04:24