# How to Configure AI Video Surveillance Without False Alarms: Zones, Confidence Thresholds and Alert Testing

> AI Release · @ai_releaseorg · https://ai-release.org/guides/kak-nastroit-ii-videonablyudenie-bez-lozhnyh-trevog-zon_en.html

## TL;DR

- **Time to complete:** ~90 minutes of configuration plus one 24-hour observation window
- **Difficulty:** Intermediate
- **You will need:** an IP camera with RTSP and ONVIF support on a fixed IP, an NVR/detector that supports polygon zones and per-object score filters, an MQTT broker (Mosquitto), `ffmpeg`/`ffprobe`, `mosquitto-clients`, `jq`, `python3`, a PoE switch or 12 V PSU, and free disk space for at least 24 hours of event clips.

## Requirements and setup
![Illustration: Requirements and setup](https://ai-release.org/guides/img/kak-nastroit-ii-videonablyudenie-bez-lozhnyh-trevog-zon-en-1.jpg?v=1795164952)


- **Camera:** RTSP URL of the main stream, a separate lower-resolution substream for detection, a static IP or DHCP reservation.
- **Detector/NVR:** software that runs the object model and exposes zones plus confidence filters. The examples below follow the config layout of the open-source NVR **Frigate**; field names change between releases — check the documentation for the exact version you install.
- **Broker:** Mosquitto reachable on port `1883` from the detector host, with a dedicated user (not anonymous access).
- **Client tools on your workstation:**

```bash
sudo apt install -y ffmpeg mosquitto-clients jq python3
ffprobe -version | head -n 1
```

- **Access:** read/write to the detector's config directory (e.g. `/opt/frigate/config/config.yml`), admin login on the camera web UI.
- **Pre-flight checklist:**

- [ ] Camera clock synced to the same NTP source as the NVR (`timedatectl` shows `System clock synchronized: yes`)
- [ ] RTSP password contains no `@`, `:` or `/` — or is URL-encoded
- [ ] Substream resolution and FPS noted (you will reuse these numbers in the config)
- [ ] Broker credentials tested before touching camera config
- [ ] At least 20 GB free for event recordings

## Step 1. Verify the stream, time sync, and scene baseline

**What to do:** confirm the camera delivers a decodable stream over TCP before any detection config exists.

```bash
ffprobe -v error -rtsp_transport tcp -select_streams v:0 \
  -show_entries stream=codec_name,width,height,avg_frame_rate \
  -of default=noprint_wrappers=1 \
  "rtsp://viewer:<camera-password>@192.168.1.50:554/stream1"
```

**Example output (success):**

```
codec_name=h264
width=1920
height=1080
avg_frame_rate=25/1
```

If `codec_name` is `hevc`, check whether your detector build decodes H.265 — many setups use the H.264 substream for detection instead.

**Why:** every later step (zones, scores, alerts) depends on a stable, TCP-transported stream. UDP packet loss produces dropped frames, and dropped frames look exactly like "detection missed the person".

Then lock the time base — a wrong clock makes correlating alert logs with reality impossible:

```bash
timedatectl
```

Expected: `System clock synchronized: yes` and `NTP service: active`.

Next, capture a baseline and inspect it. Save one daytime frame and one night frame from the exact camera position:

```bash
ffmpeg -rtsp_transport tcp -i "rtsp://viewer:<camera-password>@192.168.1.50:554/stream1" \
  -frames:v 1 day_baseline.jpg -y
```

**Why:** you need to see what the model sees. Trees, moving shadows, a swaying flag, a reflective wall under IR — these are the physical sources of most false alerts, and they must be excluded by mask or by zone, not by raising the score until real visitors disappear.

**How to check:** open `day_baseline.jpg` and repeat the capture after dark (`night_baseline.jpg`). If the night frame is dominated by an IR hotspot, plan a motion mask over that region now:

```yaml
# config.yml — ignore the timestamp overlay and the IR hotspot
motion:
  mask:
    - 0.000,0.000,1.000,0.000,1.000,0.120,0.000,0.120
    - 0.780,0.150,1.000,0.150,1.000,0.330,0.780,0.330
```

Coordinates are normalized: `0,0` is the top-left corner, `1,1` the bottom-right, values are separated by commas in `x,y` pairs. This works because masking happens before motion scoring, so a flickering IR reflection never starts a track.

## Step 2. Draw zones and set confidence thresholds
![Illustration: Step 2. Draw zones and set confidence thresholds](https://ai-release.org/guides/img/kak-nastroit-ii-videonablyudenie-bez-lozhnyh-trevog-zon-en-2.jpg?v=1795164959)


**What to do:** convert the pixel polygon you drew on the snapshot into normalized coordinates, then attach it to the camera config together with score and area filters.

```python
# pixel points -> normalized polygon for a 1280x720 detect stream
W, H = 1280, 720
pixels = [(410, 250), (880, 250), (980, 700), (300, 700)]
print(",".join(f"{x/W:.3f},{y/H:.3f}" for x, y in pixels))
```

**Example output:**

```
0.320,0.347,0.688,0.347,0.766,0.972,0.234,0.972
```

**Why:** the detector evaluates every frame at its own detection resolution, not at the camera's native one — normalized coordinates stay valid when you later change `detect.width`/`detect.height`.

Now the config. Use a substream for detection, keep tracking to the two labels you actually care about, and give the score two roles: `min_score` starts a track, `threshold` confirms it as a real event.

```yaml
mqtt:
  host: 192.168.1.10
  port: 1883
  user: mqttuser
  password: "<mqtt-password>"

detect:
  width: 1280
  height: 720
  fps: 5

objects:
  track: [person, car]
  filters:
    person:
      min_area: 4000
      max_area: 120000
      min_score: 0.55
      threshold: 0.70

cameras:
  front_door:
    ffmpeg:
      inputs:
        - path: "rtsp://viewer:<camera-password>@192.168.1.50:554/stream1"
          roles: [detect, record]
    zones:
      driveway:
        coordinates: 0.320,0.347,0.688,0.347,0.766,0.972,0.234,0.972
        objects: [person, car]
      street:
        coordinates: 0.000,0.000,1.000,0.000,1.000,0.300,0.000,0.300
        objects: []
    review:
      alerts:
        required_zones: [driveway]
```

Rules of thumb for the numbers: raise `min_score` when you get hits on shadows and empty pavement; raise `threshold` when alerts appear but the box flickers off within a second; set `min_area` to roughly the pixel area of a person at the far edge of the zone, so a cat or a distant pedestrian on the sidewalk stops qualifying. Assigning `objects: []` to the `street` zone tells the detector "this area exists but must never raise an alert", which is how you silence public road traffic without masking it (masking would also hide the context needed to confirm a real approach).

**Example:** a person walking up the driveway enters `driveway` → one `new` event with `score` above `0.70`; a car passing on the road enters only `street` → event created but suppressed by `required_zones`.

**How to check:** restart the detector and read the log at startup. You should see the camera initialise without a config warning:

```bash
docker logs --tail 50 frigate 2>&1 | grep -iE "zone|error|warn"
```

Expected: no `Error parsing config` line, and a line confirming `front_door` started capture. Then walk through the driveway once and once along the street edge; the first pass must appear in the UI's events list, the second must not.

## Step 3. Verify notifications end to end and measure the false-alarm rate
![Illustration: Step 3. Verify notifications end to end and measure the false-alarm rate](https://ai-release.org/guides/img/kak-nastroit-ii-videonablyudenie-bez-lozhnyh-trevog-zon-en-3.jpg?v=1795164966)


**What to do:** subscribe to the event topic and record raw alerts to a file for 24 hours.

```bash
mosquitto_sub -h 192.168.1.10 -p 1883 -u mqttuser -P '<mqtt-password>' \
  -t 'frigate/events' \
  | jq -r 'select(.type=="new") | [.after.start_time, .after.camera, .after.label, .after.score, (.after.entered_zones|join("|"))] | @csv' \
  >> alerts.csv
```

Field names live in the detector's MQTT schema and differ between releases — check the documentation if `jq` returns nothing. The `select(.type=="new")` guard matters: the same topic carries `update` and `end` messages, and counting those triples your numbers.

**Why:** "no false alarms" is a measurement, not a feeling. A CSV with timestamps lets you separate night IR hits from daytime motion, and separates camera A from camera B.

Summarise after 24 hours:

```python
import csv, collections
rows = list(csv.reader(open("alerts.csv")))
print(collections.Counter(f"{r[1]}/{r[2]}" for r in rows).most_common())
print("total:", len(rows))
```

**Example output:**

```
[('front_door/person', 6), ('front_door/car', 2)]
total: 8
```

Then compare against reality: for each row, keep the clip or mark it false. Anything triggered at the same minute of the night, with `score` close to your `threshold`, or with an empty `entered_zones` value, is a false positive — fix the mask or the zone rather than the threshold.

For the delivery leg, publish to a chat channel instead of polling a database: [How to Set Up VPS Monitoring via a Telegram Bot with Mini App](https://ai-release.org/guides/kak-nastroit-monitoring-vps-cherez-telegram-bota-s-mini.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide) — the same bot pattern is used to push an alert message and confirm it arrived on a phone.

**How to check:** you have success when all three are true — (1) `alerts.csv` grows only when a person or car actually enters `driveway`; (2) the message arrives on the phone within a few seconds of the walk-through; (3) a deliberate walk along the street produces zero new rows.

## Troubleshooting

**Problem. The detector starts but the camera shows a red "no frames" tile.**

- Error: `[rtsp @ 0x55f1c2] method DESCRIBE failed: 401 Unauthorized`
- Cause: wrong password, or an unencoded special character in the RTSP URL. A password like `p@ss:1` breaks the URL because `@` terminates the credentials and `:` separates user from password.
- Solution: URL-encode the password (`@` → `%40`, `:` → `%3A`), test the exact string with `ffprobe` from Step 1, then put the same string into `ffmpeg.inputs.path`. Quote the whole path in YAML so the colon does not break parsing.

**Problem. Events are created locally but nothing reaches your subscriber.**

- Error: `Connection Refused: not authorised.`
- Cause: the broker rejects the detector's credentials — anonymous access disabled, wrong user, or the detector was restarted before the config was saved.
- Solution: verify credentials independently:

```bash
mosquitto_pub -h 192.168.1.10 -p 1883 -u mqttuser -P '<mqtt-password>' -t test -m ok
```

If that fails, fix the broker user first (`mosquitto_passwd -c /etc/mosquitto/passwd mqttuser`, then `allow_anonymous false` in `mosquitto.conf`). If it succeeds, the fault is in the detector's `mqtt:` block, not the broker.

**Problem. Alerts fire every night around the same time with no one in frame.**

- Error (log line repeated each night): `{"type": "new", "after": {"label": "person", "score": 0.58, "camera": "front_door"}}`
- Cause: camera switching to night mode, IR illuminator blowing out a nearby wall or plant, and the model scoring the blown-out blob just above `min_score`.
- Solution: add a motion mask over the hotspot from Step 1, raise `min_score` for `person` by 0.05, and re-run the 24-hour capture. Do not raise `threshold` — that only delays the event, it does not remove it.

## Summary and next steps

You now have a stream verified over TCP, a masked scene, a polygon zone with two-stage confidence filters, and a 24-hour CSV that tells you the real false-alarm count instead of a guess. To scale review of a growing clip backlog across a team, hand the triage to a shared agent as described in [Claude Code for Teams: Setting Up Subagents and a Shared AI Superagent](https://ai-release.org/guides/claude-code-dlya-komandy-kak-nastroit-subagentov-i-obsc.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

## FAQ

**What is the difference between `min_score` and `threshold`?**
`min_score` is the confidence needed for the model to start tracking an object; `threshold` is the confidence needed to confirm that track as a real event. Raise `min_score` to kill random hits, raise `threshold` to kill flickering events — they solve different symptoms.

**How many zones should one camera have?**
Two is usually enough: the area where alerts are allowed (e.g. `driveway`) and the area that must never alert but still needs tracking for context (e.g. `street`). More zones mostly add config to maintain.

**Why do I get alerts for a person outside the zone?**
The object's bounding box probably overlaps the polygon, or the event was created before `required_zones` was applied. Check the `entered_zones` field in the CSV — an empty value means the alert did not pass through the zone filter.

**Does a higher detection FPS reduce false alarms?**
Not by itself, and it costs CPU. A 5 FPS detection stream is enough for a walking person; the real gains come from masks, `min_area` tuned to the far edge of the zone, and a confirmed two-stage score.
