The issue is that your image is, as you said, greyscale, so on this line:
if pixels[i,j] == (225, 225, 225):
no pixel will ever equal the RGB triplet (255,255,255)
because the white pixels will be simply the greyscale vale 255
not an RGB triplet.
It works fine if you change your loop to:
if pixels[i,j] == 29:
pixels[i,j] = 1
elif pixels[i,j] == 179:
pixels [i,j] = 2
else:
pixels[i,j] = 0
Here is the contrast-stretched result:
You may like to consider doing the conversion using a "Look Up Table", or LUT, as large numbers of if
statements can get unwieldy. Basically, each pixel in the image is replaced with a new one found by looking up its current index in the table. I am doing it with numpy
for fun too:
#!/usr/local/bin/python3
import numpy as np
from PIL import Image
# Open the input image
PILimage=Image.open("classified.png")
# Use numpy to convert the PIL image into a numpy array
npImage=np.array(PILimage)
# Make a LUT (Look-Up Table) to translate image values. Default output value is zero.
LUT=np.zeros(256,dtype=np.uint8)
LUT[29]=1 # all pixels with value 29, will become 1
LUT[179]=2 # all pixels with value 179, will become 2
# Transform pixels according to LUT - this line does all the work
pixels=LUT[npImage];
# Save resulting image
result=Image.fromarray(pixels)
result.save('result.png')
Result - after stretching contrast:
I am maybe being a bit verbose above, so if you like more terse code:
import numpy as np
from PIL import Image
# Open the input image as numpy array
npImage=np.array(Image.open("classified.png"))
# Make a LUT (Look-Up Table) to translate image values
LUT=np.zeros(256,dtype=np.uint8)
LUT[29]=1 # all pixels with value 29, will become 1
LUT[179]=2 # all pixels with value 179, will become 2
# Apply LUT and save resulting image
Image.fromarray(LUT[npImage]).save('result.png')