Python – Changing pixel color value in PIL

pythonpython-imaging-library

I need to change pixel color of an image in python. Except for the pixel value (255, 0, 0) red I need to change every pixel color value into black (0, 0, 0). I tried the following code but it doesn't helped.

from PIL import Image
im = Image.open('A:\ex1.jpg')
for pixel in im.getdata():
    if pixel == (255,0,0):
        print "Red coloured pixel"
    else:
        pixel = [0, 0, 0]

Best Answer

See this wikibook: https://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels

Modifying that code to fit your problem:

pixels = img.load() # create the pixel map

for i in range(img.size[0]): # for every pixel:
    for j in range(img.size[1]):
        if pixels[i,j] != (255, 0, 0):
            # change to black if not red
            pixels[i,j] = (0, 0 ,0)
Related Topic