first commit

This commit is contained in:
vl.arkhangelskii
2026-09-27 19:12:14 +03:00
commit ba3ba38fc9
318 changed files with 9377 additions and 0 deletions
+110
View File
@@ -0,0 +1,110 @@
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,
);
}
}
+39
View File
@@ -0,0 +1,39 @@
import 'dart:math' as math;
/// Ultralytics-style letterbox: fit the source into a square without stretching.
class Letterbox {
const Letterbox({
required this.inputSize,
required this.scale,
required this.padX,
required this.padY,
});
final int inputSize;
final double scale;
final double padX;
final double padY;
factory Letterbox.fit({
required int srcWidth,
required int srcHeight,
required int inputSize,
}) {
final scale = math.min(inputSize / srcWidth, inputSize / srcHeight);
return Letterbox(
inputSize: inputSize,
scale: scale,
padX: (inputSize - srcWidth * scale) / 2,
padY: (inputSize - srcHeight * scale) / 2,
);
}
/// Center of a model pixel, in upright source pixels. May fall outside the image.
(double x, double y) uprightFromModelPixel(int dx, int dy) {
return ((dx + 0.5 - padX) / scale, (dy + 0.5 - padY) / scale);
}
(double x, double y) uprightFromModel(double mx, double my) {
return ((mx - padX) / scale, (my - padY) / scale);
}
}
+53
View File
@@ -0,0 +1,53 @@
/// Axis-aligned box in normalized image space, origin at the top-left.
class NormRect {
const NormRect(this.left, this.top, this.width, this.height);
final double left;
final double top;
final double width;
final double height;
double get right => left + width;
double get bottom => top + height;
NormRect clamped() {
final l = left.clamp(0.0, 1.0);
final t = top.clamp(0.0, 1.0);
final r = right.clamp(0.0, 1.0);
final b = bottom.clamp(0.0, 1.0);
return NormRect(l, t, (r - l).clamp(0.0, 1.0), (b - t).clamp(0.0, 1.0));
}
NormRect lerp(NormRect other, double t) {
double mix(double a, double b) => a + (b - a) * t;
return NormRect(
mix(left, other.left),
mix(top, other.top),
mix(width, other.width),
mix(height, other.height),
);
}
/// Horizontal mirror used for the mirrored front-camera preview.
NormRect mirroredHorizontally() {
return NormRect(1 - right, top, width, height);
}
}
double rectIou(NormRect a, NormRect b) {
final interLeft = a.left > b.left ? a.left : b.left;
final interTop = a.top > b.top ? a.top : b.top;
final interRight = a.right < b.right ? a.right : b.right;
final interBottom = a.bottom < b.bottom ? a.bottom : b.bottom;
final w = interRight - interLeft;
final h = interBottom - interTop;
if (w <= 0 || h <= 0) {
return 0;
}
final inter = w * h;
final union = a.width * a.height + b.width * b.height - inter;
if (union <= 0) {
return 0;
}
return inter / union;
}
+59
View File
@@ -0,0 +1,59 @@
/// Clockwise degrees that turn a camera buffer upright on screen.
///
/// Same compensation ML Kit uses for the Android camera plugin:
/// back camera `(sensor - device) mod 360`, front camera `(sensor + device) mod 360`.
int uprightClockwiseDegrees({
required int sensorOrientation,
required int deviceDegrees,
required bool frontCamera,
}) {
if (frontCamera) {
return (sensorOrientation + deviceDegrees) % 360;
}
return (sensorOrientation - deviceDegrees + 360) % 360;
}
/// Maps a pixel of the upright image back to the raw camera buffer.
(int x, int y) rawPixelFromUpright({
required int ux,
required int uy,
required int rawWidth,
required int rawHeight,
required int clockwiseDegrees,
}) {
switch (clockwiseDegrees) {
case 0:
return (ux, uy);
case 90:
// destX = rawHeight - 1 - ry, destY = rx
return (uy, rawHeight - 1 - ux);
case 180:
return (rawWidth - 1 - ux, rawHeight - 1 - uy);
case 270:
// destX = ry, destY = rawWidth - 1 - rx
return (rawWidth - 1 - uy, ux);
default:
throw ArgumentError(
'Поворот должен быть 0, 90, 180 или 270, получено $clockwiseDegrees',
);
}
}
(int width, int height) uprightSize({
required int rawWidth,
required int rawHeight,
required int clockwiseDegrees,
}) {
switch (clockwiseDegrees) {
case 0:
case 180:
return (rawWidth, rawHeight);
case 90:
case 270:
return (rawHeight, rawWidth);
default:
throw ArgumentError(
'Поворот должен быть 0, 90, 180 или 270, получено $clockwiseDegrees',
);
}
}
+84
View File
@@ -0,0 +1,84 @@
import 'traffic_sign.dart';
import 'sign_code.dart';
class SignCatalog {
SignCatalog(List<TrafficSign> signs)
: _byCode = {for (final sign in signs) sign.code: sign} {
final seen = <String>{};
for (final sign in signs) {
if (!seen.add(sign.code)) {
throw ArgumentError('Повторяющийся номер знака: ${sign.code}');
}
}
}
final Map<String, TrafficSign> _byCode;
List<TrafficSign> get signs {
final values = _byCode.values.toList();
values.sort((a, b) => compareSignCodes(a.code, b.code));
return values;
}
TrafficSign? findByCode(String code) => _byCode[code];
/// Returns a catalog entry only for a known sign number or a traffic-light
/// class from the training set. Unknown labels stay empty on purpose.
TrafficSign? findByLabel(String rawLabel) {
final signalCode = _trafficSignalCodes[rawLabel.trim().toLowerCase()];
if (signalCode != null) {
return _byCode[signalCode];
}
final code = normalizeSignCode(rawLabel);
if (code == null) {
return null;
}
// The dataset splits one speed-limit sign into 3.24.1, 3.24.2, …
// Those suffixes are not speeds and not GOST numbers.
if (_speedLimitVariant.hasMatch(code)) {
return _byCode['3.24'];
}
return _byCode[code];
}
List<TrafficSign> byCategory(SignCategory category) {
return signs.where((sign) => sign.category == category).toList();
}
}
final RegExp _speedLimitVariant = RegExp(r'^3\.24(?:\.\d+)+$');
/// Class names from Dognellaf/russian-road-signs. Keys are lowercase.
const Map<String, String> _trafficSignalCodes = {
'redtrafficlights': 'signal.red',
'yellowtrafficlights': 'signal.yellow',
'greentrafficlights': 'signal.green',
'redyellowtrafficlights': 'signal.redYellow',
'trafficlights': 'signal.unknown',
};
int compareSignCodes(String a, String b) {
final aParts = a.split('.');
final bParts = b.split('.');
final length = aParts.length > bParts.length ? aParts.length : bParts.length;
for (var i = 0; i < length; i++) {
final aText = i < aParts.length ? aParts[i] : '';
final bText = i < bParts.length ? bParts[i] : '';
final aNumber = int.tryParse(aText);
final bNumber = int.tryParse(bText);
if (aNumber != null && bNumber != null && aNumber != bNumber) {
return aNumber.compareTo(bNumber);
}
if (aNumber != null && bNumber == null) {
return -1;
}
if (aNumber == null && bNumber != null) {
return 1;
}
final textOrder = aText.compareTo(bText);
if (textOrder != 0) {
return textOrder;
}
}
return 0;
}
+10
View File
@@ -0,0 +1,10 @@
final RegExp _signCodePattern = RegExp(r'\d+(?:\.\d+)+');
/// Pulls a GOST/ПДД number out of a model label.
///
/// `3.27`, `3_27` and `sign-3.27` all become `3.27`.
/// Labels without a dotted number return null: the app must not guess a rule.
String? normalizeSignCode(String rawLabel) {
final unified = rawLabel.trim().replaceAll('_', '.').replaceAll('-', '.');
return _signCodePattern.firstMatch(unified)?.group(0);
}
+36
View File
@@ -0,0 +1,36 @@
enum SignCategory {
warning,
priority,
prohibitory,
mandatory,
special,
information,
service,
plate,
signal,
}
class TrafficSign {
const TrafficSign({
required this.code,
required this.name,
required this.category,
required this.summary,
required this.action,
this.requiresReadingTheSign = false,
});
/// Номер по приложению 1 к ПДД, например `3.27`.
final String code;
final String name;
final SignCategory category;
/// Что означает знак.
final String summary;
/// Что делать водителю. Формулировка короче текста ПДД и не заменяет его.
final String action;
/// На знаке есть число или схема, без которых тип знака не задаёт требование полностью.
final bool requiresReadingTheSign;
}
+239
View File
@@ -0,0 +1,239 @@
import 'dart:math' as math;
import 'dart:typed_data';
class YoloBox {
const YoloBox({
required this.left,
required this.top,
required this.right,
required this.bottom,
required this.classIndex,
required this.score,
});
final double left;
final double top;
final double right;
final double bottom;
final int classIndex;
final double score;
double get width => right - left;
double get height => bottom - top;
}
/// Decodes an Ultralytics YOLO detect head from a TFLite output tensor.
///
/// Supports the raw head `[1, 4+classes, anchors]` (or transposed) and an
/// end-to-end NMS head `[1, detections, 6]`. Coordinates are returned in
/// model-input pixels.
class YoloDecoder {
const YoloDecoder({this.maxDetections = 8});
final int maxDetections;
static const int nmsFeatureCount = 6;
static const int nmsMaxRows = 300;
List<YoloBox> decode({
required Float32List data,
required List<int> shape,
required int inputSize,
required double confidenceThreshold,
required double iouThreshold,
}) {
if (shape.length != 3 || shape[0] != 1) {
throw FormatException(
'Ожидался выход YOLO формы [1, A, B], получено $shape',
);
}
final dimA = shape[1];
final dimB = shape[2];
if (data.length < dimA * dimB) {
throw FormatException('Буфер выхода короче, чем форма $shape');
}
if (_isNmsLayout(dimA, dimB)) {
return _decodeNms(
data: data,
rows: dimA,
confidenceThreshold: confidenceThreshold,
inputSize: inputSize,
);
}
final channelsFirst = dimA < dimB;
final numChannels = channelsFirst ? dimA : dimB;
final numAnchors = channelsFirst ? dimB : dimA;
if (numChannels < 5) {
throw FormatException('В выходе YOLO меньше 5 каналов: $shape');
}
double at(int channel, int anchor) {
if (channelsFirst) {
return data[channel * numAnchors + anchor];
}
return data[anchor * numChannels + channel];
}
var maxCoord = 0.0;
var scoresLookLikeLogits = false;
for (var anchor = 0; anchor < numAnchors; anchor++) {
for (var channel = 0; channel < 4; channel++) {
final value = at(channel, anchor).abs();
if (value > maxCoord) {
maxCoord = value;
}
}
for (var channel = 4; channel < numChannels; channel++) {
final score = at(channel, anchor);
if (score < 0 || score > 1) {
scoresLookLikeLogits = true;
}
}
}
final coordScale = maxCoord <= 2 ? inputSize.toDouble() : 1.0;
final candidates = <YoloBox>[];
for (var anchor = 0; anchor < numAnchors; anchor++) {
var bestClass = 0;
var bestScore = 0.0;
for (var classIndex = 0; classIndex < numChannels - 4; classIndex++) {
final raw = at(4 + classIndex, anchor);
final score = scoresLookLikeLogits ? _sigmoid(raw) : raw;
if (score > bestScore) {
bestScore = score;
bestClass = classIndex;
}
}
if (bestScore < confidenceThreshold) {
continue;
}
final cx = at(0, anchor) * coordScale;
final cy = at(1, anchor) * coordScale;
final w = at(2, anchor) * coordScale;
final h = at(3, anchor) * coordScale;
if (w < 4 || h < 4) {
continue;
}
candidates.add(
YoloBox(
left: cx - w / 2,
top: cy - h / 2,
right: cx + w / 2,
bottom: cy + h / 2,
classIndex: bestClass,
score: bestScore,
),
);
}
return _nms(candidates, iouThreshold);
}
/// End-to-end NMS export is `[1, detections, 6]` with at most 300 rows.
/// A raw 2-class head is `[1, 6, anchors]`; at 320 px there are far more
/// than 300 anchors, so the two layouts do not collide.
bool _isNmsLayout(int dimA, int dimB) {
return dimB == nmsFeatureCount && dimA <= nmsMaxRows;
}
List<YoloBox> _decodeNms({
required Float32List data,
required int rows,
required double confidenceThreshold,
required int inputSize,
}) {
double at(int row, int feature) {
return data[row * nmsFeatureCount + feature];
}
var maxCoord = 0.0;
for (var row = 0; row < rows; row++) {
for (var feature = 0; feature < 4; feature++) {
final value = at(row, feature).abs();
if (value > maxCoord) {
maxCoord = value;
}
}
}
final coordScale = maxCoord <= 2 ? inputSize.toDouble() : 1.0;
final boxes = <YoloBox>[];
for (var row = 0; row < rows; row++) {
final score = at(row, 4);
if (score < confidenceThreshold) {
continue;
}
final classIndex = at(row, 5).round();
boxes.add(
YoloBox(
left: at(row, 0) * coordScale,
top: at(row, 1) * coordScale,
right: at(row, 2) * coordScale,
bottom: at(row, 3) * coordScale,
classIndex: classIndex,
score: score,
),
);
}
boxes.sort((a, b) => b.score.compareTo(a.score));
if (boxes.length > maxDetections) {
return boxes.sublist(0, maxDetections);
}
return boxes;
}
List<YoloBox> _nms(List<YoloBox> boxes, double iouThreshold) {
boxes.sort((a, b) => b.score.compareTo(a.score));
final suppressed = List<bool>.filled(boxes.length, false);
final kept = <YoloBox>[];
for (var i = 0; i < boxes.length; i++) {
if (suppressed[i]) {
continue;
}
kept.add(boxes[i]);
if (kept.length >= maxDetections) {
break;
}
for (var j = i + 1; j < boxes.length; j++) {
if (suppressed[j]) {
continue;
}
if (boxes[i].classIndex != boxes[j].classIndex) {
continue;
}
if (_iou(boxes[i], boxes[j]) > iouThreshold) {
suppressed[j] = true;
}
}
}
return kept;
}
double _iou(YoloBox a, YoloBox b) {
final interLeft = math.max(a.left, b.left);
final interTop = math.max(a.top, b.top);
final interRight = math.min(a.right, b.right);
final interBottom = math.min(a.bottom, b.bottom);
final w = interRight - interLeft;
final h = interBottom - interTop;
if (w <= 0 || h <= 0) {
return 0;
}
final inter = w * h;
final union = a.width * a.height + b.width * b.height - inter;
if (union <= 0) {
return 0;
}
return inter / union;
}
double _sigmoid(double value) {
if (value >= 0) {
final z = math.exp(-value);
return 1 / (1 + z);
}
final z = math.exp(value);
return z / (1 + z);
}
}