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

Introduction

In today's digital era, accurately measuring brand visibility during sports event streaming has become increasingly crucial. As audiences flock to online platforms for live sports, brands are seizing the opportunity to gain exposure. However, understanding the true impact of that exposure—how effectively a brand is being seen and recognized—poses significant challenges. This is where automated tools, particularly APIs, come into play. They provide the ability to analyze video content in real-time, detecting brand presence with precision and efficiency that manual methods simply cannot match.

Brand visibility plays a vital role in determining the success of sponsorship deals and the overall value of advertising investments. When a brand is prominently displayed during a high-profile sports event, it can drive significant audience engagement, enhance recall, and ultimately contribute to higher returns on marketing investments. However, measuring this visibility manually can be a daunting task. Traditional methods often rely on subjective assessments and are time-consuming, leading to inconsistencies and potential inaccuracies. In contrast, automated solutions offer a streamlined approach, enabling brands to gather actionable insights quickly and effectively.

The purpose of this post is to guide you through the process of writing a Python script that leverages the API4AI Brand Marks and Logo Recognition API to analyze sports event videos and calculate brand visibility. We will walk through each step of the development process, from setting up the API to executing the script and interpreting the results. By the end of this guide, you will have a practical tool at your disposal to help you understand and measure brand visibility in real-time sports event streaming, empowering you to make data-driven decisions for your marketing strategies.

Section 1: Understanding Brand Visibility in Sports Event Streaming

Definition of Brand Visibility

Brand visibility in the context of sports event streaming refers to the extent to which a brand is seen and recognized by viewers during a live broadcast. It encompasses several key components that contribute to how effectively a brand can capture the audience's attention and create a lasting impression. Among these components are screen time, which measures the duration for which a brand's logo is visible; prominence, which considers the visibility of the brand in relation to other elements on the screen; size, which looks at how large the logo appears; and clarity, which assesses the quality and sharpness of the logo as it appears in the video. Together, these factors determine not only how frequently a brand is displayed but also how well it resonates with viewers.

Challenges in Measuring Brand Visibility

Despite its importance, measuring brand visibility during sports events poses several challenges. Traditional methods often rely on subjective assessments, where analysts watch broadcasts and manually record brand appearances. This approach is not only time-consuming but also prone to bias, as different individuals may interpret visibility differently. Additionally, the dynamic nature of sports events—characterized by fast-paced action, quick camera cuts, and varying angles—makes it difficult to capture every instance of brand visibility accurately.

Moreover, the sheer volume of video data generated during sports events can overwhelm manual analysis efforts. Analyzing hours of footage for brand appearances requires significant resources, making it impractical for many organizations. As a result, brands may miss critical insights that could enhance their marketing strategies and sponsorship effectiveness.

Introduction to Automated Solutions

To address these challenges, automated solutions powered by AI and machine learning have emerged as a game-changer in measuring brand visibility. By utilizing advanced algorithms, AI-driven APIs can analyze video content in real-time, accurately detecting and measuring brand logos and their visibility metrics. These tools automate the tedious process of manual analysis, enabling brands to gain insights into their visibility during sports events more efficiently and accurately.

Using automated solutions allows brands to monitor their exposure continuously, providing valuable data that can inform marketing decisions, sponsorship negotiations, and overall brand strategy. This shift from manual methods to automated analysis not only enhances the accuracy of brand visibility measurements but also empowers brands to adapt quickly to the ever-changing landscape of sports event streaming.

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

Introduction to API4AI

API4AI is a cutting-edge platform designed to harness the power of artificial intelligence for various recognition tasks, including image and video analysis. It provides developers and businesses with advanced tools to automate and enhance their brand recognition efforts. In the context of sports event streaming, the API4AI Brand Marks and Logo Recognition API stands out as a vital resource for accurately detecting and analyzing brand presence in visual content.

This API specifically focuses on identifying brand logos in images, making it an invaluable tool for marketers and brand managers seeking to measure visibility and engagement during live broadcasts. Its primary purpose is to facilitate real-time analysis of images, allowing users to gather actionable insights about their brand's exposure in a dynamic environment.

Capabilities of the API

The Brand Marks and Logo Recognition API comes equipped with a range of powerful capabilities that enhance its effectiveness in brand visibility measurement:

  1. Detection of Multiple Logos:

    • The API can simultaneously identify and analyze multiple logos within a single frame. This feature is particularly useful during sports events, where several brands may be visible at once, allowing for comprehensive analysis.

  2. Recognition of Partial Logos:

    • Unlike traditional recognition methods that require complete visibility of a logo, this API can identify logos even when they are partially obscured. This capability ensures that brands are accurately recognized, regardless of the dynamic nature of sports broadcasts.

  3. Detection of Rare or Newly Created Logos:

    • The API is designed to recognize not only established brands but also rare or newly created logos. This flexibility allows brands to measure their visibility effectively, even if they are just starting to enter the sports marketing arena.

  4. Real-Time Processing:

    • The API provides real-time analysis, enabling users to obtain immediate feedback on brand visibility. This instant access to data empowers brands to make quick decisions and adjustments to their marketing strategies.

