AI on the Edge LESSON 54: Custom Hand Gesture Recognition and Dynamic NeoPixel Control

Welcome back, everyone! This is Paul McWhorter from TopTechBoy.com, and welcome to Lesson 54 in our AI on the Edge series.

In this lesson, we are taking our hand gesture recognition system to the next level by connecting it directly to real physical hardware! We’re going to take the normalized vector distance calculations and MediaPipe hand-tracking models we’ve been building over the past few lessons, and use them to drive a 12-LED NeoPixel Ring via SPI on the Raspberry Pi in real time.

If you’re following along in the series, pull up a chair, get yourself a nice hot cup of iced coffee, and let’s get right into it!

What We Are Building Today

In previous lessons, we learned how to extract 3D landmark coordinates from MediaPipe, scale them by the palm length to achieve scale-invariant gesture tracking, and store those relative Euclidean distances into a pickle database (gestureNEOPIXEL.pkl).

In Lesson 54, we map those live gesture detections directly to non-blocking LED animation patterns:

  1. Fist: Pulses a dynamic red “charge” sine wave.

  2. Open Palm: Drives the NeoPixel ring at full intensity white beacon.

  3. Peace Sign (✌️): Runs a dual-spinner pattern with opposing green and blue tracer LEDs over a low background red glow.

  4. Thumbs Up: Illumination of a solid, bright green “success” status.

  5. Point: Sweeps a fast green radar chaser dot across a red background array.

  6. Rock / Metal (🤘): Generates a smooth, sinusoidal cyan-to-green energy pulse.

  7. OK Sign: Cycles through a full spectrum RGB rainbow wheel.

  8. Unknown / Default: Gracefully turns off all LEDs.

Hardware Setup & Wiring (SPI Interface)

To ensure high frame rates without flickering, we drive our NeoPixels over the SPI bus using the neopixel_spi library.

Wiring Diagram Guide

  • NeoPixel VCC: Connect to 5V power supply (ensure adequate power if driving high brightness).

  • NeoPixel GND: Common ground with the Raspberry Pi GND pin.

  • NeoPixel DIN (Data In): Connect to GPIO 10 (SPI0 MOSI) on the Raspberry Pi pinout (Physical Pin 19).

Note: Ensure SPI is enabled in your Raspberry Pi system configuration (sudo raspi-config -> Interfaces -> SPI).

⌨️ Interactive Keyboard Controls

While running the main video processing loop, you can dynamically manage your trained gestures directly from your keyboard without interrupting the camera feed:

  • SPACE: Capture and train/overwrite the current gesture showing on screen.

  • T: Prompt the terminal to type in and add a brand-new gesture name on the fly.

  • D: Prompt the terminal to remove/delete an existing gesture from the active dataset.

  • Q: Cleanly turn off all NeoPixel LEDs, save the updated gesture data, and terminate the program.

Complete Python Source Code

Below is the complete, fully commented Python script for Lesson 54.

Homework Assignment

Your homework for this lesson is to modify the updateNeoPixels() function to add two new custom hand gestures of your own creation! Try implementing custom animations like a warm candle flicker or a pulsating dual-color pattern. Leave a link to your solution videos in the comments below!

AI on the Edge LESSON 53: Gesture Recognition on the Pi 5 with Training File

 Welcome back, everyone! In this lesson, we are taking our custom MediaPipe hand gesture recognition system to the next level. Up until now, every time you stopped your Python script, all of your hard-earned gesture training data vanished into thin air. If you wanted to run your project again, you had to re-train every single hand sign from scratch.

That ends today. We are going to make our AI remember what it learned by saving our gesture feature vectors to a local file using Python’s pickle library.

What You Will Learn in This Lesson

  • Data Persistence: How to serialize and save Python dictionaries containing landmark distance vectors directly to disk (gesture_data.pkl).

  • Automated Setup: How to check for existing training files at boot so your program automatically skips the initial training prompt if data already exists.

  • Dynamic Training Management: How to interactively train new gestures on the fly ('t' key) or delete outdated gestures ('d' key) during runtime while automatically updating the saved file.

  • Robust Error Handling: Ensuring index tracking (trainIdx) safely syncs with live gesture arrays so pressing the spacebar never crashes your video feed.

Key Concepts Explained

1. Pickling Data Objects In MediaPipe gesture recognition, a trained gesture isn’t a complex neural network weight file; it’s simply a dictionary mapping a gesture name (string) to a list of normalized keypoint ratios (floating-point numbers). Python’s pickle module allows us to convert this dictionary into a byte stream and write it directly to a file (.pkl). When the program launches, pickle.load() reconstructs the dictionary in milliseconds.

2. Managing Execution Flow on Startup When gesture_data.pkl exists, our program automatically populates gestureNames with the keys from trainedData and sets trainIdx past the end of the array. This keeps the camera pipeline running in Inference Mode immediately. If no file exists, the script seamlessly drops into Training Setup Mode to prompt the user for initial inputs.

This is the code we develop in this video lesson:

Homework Assignment

Now that your Pi 5 can remember hand gestures across reboots, it’s time to bridge software recognition with real-world hardware control!

The Challenge: Integrate an SPI NeoPixel Ring (WS2812B/SK6812) with your gesture recognition code.

  • Map distinct hand signs to dynamic LED patterns (for example: Fist = Red Pulse, Open Palm = Bright White Beacon, Peace Sign = Dual Spinner, OK Sign = Rainbow Wheel).

  • Make sure your animation updates are smooth and non-blocking so your OpenCV camera frame rate doesn’t drop!

We want to see who in the community can build the most impressive physical light demonstration controlled entirely by hand gestures. Share your video results and code modifications in the comments below!

AI on the Edge LESSON 52: Gesture Recognition on the Raspberry Pi 5

