optimization of the detection algorithem.

BOOK update.
This commit is contained in:
Jan Pleterski
2026-11-27 09:43:25 +01:00
parent b22d7987e3
commit 5f9e2a3b86
11 changed files with 1209 additions and 542 deletions
+116 -115
View File
@@ -1,6 +1,8 @@
// ======= yolo_detector.dart (updated with imageToInputTensor helper) =======
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;
@@ -12,154 +14,153 @@ class DetectionResult {
DetectionResult(this.x1, this.y1, this.x2, this.y2, this.confidence, this.classId);
}
class CroppedImageResult {
final img.Image image;
final int offsetX;
final int offsetY;
final int cropWidth;
final int cropHeight;
/// 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;
CroppedImageResult(this.image, this.offsetX, this.offsetY, this.cropWidth, this.cropHeight);
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 = 2;
final options = InterpreterOptions()..threads = 4;
_interpreter = await Interpreter.fromAsset('assets/best_float32_nms.tflite', options: options);
_background = await IsolateInterpreter.create(address: _interpreter.address);
final inputTensor = _interpreter.getInputTensor(0);
final inputShape = inputTensor.shape;
final inputShape = _interpreter.getInputTensor(0).shape;
inputHeight = inputShape[1];
inputWidth = inputShape[2];
}
Future<List<DetectionResult>> detect(File imageFile) async {
final bytes = await imageFile.readAsBytes();
final decodedImage = img.decodeImage(bytes);
if (decodedImage == null) throw Exception("Could not decode image.");
return detectFromImage(decodedImage);
// 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];
}
Future<List<DetectionResult>> detectFromImage(img.Image originalImage) async {
final croppedResult = cropToModelAspectRatio(originalImage, inputWidth, inputHeight);
final fixedImage = img.bakeOrientation(croppedResult.image);
final inputTensor = imageToInputTensor(fixedImage, inputWidth, inputHeight);
/// 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()));
final inputBuffer = reshapeFloat(inputTensor.toList(), [1, inputHeight, inputWidth, 3]);
/// 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 outputShape = _interpreter.getOutputTensor(0).shape;
final numDetections = outputShape[1];
final outputBuffer = List.generate(1, (_) =>
List.generate(numDetections, (_) => List.filled(6, 0.0)));
_interpreter.run(inputBuffer, outputBuffer);
final rawDetections = outputBuffer[0];
final side = photo.side.toDouble();
final results = <DetectionResult>[];
for (var detection in rawDetections) {
final x1 = detection[0];
final y1 = detection[1];
final x2 = detection[2];
final y2 = detection[3];
final score = detection[4];
final classId = detection[5].toInt();
for (final d in rows) {
final score = d[4];
if (score < confidenceThreshold) continue;
// The model outputs coordinates normalized to [0, 1] relative to the input tensor (inputWidth x inputHeight)
// We need to scale back to the original cropped image coordinates
// The cropped image (cropWidth x cropHeight) was resized to (inputWidth x inputHeight)
final scaledX1 = x1 * croppedResult.cropWidth;
final scaledY1 = y1 * croppedResult.cropHeight;
final scaledX2 = x2 * croppedResult.cropWidth;
final scaledY2 = y2 * croppedResult.cropHeight;
// Add offset to get coordinates in the original image space
results.add(DetectionResult(
scaledX1 + croppedResult.offsetX,
scaledY1 + croppedResult.offsetY,
scaledX2 + croppedResult.offsetX,
scaledY2 + croppedResult.offsetY,
score,
classId,
));
// 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();
}
List<List<List<List<double>>>> reshapeFloat(List<double> flat, List<int> dims) {
final d0 = dims[0], d1 = dims[1], d2 = dims[2], d3 = dims[3];
final reshaped = List.generate(d0, (_) =>
List.generate(d1, (_) =>
List.generate(d2, (_) => List.filled(d3, 0.0))));
int index = 0;
for (int i = 0; i < d0; i++) {
for (int j = 0; j < d1; j++) {
for (int k = 0; k < d2; k++) {
for (int l = 0; l < d3; l++) {
reshaped[i][j][k][l] = flat[index++];
}
}
}
}
return reshaped;
}
CroppedImageResult cropToModelAspectRatio(img.Image image, int targetWidth, int targetHeight) {
final targetAspectRatio = targetWidth / targetHeight;
final originalAspectRatio = image.width / image.height;
int cropWidth = image.width;
int cropHeight = image.height;
if (originalAspectRatio > targetAspectRatio) {
cropWidth = (image.height * targetAspectRatio).toInt();
} else {
cropHeight = (image.width / targetAspectRatio).toInt();
}
final offsetX = ((image.width - cropWidth) / 2).toInt();
final offsetY = ((image.height - cropHeight) / 2).toInt();
final croppedImage = img.copyCrop(image, x: offsetX, y: offsetY, width: cropWidth, height: cropHeight);
return CroppedImageResult(croppedImage, offsetX, offsetY, cropWidth, cropHeight);
}
Float32List imageToInputTensor(img.Image inputImage, int width, int height) {
final resized = img.copyResize(inputImage, width: width, height: height);
final Float32List input = Float32List(width * height * 3);
int index = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final pixel = resized.getPixel(x, y);
final r = pixel.r / 255.0;
final g = pixel.g / 255.0;
final b = pixel.b / 255.0;
input[index++] = r;
input[index++] = g;
input[index++] = b;
}
}
return input;
}
}