Files
sign-detector/lib/domain/detection_stabilizer.dart
2026-09-27 19:12:14 +03:00

111 lines
2.5 KiB
Dart

import 'norm_rect.dart';
import 'traffic_sign.dart';
class SignDetection {
const SignDetection({
required this.rawLabel,
required this.confidence,
required this.box,
this.sign,
});
final String rawLabel;
final double confidence;
final NormRect box;
final TrafficSign? sign;
String get titleCode => sign?.code ?? rawLabel;
}
/// Keeps a sign on screen only after it has been seen on several frames.
class DetectionStabilizer {
DetectionStabilizer({
this.minHits = 2,
this.holdMisses = 1,
this.maxMisses = 3,
this.iouThreshold = 0.3,
});
final int minHits;
final int holdMisses;
final int maxMisses;
final double iouThreshold;
final List<_Track> _tracks = [];
void reset() => _tracks.clear();
List<SignDetection> update(List<SignDetection> frame) {
final matched = <int>{};
for (final track in _tracks) {
var bestIndex = -1;
var bestIou = iouThreshold;
for (var i = 0; i < frame.length; i++) {
if (matched.contains(i)) {
continue;
}
if (frame[i].rawLabel != track.rawLabel) {
continue;
}
final overlap = rectIou(track.box, frame[i].box);
if (overlap >= bestIou) {
bestIou = overlap;
bestIndex = i;
}
}
if (bestIndex >= 0) {
matched.add(bestIndex);
final detection = frame[bestIndex];
track
..hits += 1
..misses = 0
..confidence = detection.confidence
..box = track.box.lerp(detection.box, 0.65)
..sign = detection.sign;
} else {
track.misses += 1;
}
}
for (var i = 0; i < frame.length; i++) {
if (!matched.contains(i)) {
_tracks.add(_Track(frame[i]));
}
}
_tracks.removeWhere((track) => track.misses > maxMisses);
final visible = <SignDetection>[];
for (final track in _tracks) {
if (track.hits >= minHits && track.misses <= holdMisses) {
visible.add(track.toDetection());
}
}
visible.sort((a, b) => b.confidence.compareTo(a.confidence));
return visible;
}
}
class _Track {
_Track(SignDetection detection)
: rawLabel = detection.rawLabel,
box = detection.box,
confidence = detection.confidence,
sign = detection.sign;
final String rawLabel;
NormRect box;
double confidence;
TrafficSign? sign;
int hits = 1;
int misses = 0;
SignDetection toDetection() {
return SignDetection(
rawLabel: rawLabel,
confidence: confidence,
box: box,
sign: sign,
);
}
}