Saving Python PILs in Index Mode

Asked 2 years ago, Updated 2 years ago, 112 views

I have a question about what to do when I read an index mode image in Python's image processing library PIL.
Read the png (index mode) image and change the pixel value as shown in the code below. Attempted to save in index mode again.
However, the output image was not colored and was black and white.
The color information is missing, but I don't know what's wrong.
Does anyone know?
I look forward to hearing from you.
Thank you for your cooperation.

 from PIL import Image
import numpy as np
import sys

origin=(0,1,4,4,5)
to=(2,4,3,4,2)

for ID in open(sys.argv[1]):
   ID = ID.strip()
   im = Image.open (ID + '.png')
   imnp=np.array(im)
   for(i,j)in zip(origin,to): 
       imnp[imnp==i] = j
   pil_img=Image.fromarray(np.uint8(imnp), mode="P")
   pil_img.save(ID+'_con.png', 'png')

python image pil

2022-09-30 13:58

1 Answers

Quote the answers to the similar question from an external site.

You will need to specify a palette to save in index color.
If you want to divert the palette of the original image, before saving it,

pil_img.putpalette(im.getpalette())

I think it would be good to add .

This post was posted as a similar question from an external site as community wiki.This post was posted as Community Wiki by quoting a similar question from an external site


2022-09-30 13:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.