Using withoutbg API with Python

Author: Imran Kocabiyik

Image without background

Remove Image Background

Let's use the below photo as an example.

Image

To remove the background, you can send a POST request as follows:

import requests
import io
from PIL import Image

API_KEY = 'your API key here'

headers = {
    'accept': 'application/json',
    'X-API-Key': API_KEY,
}

files = {
    'file': open('vegetables.jpg', 'rb'),
}

response = requests.post('https://api.withoutbg.com/v1.0/image-without-background', headers=headers, files=files)

image = Image.open(io.BytesIO(response.content))
image.show()

The output will be a PNG image without background:

Image Without Background

Image with White Background

If you want an image with solid white background, you can use another endpoint. An example:

import requests
import io
from PIL import Image

API_KEY = 'your API key here'

headers = {
    'accept': 'application/json',
    'X-API-Key': API_KEY,
}

files = {
    'file': open('vegetables.jpg', 'rb'),
}

response = requests.post('https://api.withoutbg.com/v1.0/image-with-white-background', headers=headers, files=files)

image = Image.open(io.BytesIO(response.content))
image.show()

Image with White Background

Replacing the Image Background

If you want to add another background to the image you received, you can apply it as follows:

# ...
image_withoutbg = Image.open(io.BytesIO(response.content))
your_background_photo = Image.open('/path/to/file.jpg').convert('RGBA').resize(image_withoutbg.size)
your_background_photo.paste(image_withoutbg, (0,0), image_withoutbg)
image_background_replaced = your_background_photo.convert('RGB')
image_background_replaced.show()

Background Replaced

Happy building!