Using withoutbg API with Python
Author: Imran Kocabiyik
Table of Contents

Remove Image Background
Let's use the below photo as an example.
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 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()
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()
Happy building!