DEV Community

Cover image for How to Calculate Brand Visibility for Sports Event Video Streaming with Brand Recognition API
Tarana Murtuzova for API4AI

Posted on

How to Calculate Brand Visibility for Sports Event Video Streaming with Brand Recognition API

Introduction

In the modern digital landscape, accurately gauging brand visibility during the streaming of sports events has become increasingly essential. As more viewers turn to online platforms for live sports, brands are capitalizing on these opportunities to boost their exposure. However, assessing the true impact of this exposure—determining how well a brand is seen and recognized—presents substantial challenges. This is where automated solutions, especially APIs, prove invaluable. These tools allow for real-time analysis of video content, detecting brand appearances with a level of accuracy and efficiency that surpasses traditional manual methods.

Brand visibility is a key factor in evaluating the success of sponsorship agreements and the overall effectiveness of advertising investments. When a brand is prominently featured during a major sports event, it can significantly boost audience engagement, improve recall, and ultimately lead to greater returns on marketing expenditures. However, measuring this visibility by hand can be an overwhelming task. Conventional methods often depend on subjective judgment and are time-intensive, leading to inconsistencies and potential inaccuracies. In contrast, automated systems provide a more streamlined approach, enabling brands to quickly and efficiently gather actionable insights.

This post aims to guide you through the process of creating a Python script that utilizes the API4AI Brand Marks and Logo Recognition API to analyze sports event videos and quantify brand visibility. We will cover each phase of the development process, from setting up the API to running the script and interpreting the findings. By the conclusion of this guide, you will have a practical tool at your disposal to help you monitor and measure brand visibility in real-time sports event streaming, empowering you to make informed, data-driven decisions for your marketing strategies.

Section 1: Grasping Brand Visibility in Sports Event Streaming

Defining Brand Visibility

Brand visibility, within the scope of sports event streaming, refers to the degree to which a brand is observed and recognized by viewers during a live broadcast. It includes several critical aspects that influence how effectively a brand can capture the audience’s focus and leave a lasting impression. These aspects include screen time, which gauges the duration a brand’s logo is visible; prominence, which considers the visibility of the brand relative to other on-screen elements; size, which examines the dimensions of the logo; and clarity, which evaluates the quality and sharpness of the logo as it appears in the video. Collectively, these elements determine not only the frequency of a brand’s appearance but also the extent to which it connects with viewers.

Challenges in Assessing Brand Visibility

Despite its significance, assessing brand visibility during sports events presents multiple obstacles. Traditional methods often depend on subjective evaluations, where analysts watch broadcasts and manually track brand appearances. This method is not only labor-intensive but also susceptible to bias, as different people may perceive visibility in varying ways. Additionally, the dynamic nature of sports events—marked by rapid action, frequent camera shifts, and diverse angles—makes it challenging to capture every instance of brand visibility with precision.

Furthermore, the vast amount of video data generated during sports events can easily overwhelm manual analysis efforts. Reviewing hours of footage to identify brand appearances demands extensive resources, making it impractical for many organizations. Consequently, brands may overlook vital insights that could improve their marketing strategies and sponsorship success.

Introduction to Automated Solutions

To overcome these challenges, automated solutions powered by AI and machine learning have emerged as transformative tools for assessing brand visibility. By leveraging sophisticated algorithms, AI-driven APIs can analyze video content in real-time, accurately detecting and measuring brand logos and their visibility metrics. These technologies automate the tedious task of manual analysis, allowing brands to gain insights into their visibility during sports events more efficiently and accurately.

Automated solutions enable continuous monitoring of brand exposure, providing valuable data that can guide marketing strategies, sponsorship agreements, and overall brand positioning. This transition from manual methods to automated analysis not only improves the precision of brand visibility assessments but also equips brands to swiftly adapt to the ever-evolving landscape of sports event streaming.

Section 2: Overview of the API4AI Brand Marks and Logo Recognition API

Introduction to API4AI

API4AI is a state-of-the-art platform designed to leverage artificial intelligence for various recognition tasks, including image and video analysis. It equips developers and businesses with sophisticated tools to automate and enhance their brand recognition processes. When it comes to sports event streaming, the API4AI Brand Marks and Logo Recognition API emerges as a crucial tool for accurately detecting and assessing brand presence in visual content.

