# Q-22: Detect a person in one image

Data-Driven Athletics tutorial · Week 8 · Chapter 8 · about 15 min · workflow steps: Gather, Statistics, Visualize

Web page: https://apopt.com/course/tutorials/q22-detect-person/ · Data: https://apopt.com/data/tutorials/q22-detect-person/

## The decision

Before an app can measure an athlete it has to find the athlete. When a clip has more than
one person in it, will the detector find the one you want, and how sure will it be?

## The raw data

- `street.png`: a street photo with six people, 1139 × 681 pixels; it shows faces, so it is linked, not published From the Data-Driven Engineering course page [Object Detection](https://apmonitor.com/dde/index.php/Main/ObjectDetection); downloaded from there, not copied here.

A pose model starts by finding the person. An **object detector** does only that first part:
it returns a box around each thing it recognizes, a class name ("person", "car", "sports
ball") and a confidence from 0 to 1. You will run one on a street photo from the
Data-Driven Engineering course, keep the result as a table, and draw the boxes without the
photo.

The first cell needs the `ultralytics` package, so it runs in a notebook on your computer
or in Colab, not in this page. The photo shows people's faces, so it stays where it was
downloaded; only the table of boxes is published.

*Predict first:* How many people are in the photo, and how many will the detector find?

```python
import os
import pandas as pd
from ultralytics import YOLO

model = YOLO("yolo26n.pt")                       # the smallest YOLO26 detector, 80 COCO classes
r = model("street.png", verbose=False, device="cpu")[0]
rows = [[model.names[int(c)], float(p), *map(float, b)]
        for c, p, b in zip(r.boxes.cls, r.boxes.conf, r.boxes.xyxy)]
det = pd.DataFrame(rows, columns=["label", "confidence", "x1", "y1", "x2", "y2"]).round(2)
os.makedirs("clean", exist_ok=True)
det.to_csv("clean/detections.csv", index=False)
print(f"image {r.orig_shape[1]} x {r.orig_shape[0]} pixels, {len(det)} boxes")
print(det.to_string(index=False))
```

Output:

```
image 1139 x 681 pixels, 9 boxes
   label  confidence     x1     y1      x2     y2
  person        0.90 922.12 128.68 1085.04 616.81
  person        0.87 797.97 170.25  913.73 618.89
     car        0.85  19.96 513.30  194.82 572.55
  person        0.80 464.34 283.63  575.44 620.40
  person        0.72 231.52   0.00  440.33 651.01
  person        0.69 595.24  42.60  746.30 632.57
     car        0.45 714.26 516.80  832.61 561.33
 handbag        0.38 442.12 398.71  513.59 488.81
airplane        0.32 450.71  60.71  605.37 109.84
```

Each row is one box: the class, the confidence, and the top-left (`x1`, `y1`) and
bottom-right (`x2`, `y2`) corners in pixels. As in every image, y grows **downward**.

### Count and gate

From here on, everything runs in this page from the table. Count the boxes by class, then
keep only the people the detector was reasonably sure of.

```python
import pandas as pd

det = pd.read_csv("clean/detections.csv")
print(det.groupby("label")["confidence"].agg(["count", "min", "max"]).round(2).to_string())
people = det[(det["label"] == "person") & (det["confidence"] >= 0.5)].copy()
people["height_px"] = people["y2"] - people["y1"]
print(f"people at confidence 0.5 or more: {len(people)}")
print(people[["confidence", "x1", "y1", "height_px"]].sort_values("x1").to_string(index=False))
```

Output:

```
          count   min   max
label                      
airplane      1  0.32  0.32
car           2  0.45  0.85
handbag       1  0.38  0.38
person        5  0.69  0.90
people at confidence 0.5 or more: 5
 confidence     x1     y1  height_px
       0.72 231.52   0.00     651.01
       0.80 464.34 283.63     336.77
       0.69 595.24  42.60     589.97
       0.87 797.97 170.25     448.64
       0.90 922.12 128.68     488.13
```

### Draw the boxes, not the photo

A drawing made from the table is the detector's view of the scene. Boxes the detector was
unsure of (below 0.5) are dashed.

```python
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

fig, ax = plt.subplots(figsize=(7, 4.2))
for _, b in det.iterrows():
    sure = b["confidence"] >= 0.5
    ax.add_patch(Rectangle((b["x1"], b["y1"]), b["x2"] - b["x1"], b["y2"] - b["y1"], fill=False,
                           lw=2 if b["label"] == "person" else 1, ls="-" if sure else "--",
                           color="black" if b["label"] == "person" else "gray"))
    ax.text(b["x1"], b["y1"] - 6, f"{b['label']} {b['confidence']:.2f}", fontsize=7)
ax.set(xlim=(0, 1139), ylim=(681, 0), xlabel="x (pixels)", ylabel="y (pixels, grows downward)")
ax.set_aspect("equal")
plt.tight_layout()
```

![Rectangles for the nine detected boxes on a 1139 by 681 pixel frame with the y axis pointing down: five tall person boxes across the frame, and smaller boxes for two cars, a handbag and an airplane, the last three dashed for confidence below 0.5.](https://apopt.com/course/tutorials/q22-detect-person/c05-1.png)

Compare the drawing with your prediction. The photo holds six people and the detector
returns five boxes labelled "person". The sixth, a woman standing half hidden behind the man
on the left, gets no box: that is **occlusion**, the first failure in Chapter 8's table. The
box of the man on the left starts at y = 0 because he is cut off by the top of the frame,
so its height (651 px) is not his full height. The box heights already show who is near the
camera and who is far: the same pixel does not stand for the same distance across the photo,
the scale problem of Chapter 8. The bus is called a "car" (0.45), only one of the bags is
found, and the plane is found but with the lowest score of all (0.32). (The Data-Driven
Engineering page, with an older detector, misses the plane.)

The running app keeps only the single most confident person whose score is above 0.25 in each
frame, so in a clip with a coach or teammate in view it can follow the wrong person.

**For the athlete:** film alone in the frame, or with others well behind you, so the app
measures you and not someone else.

## With your own data

Take one photo of yourself with a phone, whole body in view, and run the first cell on it with
your file name. Keep the photo on your computer; the table of boxes shows no one.

## The same method in another field

The same detector counts parts on a conveyor or vehicles at an intersection; the
Data-Driven Engineering page on [object detection](https://apmonitor.com/dde/index.php/Main/ObjectDetection)
runs it on this photo and on a video.

## Acknowledgements

Photo and the original exercise from the Data-Driven Engineering course. Detection uses
Ultralytics YOLO (AGPL-3.0).

## Action card

- **Finding:** The detector found five of six people; the one it missed was half hidden behind another.
- **Evidence:** Five "person" boxes at confidence 0.69 to 0.90; no box for the partly hidden person.
- **Sure:** High for this photo; one image says nothing about your clip's lighting or framing.
- **Action:** Film alone in the frame, whole body visible, with nobody between you and the camera.
- **Retest:** Check the first frame of each new clip for a single, complete person box.

## References

- Data-Driven Engineering: [Object Detection](https://apmonitor.com/dde/index.php/Main/ObjectDetection).
- Ultralytics YOLO documentation: [object detection](https://docs.ultralytics.com/tasks/detect/).

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
