Tag Archives: Artificial intelligence

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

Welcome back, everyone! In this lesson, we take edge AI interactivity to the next level. Up until now, we have learned how to track hand landmarks, extract pixel coordinates, and calculate distances using MediaPipe. Today, we put all those building blocks together into a self-contained, real-time hand gesture recognition system running on the Raspberry Pi 5.

We are not relying on a black-box pre-trained gesture model. Instead, we write our own mathematical feature extractor, train our custom hand poses on the fly, save those gesture profiles directly to disk, and map each gesture to a non-blocking lighting animation on a NeoPixel LED ring driven over SPI.

System Architecture Overview

The system operates in three distinct phases running simultaneously inside our main loop:

  1. Normalized Feature Extraction: MediaPipe extracts 3D hand landmark coordinates. To make gesture detection scale-invariant and distance-invariant, we normalize the distances between the fingertips and the wrist against a reference palm dimension.

  2. Nearest-Neighbor Gesture Matching: Live distance vectors are compared against stored gesture profiles using a mean absolute error algorithm. If the error falls below our maximum threshold, the gesture is identified; otherwise, it defaults to “Unknown.”

  3. Non-Blocking Hardware Animation Dispatch: The recognized gesture string triggers corresponding pattern functions on the 12-LED NeoPixel ring via neopixel_spi. Animations use non-blocking time delta checks to preserve high camera preview frame rates.

Gesture-to-Hardware Animation Mapping

Our script contains predefined animation routines mapped to recognized gesture strings. Here is how each pose controls the LED ring:

Recognized Gesture LED Animation Pattern Visual Effect
fist Red Pulse Sinusoidal breathing effect fading in and out
palm Solid Beacon Full brightness white ring
peace Dual Spinner Dual green and blue dots rotating over a dim red background
thumbsup Solid Success Constant green feedback
point Radar Sweep A green trailing dot chasing around a red ring
rock Cyan Flame Sinusoidal green-cyan intensity modulation
ok Rainbow Wheel Rotating HSV spectrum cycle
Unknown / Unmatched Clear LEDs turn completely off

Interactive Keyboard Controls

While the camera loop is active, you can interact with the system using your keyboard in the preview window:

  • Spacebar: Captures the current hand pose’s normalized distance vector, assigns it to the active target gesture name, and saves the updated dataset to gestureNEOPIXEL.pkl.

  • t: Prompts the terminal to add a new custom gesture name to your training queue dynamically.

  • d: Prompts the terminal to delete a specific gesture profile from the saved dataset.

  • q: Clears the NeoPixel ring, closes the camera pipeline, saves training data, and terminates the program cleanly.

Hardware Wiring Reference

Ensure your Raspberry Pi 5 SPI interface is enabled before running the code (sudo raspi-config -> Interface Options -> SPI).

  • NeoPixel Data Input (DIN): Connect to GPIO 10 (SPI0 MOSI / Pin 19).

  • NeoPixel Ground: Connect to any GND pin on the Pi expansion header.

  • NeoPixel Power: Connect to an external 5V power supply (ensure a shared ground with the Raspberry Pi).

Homework Challenge

Now that you have a working gesture recognition system linked to hardware animations, try adding your own custom gestures! Train a brand-new gesture pose (like a “three-finger count”), write a corresponding non-blocking animation function in updateNeoPixels(), and share your video results.

Here is the code we developed in the video lesson:

Homework & Next Steps

Try setting up the circuit and running the code on your Raspberry Pi 5. Observe how the frame rate behaves when driving both the camera preview, the hand-tracking model, and the I2C OLED display simultaneously. For your homework, extend this script to include a dynamic color slider or gesture-based brightness control!

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 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!

 

 

AI on the Edge LESSON 49: Live Animated Avatars on the SSD1306 OLED With OpenCV

Hey everybody! Welcome back to the AI on the Edge series!

In Lesson 49, we’re doing something that’s just plain cool — we’re turning that tiny little SSD1306 OLED into a live animated avatar that follows your face and hands in real time!

That’s right — no more static images, and no more being tethered to your desktop and monitor. This time your OLED is alive! Move your head, smile, raise your eyebrows, wave your hands… and the little display instantly mirrors your movements like a miniature digital twin. It’s like having a tiny version of yourself living on that 128×64 screen!

What You’ll Learn in This Lesson:

  • How to use MediaPipe Face Mesh to track 468 facial landmarks
  • How to combine it with Hand Tracking at the same time
  • The trick to projecting those landmarks onto a tiny OLED in real time
  • How to draw both points and connecting lines to create smooth, animated avatars
  • How to keep everything running fast on the Raspberry Pi

This is one of those projects that makes people stop and say “Wait… how is that even possible on that little screen?!”

By the end of this lesson, you’ll have a foundation for building all kinds of fun real-time avatar projects — everything from simple face mirrors to gesture-controlled characters and beyond.

Why This Is Awesome:

We’re not just displaying video on the big screen anymore — we’re compressing all that AI power down onto a cheap little OLED. This is real AI on the Edge stuff, and it looks incredibly impressive for how simple the hardware is.

Whether you want to build interactive displays, robot faces, wearable tech, or just blow your friends’ minds, this lesson gives you the core technique to make it happen.


Ready to make your OLED come alive?

Fire up the code, run it, and watch your tiny digital self start moving with you. Then start experimenting! Try drawing just the eyes and mouth, or just the hands, or maybe even turn it into a little stick figure avatar.

As always, I want to see what you create with this! Drop your versions in the comments or tag me — I love seeing the creative stuff you guys come up with. Don’t just copy and paste my code. Show you really understand the video by making the code yout own.

Enough talk, lets get this party started!

 

AI on the Edge LESSON 46: Ultimate Dazzleing Running Rainbow On a NeoPixel Ring

In this lesson we create one of the most beautiful and satisfying NeoPixel effects — a smooth, continuous, running rainbow on a 12-LED ring. We affectionately have named this pattern the “Runbow”. This is the “ultimate” version because it is both visually stunning and highly educational, as we explore two fundamentally different programming approaches the Runbow.
The first method is the most intuitive: we place a fixed rainbow across the ring (each LED gets a different hue equally spaced around the color wheel) and then simply rotate the entire pattern one position at a time. This approach is easy to understand because it mimics physically moving a colorful wheel. We save the color of the first pixel, shift all the other pixels one place, and then place the saved color at the end. It feels like a conveyor belt of color circling around the ring.
The second method is more elegant and mathematically pure. Instead of storing and shifting colors, we recalculate the color of every LED on every frame using a moving offset. For each LED we compute its hue as (i / LED_COUNT + offset) % 1.0, where i is the LED’s position and offset is a value that slowly increases over time. This creates a perfectly smooth rainbow that flows around the ring without ever shifting raw RGB values. Because we regenerate the pattern fresh each cycle, there is no risk of color corruption or accumulated errors.
Both techniques produce a gorgeous running rainbow, but they teach very different programming mindsets. The first method helps you deeply understand array manipulation and data movement. The second method introduces the powerful concept of using mathematics and offsets to create motion — a technique used frequently in advanced LED animations, games, and visual effects. In the end, the offset method tends to look smoother and is easier to extend with additional effects (such as brightness pulsing), but both approaches are valuable skills for any embedded AI or IoT developer working with addressable LEDs.You can adjust the speed of the rainbow by changing how much you increment the offset each loop or by modifying the delay. Once you master these two methods, you will be able to create almost any animated pattern you can imagine on your NeoPixel ring. Lets get this party started!
Here is the code we developed in this video:

This is the schematic we are using to connect the NeoPixel ring:

NeoPixel
NeoPixel Schematic