Python Forum
Change color pixel in an image
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Change color pixel in an image
#1
Hey!
I have a basic image, in color.
I would like to change every color by another color.
I know the functions putpixel, et caetera.
My problem, it is that I do not know how to separate, to indicate every "zone" of color.
For example: transform all the green pixels into another color, all the red in an other one, et caetera.
Anybody would have an edvice to give me?
Thank you in advance ^u^
Reply
#2
For future reference, it wasn't immediately obvious you were talking about PIL. The packages you're using are useful things to share :p

The pythonware doc has a note that putpixel() is known to be slow, and if you want to modify large areas, you should call load() to get access to pixel data:
http://effbot.org/imagingbook/image.htm#...e.getpixel Wrote:Note that this method is rather slow; if you need to process larger parts of an image from Python, you can either use pixel access objects (see load), or the getdata method.

If you have specific colors you're changing, here's an example that does it using load():
https://stackoverflow.com/a/3766325 Wrote:
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)

If you have numpy installed, this looks like the best way:
https://stackoverflow.com/a/3753428 Wrote:
import Image
import numpy as np

im = Image.open('test.png')
im = im.convert('RGBA')

data = np.array(im)   # "data" is a height x width x 4 numpy array
red, green, blue, alpha = data.T # Temporarily unpack the bands for readability

# Replace white with red... (leaves alpha values alone...)
white_areas = (red == 255) & (blue == 255) & (green == 255)
data[..., :-1][white_areas.T] = (255, 0, 0) # Transpose back needed

im2 = Image.fromarray(data)
im2.show()
Reply
#3
Wooo, thanks for all this help ! It's really cool !
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to change the resolution of an image and save multiple plots. pianistseb 1 2,356 Dec-11-2018, 07:45 PM
Last Post: micseydel
  Button Press When Pixel Color Changes bak989 0 3,682 Apr-22-2018, 04:03 PM
Last Post: bak989
  change application image issac_n 7 16,162 Feb-22-2018, 03:03 PM
Last Post: issac_n
  Error while running python script to get pixel points from google static map image python_newbee 3 4,802 Sep-15-2017, 06:25 AM
Last Post: python_newbee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020