4

I'm very new to programming, and I am learning more about image processing using PIL.

I have a certain task that requires me to change every specific pixel's color with another color. Since there are more than few pixels I'm required to change, I've created a for loop to access to every pixel. The script "works" at least, however the result is just a black screen with (0, 0, 0) color in each pixel.

from PIL import Image
img = Image.open('/home/usr/convertimage.png')
pixels = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
            if pixels[i,j] == (225, 225, 225):
                pixels[i,j] = (1)
            elif pixels[i,j] == (76, 76, 76):
                pixels [i,j] = (2)
            else: pixels[i,j] = (0)
img.save('example.png')

The image I have is a grayscale image. There are specific colors, and there are gradient colors near the borders. I'm trying to replace each specific color with another color, and then replace the gradient colors with another color.

However for the life of me, I don't understand why my output comes out with a single (0, 0, 0) color at all.

I tried to look for an answer online and friends, but couldn't come up with a solution.

If anyone out there knows what I'm doing wrong, any feedback is highly appreciated. Thanks in advance.

2
  • There seems to be some confusion here - you say your image is greyscale but has specific colours and gradients. It can't be both colour and greyscale at the same time. Maybe share your image? Commented May 29, 2018 at 9:37
  • imgur.com/OpL3xmK This is the original image I have. There are 3 basic colors (or should be) which are yellow, red, and white. imgur.com/WlD1yDg This is the result of the image I converted greyscale to. It has tones such as (225, 225, 225) for each class. imgur.com/XEWw7HM This is the type I want to convert my image to. Each specific class has to have a different color such as a car having a color of (2, 2 ,2) in this case. Commented May 30, 2018 at 5:19

1 Answer 1

5

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:

enter image description here


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:

enter image description here


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')
Sign up to request clarification or add additional context in comments.

1 Comment

I see how I did wrong. Thanks for showing my error! Much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.