Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a single color in PIL?

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.

like image 489
rectangletangle Avatar asked Jul 02 '10 22:07

rectangletangle


People also ask

How do you change the color of an image in Python?

Using the ImageColor module, we can also convert colors to RGB format(RGB tuple) as RGB is very convenient to perform different operations. To do this we will use ImageColor. getgrb() method. The ImageColor.


2 Answers

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

like image 76
Yuda Prawira Avatar answered Sep 22 '22 19:09

Yuda Prawira


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)
like image 30
Tarantula Avatar answered Sep 25 '22 19:09

Tarantula