Changing pixel color value in PIL

Question:

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]
Asked By: Kuppo

||

Answers:

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)
Answered By: magni-

Here is the way I’d use PIL to do what you want:

from PIL import Image

imagePath = 'A:ex1.jpg'
newImagePath = 'A:ex2.jpg'
im = Image.open(imagePath)

def redOrBlack (im):
    newimdata = []
    redcolor = (255,0,0)
    blackcolor = (0,0,0)
    for color in im.getdata():
        if color == redcolor:
            newimdata.append( redcolor )
        else:
            newimdata.append( blackcolor )
    newim = Image.new(im.mode,im.size)
    newim.putdata(newimdata)
    return newim

redOrBlack(im).save(newImagePath)
Answered By: loxaxs

Taking the question to an extreme level, here’s how to randomly change the channels in PIL (neglecting any 0, which I consider as background)

rr, gg, bb = in_img.split()
rr = rr.point(lambda p: 0 if p==0 else np.random.randint(256) )
gg = gg.point(lambda p: 0 if p==0 else np.random.randint(256) )
bb = bb.point(lambda p: 0 if p==0 else np.random.randint(256) )
out_img = Image.merge("RGB", (rr, gg, bb))
out_img.getextrema()
out_img.show()

Enjoy!

Answered By: innuendo

You could use img.putpixel:

im.putpixel((x, y), (255, 0, 0))
Answered By: Anno
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.