5

I have an Image, I'd like to replace all the pixels of one color with those in a different color, what is the simplest way to go about that?

More or less I have an image in tkinter, and when a button is pressed I want the color to change.

rectangletangle
  • 46,943
  • 90
  • 196
  • 270
  • 1
    Possible duplicate: http://stackoverflow.com/questions/1616767/pil-best-way-to-replace-color – unutbu Jul 03 '10 at 00:31

2 Answers2

4

try this.

#!/usr/bin/python
from PIL import Image
import sys

img = Image.open(sys.argv[1])
img = img.convert("RGBA")

pixdata = img.load()

# Clean the background noise, if color != white, then set to black.

for y in xrange(img.size[1]):
    for x in xrange(img.size[0]):
        if pixdata[x, y] == (255, 255, 255, 255):
            pixdata[x, y] = (0, 0, 0, 255)

you can use color picker in gimp to absorb the color and see that's rgba color

Yuda Prawira
  • 11,005
  • 9
  • 45
  • 52
3

I think that the fastest way to do that is to use the Image.load() method. Something like this should work:

from PIL import Image
im = Image.open("image.jpg")
image_data = im.load()
# Here you have access to the RGB color of each pixel
# image_data[x,y] = (R,G,B)
Tarantula
  • 17,983
  • 12
  • 52
  • 71