Python Forum

Full Version: Python Pillow
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
For one of the tasks in my assignment, I have to highlighting a single colour in a black and white image. It says: In your program, any pixels which are not red should be made black and white by taking the average of the red, green, and blue channels.
I have tried making the blue and green channels grayscale and keeping the red channel the same but it still has a red tinge on the whole picture when I just want it on a certain item.
The starting image is:
[Image: HuuU86H]
And the end product should be:
İmage

The code I tried was:
from PIL import Image

file = input("File name: ")
img = Image.open(file)
red,green,blue = img.split()

for y in range(img.height):
  for x in range(img.width):
    r = red.getpixel((x,y))
    g = green.getpixel((x,y))
    b = blue.getpixel((x,y))
    total = (r+g+b)
    avg = int((total/3))
    green.putpixel((x,y),avg)
    blue.putpixel((x,y),avg)

    
new_image = Image.merge('RGB', (red, green, blue))
  
new_image.save("output.png")
The end product of that was:
[Image: KSvHC96]

If you know anything it will be great help.
Thanks.
Hello,
doesn't your end image look pretty much like the one that's expected? It does to me, after a quick glance...
Anyway, if you want to keep only the "very red" pixels red, and convert those with no or very small amount of red to grayscale, you can set a threshold for red channel and convert only pixels, which have red channel value below the threshold.