![]() |
Change color pixel in an image - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Change color pixel in an image (/thread-9148.html) |
Change color pixel in an image - louloudevinci - Mar-23-2018 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^ RE: Change color pixel in an image - nilamo - Mar-23-2018 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#tag-Image.Image.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() RE: Change color pixel in an image - louloudevinci - Mar-25-2018 Wooo, thanks for all this help ! It's really cool ! |