This API is specifically tailored to identify brand logos in images, making it an essential resource for marketers and brand managers who aim to measure visibility and engagement during live broadcasts. Its primary function is to enable real-time image analysis, providing users with actionable insights regarding their brand's exposure in a rapidly changing environment.

Capabilities of the API

The Brand Marks and Logo Recognition API is equipped with a robust set of features that significantly enhance its utility in measuring brand visibility:

  • Detection of Multiple Logos:
    The API can detect and analyze several logos within a single frame simultaneously. This capability is especially beneficial during sports events, where multiple brands may be displayed at once, allowing for a thorough and detailed analysis.

  • Recognition of Partial Logos:
    Unlike traditional recognition systems that require a logo to be fully visible, this API can identify logos even when they are partially hidden. This feature ensures that brands are recognized accurately, despite the fast-paced and unpredictable nature of sports broadcasts.

  • Detection of Rare or Newly Designed Logos:
    The API is engineered to recognize not only well-known brands but also rare or newly introduced logos. This adaptability allows emerging brands to effectively measure their visibility, even as they begin to enter the sports marketing space.

  • Real-Time Processing:
    The API offers real-time analysis, providing users with immediate insights into brand visibility. This instant access to data empowers brands to swiftly make informed decisions and adjustments to their marketing strategies.

Benefits Over Traditional Methods

Utilizing the API4AI Brand Marks and Logo Recognition API offers several key benefits compared to conventional manual analysis techniques:

  • Precision: Automated analysis minimizes human error and delivers consistent results, ensuring that brands receive accurate and trustworthy visibility metrics.
  • Efficiency: The API processes video data at high speed, allowing brands to analyze extensive content in a fraction of the time required by manual methods.
  • Scalability: Given the large volumes of video data generated during sports events, the API's scalability enables brands to analyze multiple events concurrently without compromising on accuracy or speed.

The API4AI Brand Marks and Logo Recognition API provides brands with robust tools to automate visibility analysis in sports event streaming, significantly enhancing their ability to measure and optimize their marketing strategies effectively.

Section 3: Developing a Python Script for Video Processing

Configuring the API

To begin using the API4AI Brand Marks and Logo Recognition API, you'll need to set up an account on RapidAPI Hub and obtain an API Key:

  1. Register on RapidAPI Hub: Start by creating an account on the RapidAPI Hub website.
  2. Locate the Brand Recognition API: After logging in, use this link to find the Brand Recognition API.
  3. Subscribe to the API: On the API page, choose a subscription plan that suits your needs.
  4. Acquire Your API Key:
  • Once subscribed, go to your Dashboard.
  • On the left side of the screen, you'll see an entry like "default-application_xxxxxx."
  • Navigate to the Authorization section and copy your Application Key.

Image description

Prerequisites

Before beginning the script, ensure you have the essential tools in place:

Python Installation:

Ensure that Python 3.x is installed on your system. You can download it from the official website at python.org.

Necessary Libraries:

The project requires the following libraries:

  • aiohttp for handling HTTP requests.
  • OpenCV for processing video content.

Installing Libraries:

Open your terminal or command prompt and execute the following commands to install the required libraries:

pip install opencv-python aiohttp
Enter fullscreen mode Exit fullscreen mode

Splitting Video into Frames

To perform video analysis, the first step is to extract individual frames. With just a few lines of code, OpenCV can be used efficiently to break down a video into separate frames. This process allows each frame to be isolated from the video file, facilitating further analysis or image manipulation.

import argparse
import asyncio
import itertools
from pathlib import Path

import aiohttp
import cv2
import numpy

API_URL = 'https://brand-recognition.p.rapidapi.com'

THRESHOLD = 0.5

def split_video_by_frames(path: Path):
    """Split video by frames using OpenCV."""
    cap = cv2.VideoCapture(str(path))
    while cap.isOpened():
        success, image = cap.read()
        if not success:
            break
        yield image
    cap.release()
Enter fullscreen mode Exit fullscreen mode

Looking for the Specified Brand in a Frame