Welcome back, everyone! In today’s lesson, AI on the Edge LESSON 52: Gesture Recognition on the Raspberry Pi 5, we are building a custom, real-time hand gesture recognition system from scratch. Up until now, we have been using MediaPipe to track keypoints, identify individual hand joints, and extract raw 3D coordinate data. But raw coordinates alone don’t tell the computer what your hand is actually doing. Today, we bridge that gap by teaching our Raspberry Pi 5 how to train on custom hand positions and dynamically classify live hand gestures using pure mathematics and vector geometry—no heavy neural network retraining required.

The core secret to making gesture recognition work reliably across different camera distances is scale-invariant distance normalization. If you simply measure the pixel distance between your fingertips and your wrist, bringing your hand closer to the camera lens will blow out those numbers and break your classifier. To solve this, our script establishes a baseline unit of measurement for every single frame: the distance between the wrist (landmark 0) and the index finger base joint (landmark 5). By dividing all measured finger-tip-to-wrist and tip-to-tip distances by this dynamic scale factor, the resulting feature vector remains identical whether your hand is two feet away or five feet away from the lens.

Once we extract this normalized 15-element feature vector—representing the spatial ratios between all five fingertips relative to the wrist and each other—we construct an interactive training phase directly inside the live video loop. The program prompts you in the terminal for the number of custom gestures you wish to record, along with their labels (such as “Peace”, “Thumbs Up”, or “Fist”). As you present each gesture to your camera feed and press the spacebar, the algorithm captures the instantaneous geometric signature of your hand and stores it in a runtime training dictionary.

During live inference, our classifier calculates the Sum of Absolute Errors (SAE), or Manhattan distance, between the live incoming feature vector and every stored profile in our training dataset. The function loops through all saved gestures to find the candidate with the absolute lowest cumulative error score. To prevent false positives when an untrained or messy hand pose is shown, we compare that lowest error score against a strict threshold value (maxErrorThreshold = 3.5). If the error falls within the allowable boundary, the matched gesture label is instantly displayed on the live OpenCV HUD; otherwise, the system safely defaults to “Unknown”.

We manage our camera feed using high-speed frame capture with Picamera2 running at 60 frames per second at 1280×720 resolution, processing hand detection with MediaPipe Hands, and rendering real-time performance diagnostics—including an exponential moving average FPS counter—directly onto the video output. Go ahead, study the methodology, load the concept onto your Raspberry Pi 5, grab a hot cup of coffee, and let’s get building!

 

Hand Recognition on the Raspberry Pi 5 With openCV and Mediapipe

This is a base program which allows you to use mediapipe on the Raspberry Pi 5 under openCV to identify each landmark on a hand. This program is important as we can see the index of each landmark. This will serve as the basis for our next program which will allow us to begin to do gesture recogntion.

 

AI on the Edge LESSON 51: Gesture Control of NeoPixel Ring

 

Welcome back, everyone! In today’s class, AI on the Edge LESSON 51: Gesture Control of NeoPixel Ring, we are bridging the gap between computer vision and physical hardware in a big way. Up until now, we have spent a lot of time tracking hands, plotting 3D landmarks, and rendering graphical user interfaces directly onto our camera feeds. But today, we take those virtual interactions and project them out into the real physical world using a 12-LED NeoPixel ring driven over SPI by our Raspberry Pi 5.

The core concept of this lesson is creating an intuitive, spatial gesture interface. Imagine looking at your monitor display where a graphical representation of a circular LED ring is overlaid onto your live camera feed. By extending your hand and placing your index finger tip over any of the twelve virtual LED nodes on screen, the system detects your hover position. When you pinch your thumb and index finger together, the program registers a toggle event, turning the corresponding physical LED on or off on the actual hardware ring sitting on your workbench.

To make this work reliably without wild bouncing or rapid flickering, we dive deep into the mechanics of gesture latching and debouncing. When a student first attempts spatial tracking, holding a pinch gesture over a target often causes the state to flip back and forth dozens of times per second. In this lesson, we implement a stateful boolean latch flag that locks down the trigger state the moment a pinch is registered. The algorithm strictly requires you to release the pinch—breaking contact between your thumb and index finger—before it will accept another command. This simple state machine logic is essential for turning noisy computer vision inputs into rock-solid physical control interfaces.

Beyond individual pixel control, we also construct a dynamic UI Mode Selection Panel on the right side of the screen. By hovering over the panel buttons and executing the same pinch gesture, you can cycle through five distinct lighting animation profiles in real time:

  • Static Mode: Displays fixed, custom-assigned palette colors for each active LED node.
  • Rainbow Mode: Distributes a static 360-degree color wheel spectrum across all twelve positions using HSV-to-RGB conversion algorithms.
  • Pulsate Mode: Modulates the physical brightness using a squared sine wave math function to guarantee a true black-floor fade on turned-on pixels.
  • Blink Mode: Synchronizes an on/off strobe animation derived from live system timestamps.
  • Running Rainbow Mode: Dynamically rotates the active hue spectrum around the ring by stepping the color offset frame-by-frame.

We handle all of this frame rate processing seamlessly using high-speed SPI bus communications through neopixel_spi and direct frame acquisition via Picamera2. By keeping auto-write disabled until all mathematical animation steps and hand-tracking calculations are completed for a given frame, we push smooth, flicker-free updates out to both the physical hardware and the OpenCV display overlay simultaneously.

Work through the complete Python script provided on this page, load it onto your Pi, and assemble your hardware circuit. Pay close attention to how the spatial math maps coordinates from normalized MediaPipe landmark spaces directly into circular screen coordinates using polar angle formulas. Grab your components, fire up your IDE, and let’s get building!

 

 

Making The World a Better Place One High Tech Project at a Time. Enjoy!