← Impulso Blog

A complete guide to creating NBA highlights with Python

Do you like the NBA and programming? See how to bring the two together and create your own basketball highlights.

A hand holding a basketball. The image illustrates the article’s focus on using Python to create NBA highlights.

Editorial translation by Impulso.

Do you like the NBA and programming? Now’s the time to bring those two worlds together in a fun and relatively easy way. You’ll also be able to save the plays you like most from your favorite teams or players. After all, in a world where people need to consume content faster and faster (and it needs to grab their attention right away), it’s worth remembering that not every basketball fan watches entire games. Some fans prefer what are called highlights (the most common term for standout moments or plays). The goal of this article is to help you create those videos with open-source tools. Ready? Let’s go!

This project was written in Python, but it can easily be replicated in any language. Before we get started, it’s worth mentioning the libraries we used in this project:

image-01

Play-by-play

The play-by-play provides a transcript of the game as a series of individual events. Here are some examples of the data you can find in the play-by-play:

  • Time of possession (on the game clock);
  • The period in which the possession occurred;
  • The player who started the possession (in the case of a steal or a defensive rebound);
  • The opposing player who started the possession (in the case of a missed shot or a turnover), along with the location on the court where the shot was taken and other unique identifiers we use to classify the type of possession.

Remember that the data we’re extracting comes from the official NBA APIs (data.nba.net and cdn.nba.com) and is stored in JSON format. So it only takes a few lines of code to get the data into a more traditional format, such as a DataFrame.

The first part gives us the games played on a given date:

Code building the NBA scoreboard URL for a date, requesting it and reading the JSON response.

Next, we check whether the teams we entered actually played on that date. If they did, we take the game ID and pass it to the next API. Then we extract the data and load it into a pandas DataFrame:

raw_game = f'https://cdn.nba.com/static/json/liveData/playbyplay/playbyplay\_{game\_id}.json' page = requests.get(raw_game) j = json.loads(page.content) df = pd.DataFrame(j['game']['actions'])

After that, the result looks something like this:

Play-by-play table with columns for action number, clock, period, action type and associated person.

From there, we can filter for any type of play we’re interested in (baskets, steals, blocks, etc.). In our case, we’re only looking at made shots and excluding free throws. Here’s what that looks like:

ndf = df[['clock', 'period', 'description', 'teamTricode', 'shotResult', 'actionType']] ndf = ndf[ndf['shotResult'] == 'Made'] ndf = ndf[ndf['actionType'] != 'freethrow']

Now that we have a dataset of all the moments we’re interested in, it’s time to find them in the actual game footage.

Processing the game video

The next step is to break the game video into frames and process them using the OpenCV module.

Python snippet opening the video file with OpenCV and reading the first frame to begin processing.

Now we’ll run each frame through a series of preprocessing steps to get it ready for OCR (we’ll talk more about that in a bit). Here’s what to do:

  • Crop the original frame to keep only the bottom third, where the game clock is located (so we don’t waste time reading the whole frame);
  • Convert the image to grayscale;
  • Convert the grayscale image to black and white;
  • Apply a Gaussian blur to the black-and-white image.

Code cropping the lower part of a frame, converting it to grayscale, applying a binary threshold and Gaussian blur.

Original basketball frame showing players on court and the broadcast scoreboard along the bottom.

Original

Color scoreboard crop showing Toronto 17, Golden State 8 and 7:32 left in the first quarter.

Cropped

Black-and-white processed scoreboard strip retaining team abbreviations, scores and game clock.

With Gaussian blur

Tesseract

This is an open-source optical character recognition engine. It’s the most popular OCR library and a high-quality choice for our project. It’s also quite modern, since OCR uses artificial intelligence to find and recognize text in images. In this case, the job is actually pretty simple: finding patterns in pixels, letters, words, and sentences.

It can also recognize more than 100 languages out of the box and can be trained to recognize others. Basically, the engine finds and extracts text from images. For this project, we’re using python-tesseract (pytesseract), a Python wrapper for Google’s Tesseract-OCR engine. It has 13 Tesseract configuration modes. We’re going to focus on mode 11: sparse text. That means we’ll find as much text as possible in no particular order.

Implementing Tesseract

The next step is to run our processed frame through the Tesseract engine.

Python snippet calling pytesseract.image_to_string to recognize English text in a blurred frame. OCR sequence: scoreboard crop, boxes around detected text, and final single-line transcription.

Now that we have all the text in the frame, we can look for two things: the current quarter and the game clock.

Processed black-and-white scoreboard above the line of text extracted by OCR.

The quarter is "1st" and the game clock reads "7:32". But Tesseract returns "ist". It mistook the number "1" for the letter "i".

So the next step is to map out the common errors for each quarter.

Four Python lists group possible OCR readings for each quarter of the game.

Combining play-by-play data with footage data

All right, let’s recap what we have so far: we built a play-by-play tracker, processed frames from the game footage, and ran them through the Tesseract engine to extract the text from each frame. Now it’s time to combine the data and find the highlights.

So how do we do that? Well, we process each frame of the game footage as described above and check whether the quarter and game clock we extracted match the quarter and game clock of a highlight.

If there’s a match, we save the frame number.

Code retrieving the current frame number with OpenCV and adding it to a list.

Putting the frames together

Once we’ve gone through every frame of the game and have a list of the frames where highlights occurred, all we have to do is put them together. We’ll do that using the moviepy module, which lets us cut subclips from full videos. To show the entire play that led to the highlight, we take a few seconds before and a few seconds after the exact second it happened. Code creating clips around selected frames, concatenating them and writing the finished video.

Example highlights

Now that we’ve finished creating the highlights, let’s see how they turned out.

https://www.youtube.com/watch?v=pTmcIf%5C_Zqo4

Improving efficiency

This is a basic script for finding moments of interest and creating highlight clips, but it’s far from efficient. There are several easy ways to make it more efficient, though:

  • Skipping ahead one second at a time instead of checking every frame cuts the number of frames processed in a 2-hour game (at 60 fps) from 430,000 to 7,200.
  • Finding the coordinates of the game clock and running OCR on just that area will reduce processing time.
  • Track changes in the score instead of the game clock if you only want made baskets
  • Use multiprocessing to work in parallel and speed things up. A GPU can help too.

To sum up

This is just one small example of how open-source technologies can be used to create amazing products. But you don’t have to stop here! If you’d like to join us, we work together on some open-source programming projects in our Community. Haven’t heard of it yet? Then click here to join 100% free. If you’d like to learn more about the many benefits you get when you join for free, take a look here. See you there, okay? If you have any questions, feel free to ping me at @ine.

[This text was translated and adapted from the article published by Better Programming]

Related articles