📚 Course contents
AI & Computer Vision, lesson 32 of 52
Zone Detection & Spatial Logic
Introduction
Lots of football questions are really questions about places: is anyone in the penalty box? How long did the defence spend in its own half? Is that attacker past the last defender? Today you'll draw zones on the pitch, teach the computer to tell whether a point is inside a shape, and use that to count, alert and even make a rough offside call.
By the end of this lesson you'll be able to:
- Represent a zone as a polygon (a list of corner points)
- Explain the ray casting idea behind the point-in-polygon test
- Draw zones on a frame, save them to a file and load them back
- Use zones in a trigger and in a statistic (time in zone)
- Explain why a simple offside rule is only an approximation
Working principle
Why a rectangle isn't enough
In lesson 31 the goal was a rectangle x, y, w, h. Real zones are not rectangles in the picture: the camera looks at an angle, so a rectangular goal becomes a trapezoid. A polygon (a list of corners) can describe any shape, including the L-shaped ones that appear when two areas overlap.
The point-in-polygon test (ray casting)
For one point, look at every edge of the polygon. Ask: does the edge cross the horizontal line through my point, and is the crossing to my right? Count the crossings. Odd means inside.
The ray crosses 1 edge: odd, so the point is inside the zone.
Two details make it work: the test (y1 > y) != (y2 > y) handles the corners without double counting, and the same code works for concave shapes (the notch of an L).
Which point of the player?
A bounding box is a rectangle around a player, but a position is a point. Use the feet (bottom middle of the box). The feet touch the pitch; the box centre floats in the air. This was fixed in the lesson 30 data contract: x, y is the feet.
Zones can overlap
The penalty box is also part of the left half. Return every zone that contains the point, not just the first.
Using zones
| Use | Example |
|---|---|
| Trigger | Ball in the goal zone (lesson 31) |
| Statistic | Seconds each player spends in each zone |
| Rule | A player in the penalty box when the ball arrives |
| Heatmap (lesson 41) | Which cells of a grid are busiest |
The offside line (simplified)
The line sits at the second-last defender (the keeper counts as one). An attacker is offside if they are ahead of the line and ahead of the ball. Our version works along the x-axis only. It does not handle the arms rule, whether the player is involved in play, or camera perspective. The lesson uses it as a thinking exercise, not a referee. lesson 33 fixes the perspective problem.
Zones live in pixels, for now
Everything today uses picture coordinates. If the camera moves, the zones are wrong. A tripod, and a note of where it stood (lesson 28), makes them stay right. lesson 33 moves everything onto a flat top-down pitch.

