Skip to content Skip to sidebar Skip to footer

Change White Background To A Specifc Color

Hello I am trying to give a black and white photo a colored background, first I convert pixels to either white or black then I would like to replace the white with a specific color

Solution 1:

You really, really want to avoid for loops with PIL images, try to use Numpy and it will be easier to write and faster to run.

I would do it like this:

import numpy as np
from PIL import image

# Load image and ensure greyscale
im = Image.open('U6IhW.jpg').convert('L')

# Make Numpy version for fast, efficient access
npim = np.array(im)

# Make solid black RGB output image, same width and height but 3 channels (RGB)
res = np.zeros((npim.shape[0],npim.shape[1],3), dtype=np.uint8)

# Anywhere the grey image is >127, make result image new colour
res[npim>127] = [148,105,39]

# Convert back to PIL Image and save to disk
Image.fromarray(res).save('result.png')

enter image description here


You could equally use PIL's ImageOps.colorize() like this:

from PIL import Image, ImageOps

im = Image.open('U6IhW.jpg').convert('L')                                                                                                           

# Threshold to pure black and white
bw = im.point(lambda x: 0if x<128else255)                                                                                                        

# Colorize
result = ImageOps.colorize(bw, (0,0,0), (148,105,39))

Post a Comment for "Change White Background To A Specifc Color"