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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With