This project originated at a hackathon focused on applying machine learning to social environments. The initial concept was simple: build a real-time spatial tracker for cup pong. We quickly realised the scope was too technically demanding for a 24-hour window. However, the core idea stayed with me. I decided to tackle it properly by building the complete pipeline from scratch as an engineering side-project alongside my part-time role as a Full-Stack Software Engineer.
This article is written completely by a human (me) and proof-read for typos by AI. Source code available on GitHub. Also check out my LinkedIn. The project itself marks a strong milestone in my academic and professional career shift towards AI/ML engineering.
What I have created is a framerate invariant stereo trajectory tracker and ballistic flight path reconstructor. You set up two cameras, one perpendicular to the cup pong table, the other preferably in a ~45 degree angle. You then calibrate the cameras, first to get approximate projection matrices, and then a joint calibration to refine the matrices. You set the program to record and play a cup pong game. Afterwards you process it and analyse it in the visualiser.
It features pose estimation using YOLO26, time-series machine learning analysis using a stacked GRU neural network, background subtraction using MOG2, hybrid motion masks, contour circularity estimation, PnP-mapping from Homography matrices, focal length estimation from homography, joint camera calibration, finger detection via MediaPipe, impulse based temporal alignment and stereo triangulation.
The project is implemented in python and libraries were used extensively. Most notable include OpenCV, PyTorch, MediaPipe and pillow. There’s also a small visualiser module built with React and Three.js for a one-to-one 3D reconstruction of the scene.
I will go over the important features and parts of the program in the following order:
- Introduction and constraints
- Pingpong ball tracking
- Throw detection
- Single camera trajectory tracking
- Stereo tracking: Camera calibration
- Stereo tracking: Trajectory reconstruction
- Temporal desynchronisation
- Putting it all together
Introduction and Constraints: unreliable hardware
Constraints are what make the problem. There are already countless pingpong ball trackers built, but what makes this one unique is my specific set of constraints.
Variable frame-rate capturing devices
Developing this project my dual-camera setup consisted of my MacBook front camera and iPhone back camera. The most prominent issue with this setup is the unreliable frame-rate of the iPhone front camera. iPhone cameras have an auto-exposure feature which can change frame rate slightly on the fly, which was triggered by the shadow of the thrower moving around the scene. This made the clips notoriously difficult to sync up properly. I do realise this could have been solved by buying a stable FPS webcam or using an app on the phone like Blackmagic camera, but I decided to take on the challenge.
Rolling shutter and motion blur
Another problem that stems from poor sensory equipment is motion blur. A ball moving at 6 m/s in front of a 30 FPS rolling shutter camera is not a perfect ball. It’s a blurry mess, representing more an oval, almost like a rectangle with rounded corners.
Light ball on light background
“Why don’t you just use a bright colour ball?”, Because it’s boring. You can’t always adjust the environment to your liking. At the start of the project I had a full-white ball, but I had to colour it to very light green, because tracking a white ball on a white wall without shadows consistently is impossible.
End goal. Accurate ballistic trajectories from noisy sensory data
Pingpong ball position tracking: Framediff and MOG2 with contour circularity detection
Building a proper motion mask
I initially began by creating a motion mask using simple frame differentiation by taking the absolute pixel-wise difference between the last two frames. Even with a brightness boost before the motion mask threshold cutoff, the method was not accurate enough.
So I later experimented with a sliding window pixel-wise mean of the 5–20 most recent frames as reference to subtract the current frame from, but saw little to no improvement. The real gains came from switching to a more stable and established background subtractor: Mixture of Gaussians 2 (MOG2). It’s a statistical, computationally highly efficient background model which even comes with shadow subtraction.
Towards the very end I realised when analysing that the morphological close I applied to my MOG2 mask was sometimes cleaning the ball out, especially on the secondary camera with an angle. A smaller kernel didn’t help either. MOG2 was sometimes “too accurate” to capture the motion blurred mess of a ball.
I noticed during testing that the motionmask created by framediff was often more resilient to the morphological operations. I tried a hybrid approach by taking the bitwise-or from the post-morphological operation bitmasks and got unparalleled accuracy. To bridge the masks together, I then applied a morphological closing. This is what I ended up going with.
We still miss the ball on some frames. Sensory noise is inevitable
Ball detection from motion mask
To detect a ball from a motion mask, you need to look at the shapes. The outlines of the shapes in the motion mask are called contours. OpenCV comes with a contour detection method which I used to get the outlines of the shapes in the motion mask.
To check if the outlines are those of a circular object like a ball, you can check for the circularity of the contours. My initial idea of fitting a circumscribed circle in the middle of the contour and calculating the difference between the area of the contour and the area of the circle failed on motion blur stretching the ball too wide. I then ended up reading about the isoperimetric quotient Q, which describes the ratio of the area of the contour and a circle with equal perimeter, not width. This works way better with stretched circle shapes.
Where A is the area of the contour and L its perimeter. This ended up working very well. A perfect circle contour now gets a Q of 1, which means we can instantly discard contours that get a Q below a certain threshold.
It detects a ball on almost every frame. We will address this later with a state machine.
Throw detection using YOLO and GRU
To detect a throw you must first detect or estimate the pose. My throw detection pipeline starts with the lightest YOLO model meant for edge deployment: yolo26n-pose, which gives me access to the screen-space coordinates of 17 key points, of which I’m interested in 8: left and right wrists, elbows, shoulders and hips.
A cup pong throw happens with one hand, the one which is closer to the middle of the table. So to detect a throw, we can only look at the coordinates of the hand which is closer to the middle of the table, call it the dominant hand. Since the throwing movement is not too complex, I could’ve probably used a clever algorithm to detect it, but that’s boring and unreliable so I decided to fit a machine learning model to a sliding-window of pose estimations to learn the organic movement of a throw.
Normalising the pose
Feeding raw screen-space coordinates to a machine learning model doesn’t work. It violates translation invariance and scale invariance, meaning that the position and relative size of the thrower on the screen greatly influences the model’s inference. This means the normalisation step in our throw detection pipeline must account for three variables: the thrower’s horizontal screen-space position, the shifting distance between the camera and the table, and the physical size of the thrower.
To tackle translation invariance, I anchored the elbow and wrist positions to the shoulder position. The dominant shoulder is now always at (0, 0) and the positions of dominant elbow and wrist are relative to the dominant shoulder position which means the horizontal screen position of the thrower is no longer a factor in throw detection.
To tackle scale invariance, I divided the relative dominant wrist and elbow position vectors by the torso length, which I calculated by subtracting the screen-space dominant hip position from the dominant elbow position.
Pose drawn, torso visualised
After these two normalisation steps the feature vector shrunk by 2 because there is no point in feeding constant zeros (relative dominant shoulder coordinates) to a neural network. We will only be feeding it the normalised dominant wrist and dominant elbow coordinates.
Machine learning to detect a throw
As we are dealing with time-series data, I turned my head towards Recurrent Neural Networks (RNNs). I was worried that a traditional vanilla RNN would struggle with exploding/vanishing gradients with longer throws and pumping movements. I arrived at two possible models: Gated Recurrent Unit (GRU) and Long Short-Term Memory (LSTM). Both models sustain a hidden internal state using gates to more accurately capture dependencies.
I ended up going with GRU. It’s lighter and more performant which is crucial for online inference, and almost two decades more modern than LSTM, which technically allows to capture more complex relationships, but we don’t really have a need for that. GRU also has 25% fewer parameters making it less prone to overfitting on small datasets which really matters here as we will soon see.
After some experimentation I arrived at having two stacked GRU layers of size 64 to allow the model to capture throw events accurately, avoid overfitting and minimise false positives. The latter GRU layer then feeds to a final linear projection that maps it down to a single logit. A positive value for this logit indicates a throw is happening. I actually arrived at reversing the logit back to a probability via the sigmoid function and labelling a frame as 1 when the probability was over 0.75
The inference shows a positive label just as we are throwing
The characteristic “pump fake” motion before the actual throw turned out to be almost impossible to filter out, but this architecture allowed me to at least capture all actual throws and get an almost zero false negative rate. I then later filtered pump fake false positives via trajectory tracking state machine logic.
Training the network
I didn’t want to spend a whole day recording throws and labelling frames, so I ended up recording only 20 throws. Using my custom made labeller I labeled frames as 1 from the very first frame-of-acceleration of the actual throw to the frame of ball release. This way I ended up getting around 150 positive labels, but around 8 times more negative labels. To prevent the model from being 80% accurate by always guessing zero, I gave positive labels a weight of 5, which means mispredicting a one as zero carried 5 times more weight than the other way round.
Single camera trajectory tracking
I approached this task via a state machine with 3 states: detecting a throw, scanning for the ball, tracking the ball. When we get a positive label from the GRU, we start scanning for the ball in the expected area. If and once we find the ball in that area, we start tracking the ball and recording its position each frame until it bounces or goes off the frame.
When we do detect a throw, we should scan for circular contours at the front of the wrist position. For this I use a 120 degree sector directed towards the centre of the screen with a specified radius positioned at the dominant wrist. If we detect the ball in this area, we enter the ball tracking state. Each frame we record the position and move the sector to the current position to look for the ball next frame.
Once we record a throw with enough sample points, we fit a parabola to it and start looking for a throw again. I noticed the first sample point was often recorded 2–3 frames after ball release. To mitigate this I implemented a small backtracking algorithm that prepended to the sample list the release frame. To do this I extrapolated the trajectory backwards until it was very close to a recorded palm position (vector from elbow to wrist multiplied by 1.35).
Stereo triangulation: Camera calibration
When stereo triangulating a ball position from two cameras, you need to know the relative positions and rotations of the cameras. I decided to place the origin of my 3D world to the table plane centre position. I would then place the primary camera perpendicular to the table length axis, and my secondary camera to about 45 degree angle.
Note: We assume a Pinhole camera model for both cameras. I can do this because both of my cameras aggressively correct for radial lens distortion at the hardware level.
Starting the project I had the idea of manually measuring the distances and angles, forming their translation and rotation matrices programmatically to get the necessary 3D space projection matrices for triangulation. While doing the research on it, I stumbled upon Perspective-n-point (PnP) mapping. I realised I can skip the manual measuring altogether with a more robust method, only having to measure the table dimensions.
We click each corner for both cameras in the same order, and straighten the lines using the visual guidelines
Since the four table corners are coplanar and have known 3D positions, we can click each corner to associate the corner 3D position with its 2D pixel to compute the Homography Matrix (H), which we decompose into the cameras precise translation (t) and rotation (R) which we combine to get the Extrinsic matrix: E = [R | t]
To deal with PnP reflection ambiguity in my homography calculations (Homography matrix always has 4 correct solutions), I enforce a positive depth constraint (z-component of translation vector must be positive) and a positive camera z-component, meaning the camera is assumed to never be under the table.
I also estimate the Intrinsic Matrix (K) from the Homography matrix. We only need to find the focal length because we assume all pixels are square and the optical axis are centred on the screen. I calculate it by applying the orthogonality constraints of the perpendicular table edges and solving the resulting equation for focal length. After the complicated math, we get an equation like this:
I was not able to figure out the math completely on my own. This article helped me a lot, and might help you also. One thing to note is that since our pixels are assumed to be square, we can say f₁ = f₀

