Cars image background removal

FREEMIUM
Verified
By API 4 AI | Updated hace 24 días | Video, Images
Popularity

9.5 / 10

Latency

6,865ms

Service Level

100%

Health Check

100%

Back to All Tutorials (3)

Replace background with Car Background Removal API

When you’re putting together a collection of car photos, changing the background can make them look more consistent and professional. The Car Background Removal API is a specialized tool for taking out the background from pictures with vehicles.

With this API, removing the background becomes easy. Then, you can edit the image as you like. It’s like giving the image a new background for a fresh look.

Python implementation

Install required Python packages before start: pip install requests Pillow

Removing background

Background will be removed using the Car 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/cars-image-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 the background on images with a person.

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://cars-image-background-removal.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/cars-image-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

The Car Background Removal API makes changing backgrounds incredibly easy and convenient. Using this API offers numerous benefits and solutions for various challenges related to background removal. It simplifies the work of photographers and designers and enhances the look of e-commerce product images. In the realm of digital content manipulation, this API is a must-have tool.

Moreover, the Car Background Removal API isn’t just user-friendly; it also excels in accuracy. With advanced algorithms and deep learning techniques, it can accurately separate subjects from their original backgrounds. This ensures that even intricate details and fine contours are preserved seamlessly.