By leveraging the brand recognition API, you can thoroughly analyze an image to detect the presence of the desired brand. This tool enables users to identify and confirm brands within different images, ensuring that branding elements are correctly recognized. Moreover, the aiohttp library is essential in this process, as it supports the sending of asynchronous requests.

async def is_brand_on_photo(img: numpy.ndarray, brand_name: str, api_key: str):
    """Determine if a brand is presented in a photo."""

    url = f'{API_URL}/v2/results'

    async with aiohttp.ClientSession() as s:
        async with s.post(url,
                          data={'image': cv2.imencode('.jpg', img)[1].tobytes()},
                          headers={'X-RapidAPI-Key': api_key}) as api_res:
            try:
                api_res_json = await api_res.json()
            except aiohttp.client.ContentTypeError:
                print(await api_res.text())
                print('Response is not a JSON.')
                return False

    # Handle processing failure.
    if (api_res.status != 200 or
            api_res_json['results'][0]['status']['code'] == 'failure'):
        print('Image processing failed.')
        print(api_res_json)
        return False

    # Check if your brand found in the photo.
    brands = api_res_json['results'][0]['entities'][0]['strings']

    return brand_name in brands
Enter fullscreen mode Exit fullscreen mode

Parsing Command-Line Arguments

To enhance the usability of your script, employ the argparse library to accept command-line inputs for video file paths and brand names.

def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument('--api-key', help='Rapid API key.', required=True)  # Get your token at https://rapidapi.com/api4ai-api4ai-default/api/brand-recognition/pricing
    parser.add_argument('--brand-name', required=True)
    parser.add_argument('--video', type=Path,
                        help='Path to a video.')
    return parser.parse_args()
Enter fullscreen mode Exit fullscreen mode

Core Function

The core function manages the entire workflow, including extracting frames, submitting them for recognition, and computing visibility metrics. By utilizing asyncio alongside aiohttp, you can efficiently handle the asynchronous processing of all frames retrieved from a video.

async def main():
    """
    Script entry function.
    """
    args = parse_args()
    brands_frames = await asyncio.gather(
        *[is_brand_on_photo(frame, args.brand_name, args.api_key)
          for frame in split_video_by_frames(args.video)]
    )
    count_brand_visible = sum(brands_frames)
    brand_presented_percent = count_brand_visible / len(brands_frames) * 100

    print('Frame count: ', len(brands_frames))
    print(f'Brand is presented in {count_brand_visible} frames.')
    print(f'Brand presented on {brand_presented_percent}% of the video.')


if __name__ == '__main__':
    asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Full Python Script

Below is the full Python code that brings together all the previous steps:

"""
Calculate the percentage of a video on which brand advertising is visible.

Run script:
`python3 main.py --api-key <RAPID_API_KEY> --brand-name <NAME_OF_YOUR_BRAND> <PATH_TO_VIDEO>
"""

import argparse
import asyncio
import itertools
from pathlib import Path

import aiohttp
import cv2
import numpy

API_URL = 'https://brand-recognition.p.rapidapi.com'

THRESHOLD = 0.5


def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument('--api-key', help='Rapid API key.', required=True)  # Get your token at https://rapidapi.com/api4ai-api4ai-default/api/brand-recognition/pricing
    parser.add_argument('--brand-name', required=True)
    parser.add_argument('--video', type=Path,
                        help='Path to a video.')
    return parser.parse_args()


async def is_brand_on_photo(img: numpy.ndarray, brand_name: str, api_key: str):
    """Determine if a brand is presented in a photo."""

    url = f'{API_URL}/v2/results'

    async with aiohttp.ClientSession() as s:
        async with s.post(url,
                          data={'image': cv2.imencode('.jpg', img)[1].tobytes()},
                          headers={'X-RapidAPI-Key': api_key}) as api_res:
            try:
                api_res_json = await api_res.json()
            except aiohttp.client.ContentTypeError:
                print(await api_res.text())
                print('Response is not a JSON.')
                return False

    # Handle processing failure.
    if (api_res.status != 200 or
            api_res_json['results'][0]['status']['code'] == 'failure'):
        print('Image processing failed.')
        print(api_res_json)
        return False

    # Check if your brand found in the photo.
    brands = api_res_json['results'][0]['entities'][0]['strings']

    return brand_name in brands


