Remove background colour from image using Python/PIL

20,275

Use np.all() compare along the third axis.

import numpy as np
from PIL import Image

im = Image.open('my_file.tif')
im = im.convert('RGBA')
data = np.array(im)
# just use the rgb values for comparison
rgb = data[:,:,:3]
color = [246, 213, 139]   # Original value
black = [0,0,0, 255]
white = [255,255,255,255]
mask = np.all(rgb == color, axis = -1)
# change all pixels that match color to white
data[mask] = white

# change all pixels that don't match color to black
##data[np.logical_not(mask)] = black
new_im = Image.fromarray(data)
new_im.save('new_file.tif')
Share:
20,275
hansolo
Author by

hansolo

Updated on February 20, 2020

Comments

  • hansolo
    hansolo about 4 years

    I've been trying to get this to work and am really having trouble, so would be very grateful for some help.

    Using the code below, I want to change the features with the specified RGB values to white, and all the other features in the image black (i.e. basically extracting the features from the image. Unfortunately, although I can make the features I want to 'extract' fine, when I try to remove the background colours (I'd been trying to use

    mask2 = ((red != r1) & (green != g1) & (blue != b1))
    data[:,:,:4][mask2] = [rb, gb, bb, ab]
    

    but that seems to select any pixels except those with red == r1 OR green == g1 etc, leaving me with a background image that is quite 'noisy'.) Does anyone know a way to literally extract those pixels with the specified RGB values, or a better way to recolour the background pixels?

    Thanks

    import numpy as np
    from PIL import Image
    
    im = Image.open('/home/me/nh09sw.tif')
    im = im.convert('RGBA')
    data = np.array(im)
    
    r1, g1, b1 = 246, 213, 139 # Original value
    rw, gw, bw, aw = 255, 255, 255, 255 # Value that we want to replace features with
    rb, gb, bb, ab = 0, 0, 0, 255 #value we want to use as background colour
    
    red, green, blue, alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3]
    
    mask = ((red == r1) & (green == g1) & (blue == b1))
    data[:,:,:4][mask] = [rw, gw, bw, aw]
    
    im = Image.fromarray(data)
    
    im.save('/home/me/nh09sw_recol.tif')