Domanda

I'm saving, converting to grayscale, and opening an image in Python with PIL like this

Image.open(imgname).convert('L').save(imgname)

And I get a matrix with one number per pixel. My image is has 3 colors. 255 for white, 0 for black and 128 for gray.

Is there anyway that when I convert my image to grayscale I can have 0 for white, 1 for gray and 2 for black when I read this image?

È stato utile?

Soluzione

You could make a custom lut (lookup table) and apply it to the grayscale image with the point() method just before saving it. Gray levels in the image besides 0, 128, and 255 will remain unchanged. You could, of course, change that by initializing the table differently.

lut = range(256)  # initialize to an identity lut
lut[0]   = 2
lut[128] = 1
lut[255] = 0
Image.open(imgname).convert('L').point(lut).save(imgname)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top