def split_video_by_frames(path: Path):
    """Split video by frames using OpenCV."""
    cap = cv2.VideoCapture(str(path))
    while cap.isOpened():
        success, image = cap.read()
        if not success:
            break
        yield image
    cap.release()


async def main():
    """
    Script entry function.
    """
    args = parse_args()
    brands_frames = await asyncio.gather(
        *[is_brand_on_photo(frame, args.brand_name, args.api_key)
          for frame in split_video_by_frames(args.video)]
    )
    count_brand_visible = sum(brands_frames)
    brand_presented_percent = count_brand_visible / len(brands_frames) * 100

    print('Frame count: ', len(brands_frames))
    print(f'Brand is presented in {count_brand_visible} frames.')
    print(f'Brand presented on {brand_presented_percent}% of the video.')


if __name__ == '__main__':
    asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Script Testing

Let's now experiment with the script. We've prepared a brief video featuring a few scenes with various logos, which you can download here.

Image description
Multiple frames from the video showcasing various logos: Red Bull, Nike, NEXEN TIRE, G2A, and others.

Now, let’s determine what portion of the video features the Red Bull logo.

python3 main.py --api-key YOUR_API_KEY --brand-name "Red Bull" --video ./qa_video.mp4
Frame count:  196
Brand is presented in 129 frames.
Brand presented on 65.81632653061224% of the video.
Enter fullscreen mode Exit fullscreen mode

A solid outcome for Red Bull—it appears in over 50% of the video! :)

Now, let’s compute a similar metric for a few other brands:

python3 main.py --api-key YOUR_API_KEY --brand-name "Nike" --video ./qa_video.mp4
Frame count:  196
Brand is presented in 67 frames.
Brand presented on 34.183673469387756% of the video.

python3 main.py --api-key YOUR_API_KEY --brand-name "Nexen Tire" --video ./qa_video.mp4
Frame count:  196
Brand is presented in 60 frames.
Brand presented on 30.612244897959183% of the video.

python3 main.py --api-key YOUR_API_KEY --brand-name "G2A" --video ./qa_video.mp4
Frame count:  196
Brand is presented in 64 frames.
Brand presented on 32.6530612244898% of the video.
Enter fullscreen mode Exit fullscreen mode

This is, of course, just a basic example demonstrating how different brands can be detected in a video. Feel free to tweak the script to calculate additional statistics and gain deeper insights into brand presence.

In particular, it can be quite beneficial to consider logo size information, as the API provides details on the size category of each logo, as outlined in the documentation. Understanding logo sizes offers valuable context for analyzing brand visibility and prominence within the video.

Moreover, you can easily adapt the script to deliver detailed information about all the brands identified in the video with just a few straightforward adjustments. This enhancement will improve your analysis by enabling you to monitor multiple brands and their appearances throughout the footage.

Conclusion

In this blog post, we delved into the process of calculating brand visibility in sports event video streaming using Python and the API4AI Brand Marks and Logo Recognition API. We started by exploring the concept of brand visibility and its importance in the world of sports marketing. We then guided you through the practical steps of creating a Python script to analyze video content, covering API setup, prerequisite preparation, frame extraction, brand detection within those frames, and finally, the calculation of visibility metrics. By utilizing these advanced tools, you can gain valuable insights into how effectively your brand is being recognized during live sports events.

We encourage you to experiment with the script across different videos to observe how brand visibility varies across various events and contexts. Additionally, feel free to explore more features of the API, such as detecting the size category of each logo. This experimentation will not only deepen your understanding but also enable you to tailor your marketing strategies based on real-time data.

In conclusion, the significance of leveraging AI and APIs for modern brand visibility measurement cannot be overstated. These tools allow for automated data collection and analysis, resulting in more accurate and timely insights. As technology continues to evolve, the potential for these tools to revolutionize how brands approach visibility measurement and marketing strategies will only expand. Embrace the future of analytics and empower your brand to excel in the competitive arena of sports marketing.

More stories about AI-bases APIs

Top comments (0)