Files
Jan Pleterski 5f9e2a3b86 optimization of the detection algorithem.
BOOK update.
2026-11-27 09:43:25 +01:00

167 lines
5.9 KiB
Dart

import 'dart:io';
import 'dart:isolate';
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:tflite_flutter/tflite_flutter.dart';
import 'package:image/image.dart' as img;
class DetectionResult {
final double x1, y1, x2, y2;
final double confidence;
final int classId;
DetectionResult(this.x1, this.y1, this.x2, this.y2, this.confidence, this.classId);
}
/// A decoded camera photo, upright: [channels] bytes per pixel (RGBA from the
/// platform decoder, RGB from the Dart one), row by row.
class Photo {
final Uint8List pixels;
final int width, height, channels;
Photo(this.pixels, this.width, this.height, this.channels);
/// The centre square: what detection looks at, the preview shows and gets saved.
int get side => min(width, height);
int get squareX => (width - side) ~/ 2;
int get squareY => (height - side) ~/ 2;
}
/// Decodes a camera JPEG with the platform's decoder, several times faster
/// than the pure-Dart one; falls back to that if it fails. Both apply the
/// photo's EXIF rotation, so the result is upright.
Future<Photo> decodePhoto(Uint8List jpeg) async =>
await decodePhotoNative(jpeg) ?? await Isolate.run(() => decodePhotoDart(jpeg));
Future<Photo?> decodePhotoNative(Uint8List jpeg) async {
try {
final codec = await ui.instantiateImageCodec(jpeg);
final frame = await codec.getNextFrame();
final image = frame.image;
final data = await image.toByteData(format: ui.ImageByteFormat.rawStraightRgba);
final photo = data == null
? null
: Photo(data.buffer.asUint8List(), image.width, image.height, 4);
image.dispose();
codec.dispose();
return photo;
} catch (_) {
return null;
}
}
Photo decodePhotoDart(Uint8List jpeg) {
final decoded = img.decodeImage(jpeg);
if (decoded == null) throw Exception('Could not decode image.');
return Photo(decoded.getBytes(order: img.ChannelOrder.rgb), decoded.width,
decoded.height, 3);
}
/// Model input from the photo's centre square: RGB floats 0..1, row by row,
/// [width] x [height]. Samples the same pixels as copyResize (nearest) of the
/// cropped square, without copying the square first.
Float32List inputFromPhoto(Photo photo, int width, int height) {
final side = photo.side, ox = photo.squareX, oy = photo.squareY;
final ch = photo.channels, rowBytes = photo.width * ch, px = photo.pixels;
final dx = side / width, dy = side / height;
final cols = Int32List(width);
for (int x = 0; x < width; x++) {
cols[x] = (ox + (x * dx).toInt()) * ch;
}
final input = Float32List(width * height * 3);
int i = 0;
for (int y = 0; y < height; y++) {
final row = (oy + (y * dy).toInt()) * rowBytes;
for (int x = 0; x < width; x++) {
final p = row + cols[x];
input[i++] = px[p] / 255.0;
input[i++] = px[p + 1] / 255.0;
input[i++] = px[p + 2] / 255.0;
}
}
return input;
}
/// The centre square as an image, for saving.
img.Image squareOf(Photo photo) {
final full = img.Image.fromBytes(
width: photo.width,
height: photo.height,
bytes: photo.pixels.buffer,
bytesOffset: photo.pixels.offsetInBytes,
numChannels: photo.channels);
return img.copyCrop(full,
x: photo.squareX, y: photo.squareY, width: photo.side, height: photo.side);
}
/// Save the centre square as JPEG in a background isolate.
Future<void> saveSquareInBackground(Photo photo, String path) =>
Isolate.run(() => File(path).writeAsBytesSync(img.encodeJpg(squareOf(photo))));
class YOLODetector {
late Interpreter _interpreter;
late IsolateInterpreter _background; // runs the model off the UI thread
late int inputWidth, inputHeight;
final double confidenceThreshold = 0.4;
YOLODetector._create();
/// Loads the model and runs it once, so the first real photo doesn't pay
/// for the interpreter's one-time setup.
static Future<YOLODetector> create() async {
final detector = YOLODetector._create();
await detector._loadModel();
await detector._run(Float32List(detector.inputWidth * detector.inputHeight * 3));
return detector;
}
Future<void> _loadModel() async {
final options = InterpreterOptions()..threads = 4;
_interpreter = await Interpreter.fromAsset('assets/best_float32_nms.tflite', options: options);
_background = await IsolateInterpreter.create(address: _interpreter.address);
final inputShape = _interpreter.getInputTensor(0).shape;
inputHeight = inputShape[1];
inputWidth = inputShape[2];
}
// One model run; each row of the result is x1, y1, x2, y2, score, class
Future<List<List<double>>> _run(Float32List input) async {
final numDetections = _interpreter.getOutputTensor(0).shape[1];
final output = [List.generate(numDetections, (_) => List.filled(6, 0.0))];
await _background.run(input.buffer, output);
return output[0];
}
/// Whole pipeline for a photo file. Coordinates are in pixels of the
/// photo's centre square.
Future<List<DetectionResult>> detect(File imageFile) async =>
detectPhoto(await decodePhoto(await imageFile.readAsBytes()));
/// Runs the model on [photo]'s centre square; coordinates are in pixels of
/// that square. Not re-entrant: wait for one call to finish before the next.
Future<List<DetectionResult>> detectPhoto(Photo photo) async {
final w = inputWidth, h = inputHeight;
final input = await Isolate.run(() => inputFromPhoto(photo, w, h));
final rows = await _run(input);
final side = photo.side.toDouble();
final results = <DetectionResult>[];
for (final d in rows) {
final score = d[4];
if (score < confidenceThreshold) continue;
// Corners come normalized to [0, 1] of the model input, which is the
// whole square scaled down
results.add(DetectionResult(d[0] * side, d[1] * side, d[2] * side,
d[3] * side, score, d[5].toInt()));
}
return results;
}
void close() {
_background.close();
_interpreter.close();
}
}