A visualiser to verify calibration was successful. Also an accurate visualisation of my setup.
We can then calculate the projection matrix (P) by simply multiplying Extrinsic and Intrinsic matrices together P = EK. We repeat this process for both cameras to get their projection matrices. It’s important we click the four corners in both cameras in the same order so the matrices stay aligned.
Later while improving accuracy, I implemented a joint calibration method using MediaPipe finger detection. The user holds their finger on each of the corners for a few seconds at a time. We do this after the manual calibration. By holding the finger on the same corner, both camera feeds register the exact location of the same corner, which means the projection matrices are jointly in sync also. This allows us to refine calibration accuracy beyond that which a human can do by clicking the corners on separate camera feeds.
Each camera maps the corners exact positions to the exact same world space coordinates
Stereo triangulation: Trajectory reconstruction
We have two separate single camera trajectory trackers, and we need those state machines to be in sync. To do it I treat them as a single state machine and add one more state to both of them: awaiting partner. We need the extra state because of severe temporal desynchronising, which I will touch on later.
Once we have collected the sample points from both cameras, we triangulate the timestamp-matched points from both feeds into 3D points using our calibrated projection matrices. I fit two types of trajectories to the 3D points: A ballistic trajectory and a space curve. The space curve allows to gauge more easily the real detected flight path of the ball, and the ballistic trajectory can be used for the projectile animation later.
We track the ball on both cameras and timestamp the observations
It is also noteworthy that when pairing the 3D points, I used the absolute timestamps of the 3D observations. In other words, the positions are very accurate because the varying framerate has no effect on it. Both curves are also functions of absolute time.
Temporal Desynchronisation on consumer hardware
My hybrid motion mask strategy + yolo pose inference made online inference unfeasible at 30FPS, so I had to record the throws and cup pong games and process them offline. This introduces a challenge due to the variable frame rate of my secondary camera, which often recorded 10–15% less frames in the same time due to auto-exposure and auto-framerate.
The hybrid motion masks for a dual-camera setup are too expensive to run 30fps on my laptop.
While writing this, I found out I actually could switch my secondary camera to a stable framerate (still dropping around 10 frames per minute) with auto-exposure being a massively smaller nuisance. However, what I have created is a framerate invariant system where the two cameras can record at different arbitrary and/or non-stable frame rates while reconstructing a precise and smooth 3D ballistic trajectory from the flight path. In the end I think it’s much more impressive and made the project way more insightful and challenging.
Solving temporal desync on unstable framerates
Both camera frame consumers run on their own threads. When they capture a frame, they also capture the exact timestamp and associate it with the frame index. These timestamp-frameindex sidecars are then concatenated into one master stereo timeline after recording, which contains a timestamp and each cameras native frame at that timestamp.
To construct the master stereo timeline, we greedily pair frames based on a tolerance calculated from the actual average frame time halved. If the frame timestamp delta is below tolerance, stereo timeline advances both feeds. If one camera frame timestamp is more than tolerance-level early, it holds its native frame and only the other advances in the next master timeline slot.
When triangulating the throws, we use absolute timestamps of the observations instead of simple framematching.
Solving temporal desync on stable framerates
Even on stable framerates, the cameras aren’t in perfect sync. This systematic error is caused by one camera starting before the other. Before they start recording a movie scene, they use a tool called clapperboard by clapping the jaws together to sync audio (clap sound) and video (jaws colliding). I was inspired by this approach and settled on syncing the two video feeds from a ball bounce.
When the ball is dropped straight down, we start recording the ball positions. We track the balls trajectory and extrapolate the exact timestamp of collision with the table. Since the bounce happens at the exact same moment on both cameras, we can calculate the precise frame delay down to a subframe level.
I ended up not wiring this module up to anything else than this standalone filter because even with stable framerates one of my cameras was dropping frames. It still works given that you have two cameras that don’t drop frames and record at the exact same frame rate.
Putting it all together: Stereo tracking of complete games
So far everything is implemented assuming the player is on the right of the main camera. To get a 2-player game tracked, we need to mirror some of the logic to work for the other side also. I will skip over it as its only minor programmatic changes. Perhaps the most noteworthy change is that we need to mirror the coordinates for GRU inference because we don’t want to teach a bidirectional throw detector. We also batch the YOLO inference
In many parts of the game tracker the main camera is responsible for orchestration. For example, GRU inference is only ever run on main camera, and secondary camera enters the scanning ball phase on trajectory tracking once main camera gives a signal. Same goes for palm position backtracking, where the secondary camera is walked backwards as much as main camera.
To put it all together, I implemented a lightweight browser-based game visualiser where each throw, the table and each camera is rendered on a one-to-one 3D scene built on Three.js. I even implemented a little physics-based simulated recreation of the ballistic trajectory of each throw, running off of only the ballistic initials.
All code can be found on GitHub. Also check my LinkedIn.
Physics simulation based on ballistic intials.
