BirdGuard is my small project that watches a bird feeder camera and saves clips when a bird is there. In January I wrote about running YOLOv8 on a CPU with ONNX Runtime. That pipeline used the pretrained COCO model and only kept class 14, bird. It worked in the demo images. On my own camera it was not good enough, so I trained a custom model. The steps below are in the order I did them, including the parts I got wrong the first time.
Why the COCO model was not enough
The COCO “bird” class is trained on photos where the bird is usually large, sharp and in the middle. My camera is different. The birds are small in the frame, often half hidden by the feeder, and the image is soft in the morning and noisy at dusk. The pretrained model missed many of them. It also fired on things that are not birds: leaves moving in the wind and the shadow of the feeder.
You can tune the confidence threshold, but that only moves the problem. A lower threshold gives more false alarms, a higher one misses more birds. The real fix is to show the model my scene. A custom model with one class, trained on my own frames, learns what the background looks like and what a bird looks like in this exact place.
When is this worth the work? If your camera sees objects that are typical COCO photos (people walking in front of a door, cars in a street), first try the pretrained model with a good threshold. Train your own when the scene is unusual, the objects are small, or you need a class that COCO does not have.
Collecting frames
I already record the RTSP stream from the camera. For training data I wanted single frames spread over many days and different light. ffmpeg can save one frame every N seconds with the time in the file name:
mkdir -p frames
ffmpeg -rtsp_transport tcp -i rtsp://192.168.1.50:554/stream1 \
-vf fps=1/10 -q:v 2 -strftime 1 "frames/%Y%m%d-%H%M%S.jpg"
One frame every ten seconds is still too many, and most of them are empty and almost identical. Two things helped me:
- Keep the time in the file name. I need it later for the train/val split.
- Pre-filter with the COCO model. I ran the pretrained model over the frames and listed the ones where it saw a bird, even with low confidence. These frames went to the labelling queue first. I did not use its boxes as labels, only to choose frames.
yolo predict model=yolov8n.pt source=frames/ classes=14 conf=0.1 save_txt
save_txt writes one text file per frame with detections, under runs/detect/predict/labels/. Frames with a file are candidates.
I also kept a set of frames with no birds on purpose: windy days, rain, dusk, the feeder empty, the feeder full. They matter later.
Labelling
There are a few tools for this in spring 2023:
- Label Studio: open source, runs locally (pip or Docker), and has a YOLO export.
- CVAT: open source, more features for video and teams. It exports the older “YOLO 1.1” format. The label
.txtfiles are the same as YOLOv8 uses, but you need to rearrange the folders and writedata.yamlyourself. - Roboflow: hosted service with a “YOLOv8” export, and it can do the split and augmentation for you. Your images go to their servers, which I did not want for a camera at home.
I used Label Studio locally. For one class and bounding boxes, any of the three is fine. Pick the one you will not mind using for a few evenings.
Rules I wrote down before I started, because I changed my mind halfway the first time:
- Label every bird in a frame. A frame with one labelled bird and one unlabelled bird teaches the model that the second one is background.
- Boxes are tight around the visible part of the bird.
- Partly hidden birds get a box if I can tell it is a bird. If I cannot tell, I skip the frame instead of guessing.
- Frames with no bird get no boxes. They stay in the dataset as negative images.
Dataset layout and data.yaml
Ultralytics finds the labels by replacing images with labels in the path. So the layout is:
birdguard/
data.yaml
images/
train/ 20230312-071530.jpg ...
val/ 20230402-064010.jpg ...
labels/
train/ 20230312-071530.txt ...
val/ 20230402-064010.txt ...
Each label file has one line per box: class id, then centre x, centre y, width and height, all normalized to 0..1:
0 0.4821 0.6113 0.0640 0.0815
A negative image has an empty label file, or no label file at all. Both are treated as background.
data.yaml:
path: /data/birdguard
train: images/train
val: images/val
names:
0: bird
Split by day, not at random
This is the mistake I made first. I exported everything from Label Studio and split it 80/20 at random. The validation numbers looked very good. Then the model was clearly worse on new days.
The reason is leakage. Frames taken ten seconds apart are almost the same image. With a random split, the validation set contains near copies of training frames, so validation measures memory, not generalization.
Split by day instead. All frames from one day go to the same side. I keep some full days for validation, chosen to include different weather:
from pathlib import Path
import shutil
VAL_DAYS = {"20230402", "20230409", "20230416"} # whole days, my choice
src_img, src_lbl = Path("export/images"), Path("export/labels")
root = Path("birdguard")
for img in src_img.glob("*.jpg"):
day = img.stem.split("-")[0]
split = "val" if day in VAL_DAYS else "train"
for sub, src in (("images", img), ("labels", src_lbl / f"{img.stem}.txt")):
dst = root / sub / split
dst.mkdir(parents=True, exist_ok=True)
if src.exists():
shutil.copy2(src, dst / src.name)
The numbers after this change were lower. They were also honest.
Training
I use the ultralytics package, version 8.0.x, on a desktop with a GPU. Pin the version in your requirements.txt; the package gets new releases very often and small details change.
pip install "ultralytics==8.0.*"
yolo detect train data=birdguard/data.yaml model=yolov8n.pt imgsz=640 epochs=100 batch=16
The arguments that matter most:
model=yolov8n.ptstarts from the COCO pretrained weights. Always start from pretrained weights for a small dataset. I started withnbecause it must run on CPU later.yolov8s.ptis a good second try ifnis not accurate enough and you can afford the slower inference.imgsz=640is the training size. My birds are small, so I did not go lower. If your objects are large, a smaller size trains and runs faster.epochs=100is the default. Training also stops early when the validation metric stops improving (thepatienceargument).batch=16is the default. Lower it if you run out of GPU memory.
The run goes to runs/detect/train/ (then train2, train3, …). Use name= to give runs readable names, because after a week you will not remember what train7 was.
On the first run, change nothing else. Ultralytics also recommends training with the defaults first and getting a baseline before you tune.
Reading the results
The run folder has weights/best.pt, weights/last.pt, results.csv, results.png, and several plots. To evaluate the best weights again on the validation set:
yolo detect val model=runs/detect/train/weights/best.pt data=birdguard/data.yaml
What the numbers mean for a single-class detector:
- Precision: of the boxes the model reported, how many were real birds. Low precision means false alarms.
- Recall: of the real birds, how many the model found. Low recall means missed birds.
- mAP50: average precision when a box counts as correct if it overlaps the label by at least 50% IoU. This is the “did it find the bird” metric.
- mAP50-95: the same, averaged over IoU thresholds from 0.5 to 0.95. It also rewards tight boxes. It is always lower than mAP50.
For BirdGuard I care more about mAP50 and recall than about exact box edges. I only need to know that a bird is there.
Do not stop at the summary line. These files told me more:
results.png: loss and metric curves per epoch. If validation loss goes up while training loss goes down, the model is overfitting.confusion_matrix.png: with one class, the interesting cells are “bird predicted as background” (misses) and “background predicted as bird” (false alarms).val_batch0_labels.jpgandval_batch0_pred.jpg: the labels and predictions side by side. I found two labelling mistakes just by looking at these.PR_curve.pngandF1_curve.png: the F1 curve shows which confidence threshold gives the best balance. I used it to pick the threshold for the pipeline.
Then look at the false positives one by one. Run prediction on the validation days and save the images:
yolo predict model=runs/detect/train/weights/best.pt source=birdguard/images/val conf=0.25 save=True
Go through the frames that have boxes but no label. On my dataset most false positives fell into a few groups, mostly moving leaves and one part of the feeder in strong light. Each group became a short to-do: collect more negative frames of exactly that.
Common mistakes
Leaky split. Covered above. If validation numbers look too good, check this first.
Too few negative images. My first model had almost only frames with birds, because I chose frames with the COCO pre-filter. So it learned that there is always a bird somewhere. The Ultralytics training tips suggest a small share of background images, roughly up to 10%, to reduce false positives. For a fixed camera I would go to the upper end of that and pick negatives from the hard cases, not random empty frames.
Label mistakes. Missing boxes, loose boxes, and a few boxes with the wrong class id after an export. Class ids follow the order of the labels in the tool, so if you add or remove a label there, the ids can shift. Open some label files and check the class ids before training. Viewing train_batch0.jpg in the run folder shows the labels drawn on augmented training images. Look at it once per dataset version.
Changing two things at once. New data and a bigger model in the same run, and then you do not know which one helped.
Export to ONNX for the existing pipeline
The CPU pipeline from January stays the same. Only the model file changes:
yolo export model=runs/detect/train/weights/best.pt format=onnx imgsz=640
The output is now [1, 5, 8400] instead of [1, 84, 8400]: four box values and one class score. My post-processing code takes the argmax over the class scores, which still works with one class. The class names are in the model metadata, so the pipeline reads bird from there and I did not need to change the label list.
Before switching, run the exported model and the .pt model on the same validation frames and compare the boxes. They should be very close. Then I let the new model run next to the old one for a few days and compared the saved clips.
What I would do next
The weak spot is still dusk, when the camera switches to a noisy image. I will collect more frames from that hour and train again from the same starting weights. I also want a small script that saves every frame where the old and new model disagree, because those are the most useful frames to label next.
The license note from the January post also applies here: the ultralytics package and the YOLOv8 weights are AGPL-3.0. Read what that means for a model fine-tuned from those weights before you ship it anywhere.