Cars image background removal

FREEMIUM
Verified
By API 4 AI | Updated il y a 24 jours | Video, Images
Popularity

9.5 / 10

Latency

6,865ms

Service Level

100%

Health Check

100%

Back to All Tutorials (3)

Car image background removing Telegram bot

Introducing a specialized Telegram bot designed specifically for car dealerships, this innovative solution has the power to automate mundane tasks and free up valuable time for your employees. With a focus on enhancing your advertising activities on popular websites like cars.com, copart.com, or craigslits.org, this tutorial aims to revolutionize your approach to showcasing vehicles.

The Telegram bot’s core functionality revolves around optimizing car photographs to give them a professional edge, infused with your brand’s unique style. Let’s delve into its key features:

Background Removal: The bot leverages advanced algorithms to seamlessly remove the background from car photographs. By eliminating any distracting elements and clutter, the focus remains solely on the vehicle itself. This creates a clean and visually appealing image that instantly captures the viewer’s attention.

Personalized Background: In addition to background removal, the bot allows you to incorporate a personalized background into your car photographs. You can choose from a selection of pre-designed backgrounds that align with your brand’s aesthetic or provide your own custom backgrounds. This customization adds a distinctive touch to your images, making them instantly recognizable and reinforcing your brand identity.

Logo Integration: Branding plays a vital role in establishing trust and recognition. The Telegram bot offers a seamless feature to affix your car dealership’s logo onto the edited images. By strategically placing your logo, such as in a corner or at the bottom, you create a consistent brand presence across all your advertisements. This strengthens brand recognition and instills confidence in potential buyers, as they associate the high-quality images with your dealership’s reputation.

By incorporating this Telegram bot into your advertising workflow, you can transform your car photographs into captivating visuals that reflect your brand’s style. Whether you represent a car dealership, sell vehicles on an auction platform, or simply place advertisements on commercial websites, this solution is designed to optimize your approach.

If you’re still unsure about how to differentiate between good and bad ad photos, take a look at the examples provided below. These illustrations will help you understand the key characteristics that define effective and ineffective advertising visuals. By studying these examples, you can gain valuable insights to improve the quality and impact of your own ad photos. Let’s explore them together:

Nice Bad

Not everyone has the luxury of possessing professional photography skills or access to high-end software.
Frequently, time constraints or technical limitations can hinder the quality of car photos, resulting in subpar visual representation.
In this tutorial, you’ll learn how to make a Telegram chatbot that is designed to overcome these challenges, allowing you to produce attractive car images without the need for extensive photography knowledge or specialized software.
A smartphone is all you need, as the chatbot will handle the remainder, ensuring your photos attain the desired level of professionalism.

Through API4AI, integrating sophisticated functionalities into your bot becomes effortless. Hence, we will employ Python and utilize the Car Background Removal API from API4AI in our implementation.

Learning Car Background Removal API

Install the required packages:
pip install pyTelegramBotAPI requests Pillow

All the information you need can be found at: https://api4.ai/docs/car-bg-removal

In order to get a car photo without background, send your photo in a post request to endpoint /img-bg-removal/v1/cars/results.

path_to_img = 'car.jpg'
output_img = 'res.jpg'
with open(path_to_img, 'rb') as f:
    response = requests.post('https://demo.api4ai.cloud/img-bg-removal/v1/cars/results',
                             files={'image': f})
img_b64 = response.json()['results'][0]['entities'][0]['image'].encode('utf8')
with open(output_img, 'wb') as img:
    img.write(base64.decodebytes(img_b64))

Go to https://rapidapi.com/api4ai-api4ai-default/api/cars-image-background-removal and get an API token for use in production code.

Getting an API key

Go to pricing and subscribe to a plan that suits you.
Then go to your dashboard at https://rapidapi.com/developer/dashboard, choose your application, click authorization, and
copy an API key.

Learning pyTelegramBotAPI

Official documentation for pyTelegramBotAPI is available at: https://pytba.readthedocs.io/en/latest/index.html

Let’s start with a simple bot:

bot = telebot.TeleBot(token)

@bot.message_handler(func=lambda message: True)
def echo_message(message):
    bot.reply_to(message, message.text)  

bot.infinity_polling()

Do not forget to create your bot from the father bot https://t.me/BotFather.

Learn more at: https://core.telegram.org/bots/api

Python implementation

Let’s start with simple handlers. This is how we know everything works well.
Handlers should send a message on start and help commands.

Do not forget to install the required packages:
pip install pyTelegramBotAPI requests Pillow

COMPANY_NAME = 'MyCompanyName'

def start_handler(msg: telebot.types.Message, bot: telebot.TeleBot):

    text = f'Hi, welcome to {COMPANY_NAME}. ' \
           'I will help you remove the background from a car photo.'
    bot.send_message(msg.chat.id, text)


