tflite_service.dartобразноеimport 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as img;
import 'package:tflite_flutter/tflite_flutter.dart';
class TFLiteService {
late Interpreter _interpreter;
final int inputSize = 640;
late List _labels;
Future loadModel() async {
try {
// Load model from assets
final modelData = await rootBundle.load('assets/best_saved_model_YOLOv11/best_float32.tflite');
final interpreterOptions = InterpreterOptions();
_interpreter = await Interpreter.fromBuffer(
modelData.buffer.asUint8List(),
options: interpreterOptions,
);
print("
print('
print("
print('
// Load labels
final labelsData = await rootBundle.loadString('assets/best_saved_model_YOLOv11/labels.txt');
_labels = labelsData
.split('\n')
.map((label) => label.trim())
.where((label) => label.isNotEmpty)
.toList();
print("
} catch (e) {
print("
}}
Future detectObjects(File imageFile) async {
final img.Image? image = img.decodeImage(imageFile.readAsBytesSync());
if (image == null) return [];
final originalWidth = image.width;
final originalHeight = image.height;
//
final img.Image resizedImage = img.copyResize(image, width: inputSize, height: inputSize);
//
final Float32List input = _imageToFloat32(resizedImage);
final output = List.generate(1, (_) => List.generate(8, (_) => List.filled(8400, 0.0)));
try {
_interpreter.run(input, output);
} catch (e) {
print("
return [];
}
final results = [];
for (int i = 0; i < 8400; i++) {
final double x = output[0][0];
final double y = output[0][1];
final double w = output[0][2];
final double h = output[0][3];
final double objectness = output[0][4];
if (objectness < 0.4) continue;
final List classScores = [
output[0][5],
output[0][6],
output[0][7],
];
final double maxScore = classScores.reduce((a, b) => a > b ? a : b);
final int classIndex = classScores.indexOf(maxScore);
if (maxScore < 0.4) continue;
final double finalScore = objectness * maxScore;
final double left = (x - w / 2) / inputSize * originalWidth;
final double top = (y - h / 2) / inputSize * originalHeight;
final double right = (x + w / 2) / inputSize * originalWidth;
final double bottom = (y + h / 2) / inputSize * originalHeight;
final detection = {
"rect": {
"x": left / originalWidth,
"y": top / originalHeight,
"w": (right - left) / originalWidth,
"h": (bottom - top) / originalHeight,
},
"confidence": finalScore,
"detectedClass": _labels[classIndex],
};
results.add(detection);
//
print("
"\nScore: ${finalScore.toStringAsFixed(2)} ");
}
if (results.isEmpty) {
print("
}
return results;}
//
Float32List _imageToFloat32(img.Image image) {
final Float32List buffer = Float32List(inputSize * inputSize * 3);
int pixelIndex = 0;
for (int y = 0; y < inputSize; y++) {
for (int x = 0; x < inputSize; x++) {
final pixel = image.getPixel(x, y);
buffer[pixelIndex++] = pixel.r / 255.0;
buffer[pixelIndex++] = pixel.g / 255.0;
buffer[pixelIndex++] = pixel.b / 255.0;
}
}
return buffer;}}
< /code>
boxes.dart
import 'package:flutter/material.dart';
List renderBoxes(List results, Size screen) {
return results.map((result) {
final box = result["rect"];
final label = result["detectedClass"];
final confidence = result["confidence"];
final x = box["x"];
final y = box["y"];
final w = box["w"];
final h = box["h"];
final left = x * screen.width;
final top = y * screen.height;
final boxWidth = w * screen.width;
final boxHeight = h * screen.height;
return Positioned(
left: left,
top: top,
width: boxWidth,
height: boxHeight,
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.green, width: 2),
borderRadius: BorderRadius.circular(8),
),
child: Align(
alignment: Alignment.topLeft,
child: Container(
color: Colors.green,
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
child: Text(
"$label ${(confidence * 100).toStringAsFixed(0)}%",
style: const TextStyle(
color: Colors.white,
fontSize: 12,
),
),
),
),
),
);}).toList();}
< /code>
Я также прикрепляю свой журнал здесь: < /p>
E/ActivityThread(15261): fail in deliverResultsIfNeeded java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
E/ActivityThread(15261): fail in deliverResultsIfNeeded java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
I/HandWritingStubImpl(15261): refreshLastKeyboardType: 1
I/HandWritingStubImpl(15261): getCurrentKeyboardType: 1
E/tflite (15261): tensorflow/lite/kernels/pad.cc:79 SizeOfDimension(op_context->paddings, 0) != op_context->dims (4 != 1)
E/tflite (15261): Node number 0 (PAD) failed to prepare.
I/flutter (15261):
Подробнее здесь: https://stackoverflow.com/questions/796 ... econdition
Мобильная версия