2

There are custom libraries in python that you can use to remove the background in images.

An example is the rembg library used below:

from rembg import remove
from PIL import Image

input_path = 'input.png'
output_path = 'output.png'

input = Image.open(input_path)
output = remove(input)
output.save(output_path)

My project is to compare the background of the images.

Is it possible to save the removed background as png too?

Mikee
  • 783
  • 1
  • 6
  • 18

1 Answers1

1

The background is marked as zeros in the alpha (transparency channel) of output image.

We may extract the alpha channel, negate it (255 - alpha), and scale the input by the negated alpha.
We may have to divide by 255 for bringing alpha to range [0, 1] before scaling.


Code sample:

from rembg import remove
from PIL import Image
import numpy as np

input_path = 'animal-2.jpg'
output_path = 'output.png'
background_path = 'background.png'

input = Image.open(input_path)
output = remove(input)

input_rgb = np.array(input)[:, :, 0:3]  # Convert PIL to NumPy (keep only RGB channels).
outout_rgba = np.array(output)  # Convert PIL to NumPy.
alpha = outout_rgba[:, :, 3]  # Extract alpha channel.
alpha3 = np.dstack((alpha, alpha, alpha))  # Convert to 3 channels

background_rgb = input_rgb.astype(np.float) * (1 - alpha3.astype(np.float)/255)  # Multiply by 1-alpha
background_rgb = background_rgb.astype(np.uint8)  # Convert back to uint8

background = Image.fromarray(background_rgb)

output.save(output_path)
background.save(background_path)

Input:
enter image description here

Output:
enter image description here

Negated alpha:
enter image description here


Note:
The above solution assumes that there may be some alpha values between 0 and 255 (some semi-transparent background pixels), and my be simplified if assumed there are only 0 and 255 values.

Rotem
  • 30,366
  • 4
  • 32
  • 65