def help_handler(msg: telebot.types.Message, bot: telebot.TeleBot):
    text = 'I will help you remove the background from a car photo. ' \
           'Just send me a photo of a car.'
    bot.send_message(msg.chat.id, text)

The next step is to register these handlers. The code in register_handlers is an alternative to registering using decorators:

	@bot.message_handler(commands=['start'], pass_bot=True)
    def start_handler(msg: telebot.types.Message, bot: telebot.TeleBot):
        text = f'Hi, welcome to {COMPANY_NAME}. ' \
               'I will help you remove the background from a car photo.'
        bot.send_message(msg.chat.id, text)  

The reason we intentionally avoid decorators is to avoid global variables.

def register_handlers(bot: telebot.TeleBot):
    bot.register_message_handler(start_handler, commands=['start'],
                                 pass_bot=True)
    bot.register_message_handler(help_handler, commands=['help'],
                                 pass_bot=True)

And now we are ready to create the main function and launch the bot.

def main():
    bot = telebot.TeleBot('Your Token')
    register_handlers(bot)
    bot.infinity_polling()


if __name__ == '__main__':
    main()

The only thing the bot can do for now is sending welcome and help messages.

Let’s add the background removal feature.
We are going to write image_handler step-by-step.

Images from a message are stored on Telegram servers. You can download them using requests or telebot helper function.

import argparse
import base64
import io

import requests
import telebot
from PIL import Image
from requests.adapters import HTTPAdapter, Retry

bg_img = Image.open('bg.png')
logo_img = Image.open('logo.png')

def image_handler(msg: telebot.types.Message, bot: telebot.TeleBot):
    file_path = bot.get_file(msg.photo[-1].file_id).file_path
    orig_photo = bot.download_file(file_path)

Car Background Removal API from API4AI can work in several modes. We will use fg-image-shadow as default.

Now we have a user’s photo, and we are going to send this photo to an API4AI.
We strongly recommend you use exponential backoff when sending your requests.

    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?mode=fg-image-shadow'
    # Make timeout bigger because image processing is a long process.
    api_res = s.post(url, headers={'X-RapidAPI-Key': API_KEY},
                     files={'image': orig_photo}, timeout=20)
    api_res_json = api_res.json()

API4AI and RapidAPI can send errors intentionally or due to unexpected conditions.
All errors that can be sent by API4AI can be found at https://api4.ai/docs/car-bg-removal.

    # Handle possible errors.
        # Handle processing failure.
    if (api_res.status_code != 200 or
            api_res_json['results'][0]['status']['code'] == 'failure'):
        bot.send_message(msg.chat.id, 'Image cannot be processed.')
        return

This is how you can decode an image from base64 to binary format.

    # Decode the processed image from base64 to binary format.
    car_img_64: str = api_res_json['results'][0]['entities'][0]['image']
    car_img_bytes: bytes = base64.b64decode(car_img_64)

This is how you can add your custom background to an image.
If the background resolution is bigger than the resolution of a car photo, then the background will be cropped in the center.

    car_img = Image.open(io.BytesIO(car_img_bytes))
    w, h = car_img.size
    result_img = bg_img.crop((0, 0) + car_img.size)
    result_img.paste(car_img, mask=car_img.split()[3])

