Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing pixel color value in PIL

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]
like image 387
Kuppo Avatar asked Apr 07 '16 06:04

Kuppo


People also ask

How do I change the pixel color in Java?

Create a Color object bypassing the new RGB values as parameters. Get the pixel value from the color object using the getRGB() method of the Color class. Set the new pixel value to the image by passing the x and y positions along with the new pixel value to the setRGB() method.

Is PIL a RGB or BGR?

The library encourages adding support for newer formats in the library by creating new file decoders. The basic difference between OpenCV image and PIL image is OpenCV follows BGR color convention and PIL follows RGB color convention and the method of converting will be based on this difference.


2 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) 
like image 150
magni- Avatar answered Oct 13 '22 14:10

magni-


You could use img.putpixel:

im.putpixel((x, y), (255, 0, 0))
like image 43
Anno Avatar answered Oct 13 '22 16:10

Anno