Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change specific RGB color pixels to another color, in image file

I would like to change a single color with Python.

If a fast solution with PIL exists, I would prefer this solution.

At the moment, I use

convert -background black -opaque '#939393' MyImage.png MyImage.png
like image 527
Martin Thoma Avatar asked Jun 26 '11 10:06

Martin Thoma


People also ask

How can I change all pixels of one color to another color in a picture?

Start by going to Image > Adjustments > Replace Color. Tap in the image to select the color to replace — I always begin with the purest part of the color. Fuzziness sets the tolerance of the Replace Color mask. Set the hue you're changing to with the Hue, Saturation, and Lightness sliders.

How do you change pixel color?

Once your phone finishes rebooting, you will find the new colors in Settings –> Display –> Styles & Wallpaper. Select "Custom 1" and choose a font and icon style. When you get to colors, you will see the new set of colors you flashed.


2 Answers

If numpy is available on your machine, try doing something like:

import numpy as np
from PIL import Image

im = Image.open('fig1.png')
data = np.array(im)

r1, g1, b1 = 0, 0, 0 # Original value
r2, g2, b2 = 255, 255, 255 # Value that we want to replace it with

red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]

im = Image.fromarray(data)
im.save('fig1_modified.png')

It will use a bit (3x) more memory, but it should be considerably (~5x, but more for bigger images) faster.

Also note that the code above is slightly more complicated than it needs to be if you only have RGB (and not RGBA) images. However, this example will leave the alpha band alone, whereas a simpler version wouldn't have.

like image 70
Joe Kington Avatar answered Sep 19 '22 08:09

Joe Kington


This is a modification of Joe Kington's answer above. The following is how to do this if your image contains an alpha channel as well.

import numpy as np
import Image

im = Image.open('fig1.png')
im = im.convert('RGBA')
data = np.array(im)

r1, g1, b1 = 0, 0, 0 # Original value
r2, g2, b2, a2 = 255, 255, 255, 255 # Value that we want to replace it with

red, green, blue, alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:4][mask] = [r2, g2, b2, a2]

im = Image.fromarray(data)
im.save('fig1_modified.png')

It took me a long time to figure out how to get it to work. I hope that it helps someone else.

like image 30
hazzey Avatar answered Sep 22 '22 08:09

hazzey