[DIY] Remove Backgound of Portrait Photo

This blog introduces tools used to remove background of portrait photos. Required tools are listed below:

  • Rembg: remove background by using u2net model
  • MacOS Preview: polish photos from Rembg and crop photos
  • A simple Python script: change the background from transparent to any color (e.g, white).

Rembg

You could follow instructions on Github to install Rembg. Note that I fail to install Rembg on my MacBook Pro with M1 chip. I suggest to install Rembg on a Linux machine.

Once you complete the installation, you could easily remove background by Rembg. To avoid redundant jump between websites, I copy the example commands of Rembg to here.

Usage as a cli

Remove the background from a remote image

1
curl -s http://input.png | rembg > output.png

Remove the background from a local file

1
rembg -o path/to/output.png path/to/input.png

Remove the background from all images in a folder

1
rembg -p path/to/input path/to/output

MacOS Preview

You could use “Instant Alpha” button to polish your photo.

Python Script for Setting Background Color

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from PIL import Image

INPUT_FILE = 'test.png'
OUTPUT_FILE = "img2.png"
BG_COLOR = (255, 255, 255, 255) # (R, G, B, A)

img = Image.open(INPUT_FILE)
img = img.convert("RGBA")
datas = img.getdata()

newData = []
for item in datas:
if item == (0, 0, 0, 0):
newData.append(BG_COLOR)
else:
newData.append(item)

img.putdata(newData)
img.save(OUTPUT_FILE, "PNG")

Recommended Posts