240 lines
6.6 KiB
Dart
240 lines
6.6 KiB
Dart
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);
|
|
}
|
|
}
|