Background Removal

FREEMIUM
Verified
Por API 4 AI | Atualizado vor 17 Tagen | Visual Recognition
Popularidade

9.6 / 10

Latência

7,107ms

Nível de serviço

100%

Health Check

N/A

Voltar para todos os tutoriais (2)

Replace background with Background Removal API

When you want a group of photos to look consistent and professional together, changing the background can really help. The Background Removal API makes it easy to take out the background from images. After that, you can edit the image the way you want.

In this case, the API swaps out the old background for a new one, giving your image a whole new look.

Python implementation

Install required Python packages before start: pip install requests Pillow

Removing background

Background will be removed using the 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/background-removal4/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/background-removal4/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

The Background Removal API makes changing backgrounds incredibly easy and convenient. By using this API, you unlock a host of benefits and solutions for various background removal challenges. It simplifies the editing process for photographers and designers, enhances e-commerce product images, and more. This API is an essential tool for digital content manipulation.

In addition to being user-friendly, the Background Removal API offers exceptional accuracy. Its advanced algorithms and deep learning techniques can accurately distinguish between subjects and backgrounds, preserving intricate details and contours.