Benefits Over Traditional Methods

Using the API4AI Brand Marks and Logo Recognition API presents several significant advantages over traditional manual analysis methods:

  • Accuracy: Automated analysis reduces human error and provides consistent results, ensuring that brands receive reliable visibility metrics.

  • Speed: The API processes video data quickly, enabling brands to analyze vast amounts of content in a fraction of the time it would take with manual methods.

  • Scalability: As sports events generate large volumes of video data, the API's ability to scale allows brands to analyze multiple events simultaneously without sacrificing accuracy or speed.

In summary, the API4AI Brand Marks and Logo Recognition API equips brands with powerful tools to automate their visibility analysis in sports event streaming, enhancing their ability to measure and optimize their marketing efforts effectively.

Section 3: Writing Python Script for Video Processing

Setting up the API

To get started with the API4AI Brand Marks and Logo Recognition API, you’ll first need to create an account on RapidAPI Hub and obtain an API Key:

  • Create an Account on Rapid API Hub website.

  • Find the Brand Recognition API: Once logged in, follow this link to find NSFW API.

  • Subscribe to the API on the page with subscription plans.

  • Obtain Your API Key:

    • After subscribing, navigate to the Dashboard.

    • On the left pat of the screen you should see something like “default-application_xxxxxx“.

    • Go to Autorization and copy Application Key

Rapid API Hub - Obtain API Key

Prerequisites

Before you start writing the script, ensure you have the necessary tools installed:

  • Python Installation:

    • Make sure you have Python 3.x installed on your machine. You can download it from python.org.

  • Required Libraries:

    • The following libraries are essential for this project:

      • aiohttp for making HTTP requests.

      • OpenCV for video processing.

  • Installing Libraries:

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

pip install opencv-python aiohttp

Splitting Video into Frames

To analyze the video, you first need to extract frames from it. In just a few simple lines of code, OpenCV can be effectively employed to split a video into individual frames. This process allows for the extraction of each frame from a video file, enabling further analysis or manipulation of the images.

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()

Looking for the Specified Brand in a Frame

By utilizing the brand recognition API, it becomes possible to thoroughly examine an image for the presence of the intended brand. This tool allows users to identify and verify brands within various images, ensuring that the branding elements are accurately recognized. Additionally, the aiohttp library plays a crucial role in this process by facilitating the dispatch 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

Parsing Command-Line Arguments

To make your script user-friendly, use the argparse library to accept command-line arguments 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()

Main Function

The main function orchestrates the overall process, including capturing frames, sending them for recognition, and calculating visibility metrics. The combination of asyncio and aiohttp can effectively facilitate the asynchronous handling of all frames extracted 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())

Complete Python Code

Here’s the complete Python script that integrates 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())

Testing the Script

Now let’s play a bit with the script. WE prepared a short video containing a couple of scenes with different logos, download it here.

Several frames from video for testing

Several frames from videos illustrating different logos: Red Bull, Nike, NEXEN TIRE, G2A, etc.

Now let's try to understand what fraction of the video contains the Red Bull logo displayed:

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.

Not bad result for Red Bull - it is presented on more than 50% of video :)

Let’s calculate similar metric for several more 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.

Of course, this is just a very simple example illustrating how different brands can be detected in a video. Feel free to modify the script to calculate additional statistics and gain deeper insights into the brand presence.

In particular, it can be very useful to take into account information about logo sizes, as the API can return details regarding the size category of each logo, as described in the documentation. Understanding logo sizes can provide valuable context for analyzing brand visibility and prominence within the video.

Additionally, you can easily modify the script to provide comprehensive information about all the brands identified in the video with just a few simple adjustments. This functionality can enhance your analysis by allowing you to track multiple brands and their occurrences throughout the footage.

Conclusion

In this blog post, we explored the process of calculating brand visibility in sports event video streaming using Python and the API4AI Brand Marks and Logo Recognition API. We began by understanding the concept of brand visibility and its significance in the realm of sports marketing. We then walked through the practical steps involved in writing a Python script to analyze video content, which included setting up the API, preparing prerequisites, extracting frames from video, analyzing those frames for brand presence, and finally calculating visibility metrics. By leveraging 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 on different videos to see how brand visibility can vary across various events and contexts. Feel free to explore additional features of the API, such as detecting size category for each logo. This experimentation will not only enhance your understanding but also help you tailor your marketing strategies based on real-time data.

In closing, the importance of leveraging AI and APIs for modern brand visibility measurement cannot be overstated. These tools provide the means to automate data collection and analysis, resulting in more accurate and timely insights. As technology continues to advance, the potential for these tools to transform how brands approach visibility measurement and marketing strategy will only grow. Embrace the future of analytics, and empower your brand to stand out in the competitive landscape of sports marketing.

Previous
Previous

Top Use Cases for Cloud-Based OCR in Industry and Business Automation

Next
Next

A Beginner’s Guide to Implementing AI APIs in Your Business