People photo background removal

FREEMIUM
Popularity

8.4 / 10

Latency

288ms

Service Level

100%

Health Check

100%

Back to All Tutorials (2)

Replace background with People Background Removal API

When presenting a series of photos featuring people, changing the background can enhance consistency and professionalism. The People Background Removal API specializes in removing backgrounds from peopleโ€™s photos. By using the API, background removal becomes effortless, allowing for further customization of images. In this scenario, the API replaces the original background with a new one, revitalizing the imageโ€™s overall appeal.

Python implementation

Install required Python packages before start: pip install requests Pillow

Removing background

Background will be removed using the People Background Removal API. Just send an image to the API, and you will receive the image without the background in response.

def remove_bg(img: Path, api_key: str) -> Image.Image:
    """Remove background from original image."""
    # We strongly recommend you use exponential retries.
    error_statuses = (408, 409, 429, 500, 502, 503, 504)
    s = requests.Session()
    retries = Retry(backoff_factor=1.5, status_forcelist=error_statuses)
    s.mount('https://', HTTPAdapter(max_retries=retries))

    url = f'{API_URL}/v1/results'
    with img.open('rb') as f:
        api_res = s.post(url, files={'image': f},
                         headers={'X-RapidAPI-Key': api_key}, timeout=20)

    # Handle processing failure.
    if (api_res.status_code != 200 or
            api_res.json()['results'][0]['status']['code'] == 'failure'):
        print('Image processing failed.')
        sys.exit(1)

    api_res_json = api_res.json()

    res_img = api_res_json['results'][0]['entities'][0]['image']
    return Image.open(io.BytesIO(b64decode(res_img)))

Adding new background

Pillow package will help add new background. In this code, we assume that background size is the same to the image size or the image will be inserted to the top-left corner of background.

def add_background(img: Image.Image, bg: Image.Image) -> Image.Image:
    """Add custom background to image."""
    res_img = bg.crop((0, 0) + img.size)
    res_img.paste(img, mask=img.split()[3])
    return res_img

Parse command line arguments

Parse command line arguments using argparse.

def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument('--api-key', help='Rapid API token.', required=True)  # Get your token at https://rapidapi.com/api4ai-api4ai-default/api/people-photo-background-removal/pricing
    parser.add_argument('--orig-image', type=Path,
                        help='Path to an image.', required=True)
    parser.add_argument('--background', type=Path,
                        help='Path to a new background.')
    return parser.parse_args()

Main function

Change the background using the aforementioned functions and save the new image.

def main():
    """
    Script entry function.

    Image will be saved in working directory.
    """
    args = parse_args()
    im = remove_bg(args.orig_image, args.api_key)
    with open('res.png', 'wb') as f:
        add_background(im, Image.open(args.background)).save(f)

Python code

"""
Change background in specified image.

Run script:
`python3 main.py --api-key <RAPID_API_KEY> --orig-image <PATH_TO_IMAGE> --background <PATH_TO_BACKGROUND_IMAGE>`
"""

import argparse
import io
import sys
from base64 import b64decode
from PIL import Image
from pathlib import Path

import requests
from requests.adapters import Retry, HTTPAdapter

API_URL = 'https://background-removal4.p.rapidapi.com'


def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument('--api-key', help='Rapid API token.', required=True)  # Get your token at https://rapidapi.com/api4ai-api4ai-default/api/people-photo-background-removal/pricing
    parser.add_argument('--orig-image', type=Path,
                        help='Path to an image.', required=True)
    parser.add_argument('--background', type=Path,
                        help='Path to a new background.')
    return parser.parse_args()


def remove_bg(img: Path, api_key: str) -> Image.Image:
    """Remove background from original image."""
    # We strongly recommend you use exponential retries.
    error_statuses = (408, 409, 429, 500, 502, 503, 504)
    s = requests.Session()
    retries = Retry(backoff_factor=1.5, status_forcelist=error_statuses)
    s.mount('https://', HTTPAdapter(max_retries=retries))

    url = f'{API_URL}/v1/results'
    with img.open('rb') as f:
        api_res = s.post(url, files={'image': f},
                         headers={'X-RapidAPI-Key': api_key}, timeout=20)

    # Handle processing failure.
    if (api_res.status_code != 200 or
            api_res.json()['results'][0]['status']['code'] == 'failure'):
        print(api_res.json())
        print('Image processing failed.')
        sys.exit(1)

    api_res_json = api_res.json()

    res_img = api_res_json['results'][0]['entities'][0]['image']
    return Image.open(io.BytesIO(b64decode(res_img)))


def add_background(img: Image.Image, bg: Image.Image) -> Image.Image:
    """Add custom background to image."""
    res_img = bg.crop((0, 0) + img.size)
    res_img.paste(img, mask=img.split()[3])
    return res_img


def main():
    """
    Script entry function.

    Image will be saved in working directory.
    """
    args = parse_args()
    im = remove_bg(args.orig_image, args.api_key)
    with open('res.png', 'wb') as f:
        add_background(im, Image.open(args.background)).save(f)


if __name__ == '__main__':
    main()

Time to test

Letโ€™s try the script!

We have an image that we want to change the background for:

And the background we want to use:

Put these images to the same folder with main.py and run the script:
python main.py --api-key <RAPID-API-TOKEN> --orig-image pccase.jpg --background stripes.png

And now we have the result:

Conclusion

Changing backgrounds becomes incredibly easy with the People Background Removal API. This tool offers a wide range of benefits for removing backgrounds from images. It simplifies work for photographers and designers while making e-commerce product images look better. This API is a must-have for working with digital content.

Notably, the People Background Removal API is user-friendly and excels at accurately separating subjects from their backgrounds. It uses advanced technology to distinguish between objects and backgrounds, preserving details and contours seamlessly.