Draw in the Air: The Magic Behind GhostPen
Computer vision is often taught through boring tutorials: 'detecting a face in an image' or 'reading a license plate.' I wanted to build something inherently magical.
Enter GhostPen: an application that tracks your hand in real-time, recognizes your index finger, and draws a glowing line on the screen exactly where you point in thin air. No gloves, no sensors, just your webcam and raw Python.
Here is how you can build the core logic yourself.
The Tech Stack: Lean and Fast
Real-time processing requires minimal overhead. I chose:
cv2): For capturing webcam frames and drawing the interface.Understanding MediaPipe Hand Tracking
MediaPipe doesn't just find your hand; it maps 21 specific 3D landmarks (knuckles and joints).
For GhostPen to work, I only care about two specific points:
Landmark 8: The Tip of the Index Finger.Landmark 12: The Tip of the Middle Finger.If both fingers are up = Selection Mode (moving the hand around).
If only the index finger is up = Drawing Mode (painting on the screen).
The Drawing Logic: Connecting the Dots
If you just spawn a dot every time the index finger moves, you get a dotted line if the user moves their hand too fast. To create a smooth stroke, we must draw a line from the previous frame's coordinate to the current frame's coordinate.
`python
if drawing_mode:
if xp == 0 and yp == 0:
xp, yp = x1, y1 # Initialize coordinates
# Draw a line from previous (xp, yp) to current (x1, y1)
cv2.line(img, (xp, yp), (x1, y1), color, brush_thickness)
xp, yp = x1, y1 # Update for the next frame
`
The Canvas Problem
If you draw directly on the webcam image, the drawing disappears on the next frame because the webcam provides a brand-new, clean image 30 times a second.
The solution? Create a separate imgCanvas filled with black. We draw all the lines on this black canvas. Then, at the end of every loop, we blend the imgCanvas with the real webcam feed using bitwise operations: cv2.addWeighted().
Why Side Projects Like This Matter
GhostPen is fun, but it teaches fundamental concepts: loop optimization, array masking, state machines, and real-time performance tuning.
When I am asked in interviews about algorithmic efficiency, I don't recite textbook definitions. I talk about how I pushed GhostPen from 15fps to 60fps by optimizing matrix operations.
Code is just tools. What you build with them is entirely up to your imagination.