Also, the bot supports custom logos.
A logo will be placed at the top left.

    logo_img_scaled = logo_img.resize((w // 8, w // 8))
    result_img.paste(logo_img_scaled, mask=logo_img_scaled.split()[3])

The last thing is to send the new image to the user.

    result_img_buffer = io.BytesIO()
    result_img.save(result_img_buffer, 'png')
    result_img_buffer.seek(0)
    bot.send_photo(msg.chat.id, result_img_buffer)

Do not forget to register this new handler in register_handlers function.
Specify that the handler will be called on all photo messages.

    bot.register_message_handler(image_handler, content_types=['photo'],
                                 pass_bot=True)

The ready Python code is:

"""
Telegram bot.

Telegram bot that can be used for internal purposes
in your car dealership company.
Send a car photo to the bot in Telegram and
you will get a photo of a car without a background in return.

Pass your bot token you got from https://t.me/BotFather
when you launch this script.

How to launch:
`pip3 install requests pyTelegramBotAPI`
`python3 main.py <BOT TOKEN>`
"""

import argparse
import base64
import io

import requests
import telebot
from PIL import Image
from requests.adapters import HTTPAdapter, Retry


COMPANY_NAME = 'MyCompanyName'
API_URL = 'https://cars-image-background-removal.p.rapidapi.com'
bg_img = Image.open('bg.png')
logo_img = Image.open('logo.png')

API_KEY = ''


def parse_args() -> argparse.Namespace:
    """
    Parse command line arguments.

    Returns
    -------
    Arguments from the command line as argparse.Namespace.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('--bot-token',
                        help='Telegram bot token.',
                        required=True)
    parser.add_argument('--api-token',
                        help='Cars image background removal API token.',
                        required=True)  # Get your API key at https://rapidapi.com/api4ai-api4ai-default/api/cars-image-background-removal/details  # noqa

    return parser.parse_args()


def start_handler(msg: telebot.types.Message, bot: telebot.TeleBot):
    """
    Handle the command '/start'.

    Arguments
    ---------
    msg : telebot.types.Message
        message sent to the bot.
    bot : telebot.Telebot
    """
    text = f'Hi, welcome to {COMPANY_NAME}. ' \
           'I will help you remove the background from a car photo.'
    bot.send_message(msg.chat.id, text)


def help_handler(msg: telebot.types.Message, bot: telebot.TeleBot):
    """
    Handle command '/help'.

    Arguments
    ---------
    msg: telebot.types.Message
        message sent to the bot.
    bot: telebot.Telebot
    """
    text = 'I will help you remove the background from a car photo. ' \
           'Just send me a photo of a car.'
    bot.send_message(msg.chat.id, text)


def image_handler(msg: telebot.types.Message, bot: telebot.TeleBot):
    """
    Handle all photos sent to the Telegram bot using API4AI.

    Learn more about the Car Background Removal API:
    https://api4.ai/apis/car-bg-removal

    Arguments
    ---------
    msg : telebot.types.Message
        message sent to the bot.
    bot : telebot.Telebot
    """

    # Download a photo from a message.
    # msg.photo is a list of different resolutions of the photo.
    # The last element has the highest resolution.
    file_path = bot.get_file(msg.photo[-1].file_id).file_path
    orig_photo = bot.download_file(file_path)

    # We strongly recommend you use exponential backoff.
    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?mode=fg-image-shadow'
    # Make timeout bigger because image processing is a long process.
    api_res = s.post(url, headers={'X-RapidAPI-Key': API_KEY},
                     files={'image': orig_photo}, timeout=20)
    api_res_json = api_res.json()

    # Handle processing failure.
    if (api_res.status_code != 200 or
            api_res_json['results'][0]['status']['code'] == 'failure'):
        bot.send_message(msg.chat.id, 'Image cannot be processed.')
        return

    # Decode the processed image from base64 to binary format.
    car_img_64: str = api_res_json['results'][0]['entities'][0]['image']
    car_img_bytes: bytes = base64.b64decode(car_img_64)
    car_img = Image.open(io.BytesIO(car_img_bytes))

    # Paste car image over custom background and add a company logo.
    w, h = car_img.size
    result_img = bg_img.crop((0, 0) + car_img.size)
    result_img.paste(car_img, mask=car_img.split()[3])
    logo_img_scaled = logo_img.resize((w // 8, w // 8))
    result_img.paste(logo_img_scaled, mask=logo_img_scaled.split()[3])

    # Send the photo in an answer.
    result_img_buffer = io.BytesIO()
    result_img.save(result_img_buffer, 'png')
    result_img_buffer.seek(0)
    bot.send_photo(msg.chat.id, result_img_buffer)


def register_handlers(bot: telebot.TeleBot):
    """
    Register handlers for Telegram bot commands.

    You can create handlers the way suggested here:
    https://pytba.readthedocs.io/en/latest/quick_start.html#synchronous-telebot
    but it requires the bot variable to be global.

    Arguments
    ---------
    bot : telebot.Telebot
    """
    bot.register_message_handler(start_handler, commands=['start'],
                                 pass_bot=True)
    bot.register_message_handler(help_handler, commands=['help'],
                                 pass_bot=True)
    bot.register_message_handler(image_handler, content_types=['photo'],
                                 pass_bot=True)


def main():
    """
    Script entrypoint.

    Parse command line arguments and run the Telegram bot.
    """
    args = parse_args()
    bot = telebot.TeleBot(args.bot_token)
    global API_KEY
    API_KEY = args.api_token
    register_handlers(bot)

    bot.infinity_polling()


if __name__ == '__main__':
    main()

As a result, we have a Telegram bot that works!

Conclusion

Having a Telegram bot can provide numerous benefits for your business, including cost-efficiency, accessibility, streamlined automation, personalization, and fortified security measures.
By leveraging the power of API4AI, it becomes possible to augment the capabilities of your bot, tailoring its functionalities to align with the specific requirements of your tasks.

To further optimize the functionality of your bot, the subsequent stride entails deploying it on a cloud platform of your choice.
Prominent examples encompass Google Cloud Run and Heroku, which offer robust infrastructures for hosting and running your bot seamlessly.