first commit
This commit is contained in:
@@ -0,0 +1,290 @@
|
||||
import 'dart:async';
|
||||
import 'dart:isolate';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:tflite_flutter/tflite_flutter.dart';
|
||||
|
||||
import '../../domain/letterbox.dart';
|
||||
import '../../domain/norm_rect.dart';
|
||||
import '../../domain/rotation.dart';
|
||||
import '../../domain/yolo_decoder.dart';
|
||||
import '../frame/yuv_sampler.dart';
|
||||
|
||||
class FrameHit {
|
||||
const FrameHit({
|
||||
required this.label,
|
||||
required this.confidence,
|
||||
required this.box,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final double confidence;
|
||||
final NormRect box;
|
||||
}
|
||||
|
||||
class FrameOutcome {
|
||||
const FrameOutcome({required this.hits, required this.elapsedMs});
|
||||
|
||||
final List<FrameHit> hits;
|
||||
final int elapsedMs;
|
||||
}
|
||||
|
||||
class DetectorWorker {
|
||||
Isolate? _isolate;
|
||||
SendPort? _send;
|
||||
final ReceivePort _incoming = ReceivePort();
|
||||
StreamSubscription<dynamic>? _subscription;
|
||||
final Map<int, Completer<Object>> _pending = {};
|
||||
var _nextId = 0;
|
||||
var _ready = false;
|
||||
|
||||
bool get isReady => _ready;
|
||||
|
||||
Future<int> start({
|
||||
required Uint8List modelBytes,
|
||||
required List<String> labels,
|
||||
}) async {
|
||||
_isolate = await Isolate.spawn(detectorIsolateMain, _incoming.sendPort);
|
||||
final sendCompleter = Completer<SendPort>();
|
||||
_subscription = _incoming.listen((message) {
|
||||
if (message is SendPort) {
|
||||
if (!sendCompleter.isCompleted) {
|
||||
sendCompleter.complete(message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
_onMessage(message);
|
||||
});
|
||||
_send = await sendCompleter.future;
|
||||
final id = _nextId++;
|
||||
final pending = Completer<Object>();
|
||||
_pending[id] = pending;
|
||||
_send!.send(_LoadModel(id, modelBytes, labels));
|
||||
final inputSize = await pending.future;
|
||||
_ready = true;
|
||||
return inputSize as int;
|
||||
}
|
||||
|
||||
Future<FrameOutcome> detect({
|
||||
required YuvFrame frame,
|
||||
required int clockwiseDegrees,
|
||||
required double confidenceThreshold,
|
||||
double iouThreshold = 0.45,
|
||||
}) {
|
||||
final send = _send;
|
||||
if (send == null || !_ready) {
|
||||
return Future.error(StateError('Детектор не загружен'));
|
||||
}
|
||||
final id = _nextId++;
|
||||
final pending = Completer<Object>();
|
||||
_pending[id] = pending;
|
||||
send.send(
|
||||
_FrameJob(
|
||||
id: id,
|
||||
frame: frame,
|
||||
clockwiseDegrees: clockwiseDegrees,
|
||||
confidenceThreshold: confidenceThreshold,
|
||||
iouThreshold: iouThreshold,
|
||||
),
|
||||
);
|
||||
return pending.future.then((value) => value as FrameOutcome);
|
||||
}
|
||||
|
||||
void _onMessage(Object? message) {
|
||||
if (message is _Ready) {
|
||||
_pending.remove(message.id)?.complete(message.inputSize);
|
||||
return;
|
||||
}
|
||||
if (message is _FrameDone) {
|
||||
_pending
|
||||
.remove(message.id)
|
||||
?.complete(
|
||||
FrameOutcome(hits: message.hits, elapsedMs: message.elapsedMs),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (message is _Failed) {
|
||||
_pending.remove(message.id)?.completeError(StateError(message.reason));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> dispose() async {
|
||||
_isolate?.kill(priority: Isolate.immediate);
|
||||
await _subscription?.cancel();
|
||||
_incoming.close();
|
||||
_isolate = null;
|
||||
_send = null;
|
||||
_ready = false;
|
||||
}
|
||||
}
|
||||
|
||||
class _LoadModel {
|
||||
const _LoadModel(this.id, this.bytes, this.labels);
|
||||
|
||||
final int id;
|
||||
final Uint8List bytes;
|
||||
final List<String> labels;
|
||||
}
|
||||
|
||||
class _FrameJob {
|
||||
const _FrameJob({
|
||||
required this.id,
|
||||
required this.frame,
|
||||
required this.clockwiseDegrees,
|
||||
required this.confidenceThreshold,
|
||||
required this.iouThreshold,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final YuvFrame frame;
|
||||
final int clockwiseDegrees;
|
||||
final double confidenceThreshold;
|
||||
final double iouThreshold;
|
||||
}
|
||||
|
||||
class _Ready {
|
||||
const _Ready(this.id, this.inputSize);
|
||||
|
||||
final int id;
|
||||
final int inputSize;
|
||||
}
|
||||
|
||||
class _FrameDone {
|
||||
const _FrameDone(this.id, this.hits, this.elapsedMs);
|
||||
|
||||
final int id;
|
||||
final List<FrameHit> hits;
|
||||
final int elapsedMs;
|
||||
}
|
||||
|
||||
class _Failed {
|
||||
const _Failed(this.id, this.reason);
|
||||
|
||||
final int id;
|
||||
final String reason;
|
||||
}
|
||||
|
||||
void detectorIsolateMain(SendPort mainPort) {
|
||||
final inbox = ReceivePort();
|
||||
mainPort.send(inbox.sendPort);
|
||||
const decoder = YoloDecoder();
|
||||
final sampler = YuvSampler();
|
||||
Interpreter? interpreter;
|
||||
List<String> labels = const [];
|
||||
var inputSize = 0;
|
||||
List<int> outputShape = const [];
|
||||
Uint8List? inputBytes;
|
||||
Uint8List? outputBytes;
|
||||
|
||||
inbox.listen((message) {
|
||||
if (message is _LoadModel) {
|
||||
try {
|
||||
final options = InterpreterOptions()..threads = 4;
|
||||
final created = Interpreter.fromBuffer(message.bytes, options: options);
|
||||
final inputTensor = created.getInputTensors().first;
|
||||
final outputTensor = created.getOutputTensors().first;
|
||||
if (inputTensor.type != TensorType.float32 ||
|
||||
outputTensor.type != TensorType.float32) {
|
||||
created.close();
|
||||
mainPort.send(
|
||||
_Failed(
|
||||
message.id,
|
||||
'Нужна модель float32. Экспортируйте без half и без int8.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final shape = inputTensor.shape;
|
||||
if (shape.length != 4 || shape[3] != 3 || shape[1] != shape[2]) {
|
||||
created.close();
|
||||
mainPort.send(
|
||||
_Failed(
|
||||
message.id,
|
||||
'Ожидался вход NHWC [1, N, N, 3], получено $shape.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
interpreter = created;
|
||||
labels = message.labels;
|
||||
inputSize = shape[1];
|
||||
outputShape = outputTensor.shape;
|
||||
inputBytes = Uint8List(inputSize * inputSize * 3 * 4);
|
||||
final elements = outputShape.fold<int>(1, (a, b) => a * b);
|
||||
outputBytes = Uint8List(elements * 4);
|
||||
mainPort.send(_Ready(message.id, inputSize));
|
||||
} catch (error) {
|
||||
mainPort.send(_Failed(message.id, '$error'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message is! _FrameJob) {
|
||||
return;
|
||||
}
|
||||
final current = interpreter;
|
||||
final input = inputBytes;
|
||||
final output = outputBytes;
|
||||
if (current == null || input == null || output == null) {
|
||||
mainPort.send(_Failed(message.id, 'Модель не загружена'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final started = DateTime.now().microsecondsSinceEpoch;
|
||||
final floats = sampler.sample(
|
||||
frame: message.frame,
|
||||
clockwiseDegrees: message.clockwiseDegrees,
|
||||
inputSize: inputSize,
|
||||
);
|
||||
input.setAll(
|
||||
0,
|
||||
floats.buffer.asUint8List(floats.offsetInBytes, floats.lengthInBytes),
|
||||
);
|
||||
current.run(input, output);
|
||||
final scores = Float32List.view(output.buffer);
|
||||
final boxes = decoder.decode(
|
||||
data: scores,
|
||||
shape: outputShape,
|
||||
inputSize: inputSize,
|
||||
confidenceThreshold: message.confidenceThreshold,
|
||||
iouThreshold: message.iouThreshold,
|
||||
);
|
||||
final upright = uprightSize(
|
||||
rawWidth: message.frame.width,
|
||||
rawHeight: message.frame.height,
|
||||
clockwiseDegrees: message.clockwiseDegrees,
|
||||
);
|
||||
final letterbox = Letterbox.fit(
|
||||
srcWidth: upright.$1,
|
||||
srcHeight: upright.$2,
|
||||
inputSize: inputSize,
|
||||
);
|
||||
final hits = <FrameHit>[
|
||||
for (final box in boxes)
|
||||
FrameHit(
|
||||
label: box.classIndex >= 0 && box.classIndex < labels.length
|
||||
? labels[box.classIndex]
|
||||
: 'class_${box.classIndex}',
|
||||
confidence: box.score,
|
||||
box: _toUpright(box, letterbox, upright.$1, upright.$2),
|
||||
),
|
||||
];
|
||||
final elapsedMs =
|
||||
((DateTime.now().microsecondsSinceEpoch - started) / 1000).round();
|
||||
mainPort.send(_FrameDone(message.id, hits, elapsedMs));
|
||||
} catch (error) {
|
||||
mainPort.send(_Failed(message.id, '$error'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
NormRect _toUpright(YoloBox box, Letterbox letterbox, int width, int height) {
|
||||
double nx(double value) => (value - letterbox.padX) / letterbox.scale / width;
|
||||
double ny(double value) =>
|
||||
(value - letterbox.padY) / letterbox.scale / height;
|
||||
final left = nx(box.left);
|
||||
final top = ny(box.top);
|
||||
final right = nx(box.right);
|
||||
final bottom = ny(box.bottom);
|
||||
return NormRect(left, top, right - left, bottom - top).clamped();
|
||||
}
|
||||
Reference in New Issue
Block a user