有没有办法将AI图像处理移至单独的线程?

问题描述 投票:0回答:2

需要帮助提高此功能的性能。有没有办法将 AI 处理逻辑移动到单独的线程,因为一旦我startImageStream,应用程序就感觉很垃圾。

class SessionRecordingScreen extends StatefulWidget {
  const SessionRecordingScreen({super.key});

  @override
  State<SessionRecordingScreen> createState() => _SessionRecordingScreenState();
}

class _SessionRecordingScreenState extends State<SessionRecordingScreen> {
  ObjectDetector? _objectDetector;
  bool _canProcess = false;
  bool _isBusy = false;
  bool _isInitialized = false;
  final _model = 'assets/ml/yolov8_small.tflite';

  int catches = 0;
  int droppedBalls = 0;

  void _initializeDetector() async {
    _objectDetector?.close();
    _objectDetector = null;
    final modelPath = await getAssetPath(_model);
    final options = LocalObjectDetectorOptions(
      mode: DetectionMode.stream,
      modelPath: modelPath,
      classifyObjects: true,
      multipleObjects: true,
    );
    _objectDetector = ObjectDetector(options: options);
    _canProcess = true;
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      child: Material(
        child: CameraViewWidget(
          onImage: _processImage,
          onCameraFeedReady: () {
            if (!_isInitialized) {
              _initializeDetector();
              _isInitialized = true;
            }
          },
          catches: catches,
          droppedBalls: droppedBalls,
        ),
      ),
    );
  }

  Future<void> _processImage(InputImage inputImage) async {
    if (!_canProcess || _isBusy) return;
    _isBusy = true;

    final List<Object> results =
        await _objectDetector!.processImage(inputImage);

    if (results.isEmpty) {
      _isBusy = false;
      return;
    }
    _isBusy = false;
  }
}

CameraViewWidget只是一个CameraWidget,带有InputImage解析器,因为我需要它用于google_ml_kit。

我尝试使用计算和隔离,但没有成功。谢谢你的帮助

flutter google-mlkit
2个回答
0
投票

您可以调整您的实现以删除这些异步/等待,从而对您的解决方案采用并发方法。

在 flutter/dart 中,如果您想使用并发解决方案,您将需要了解如何使用

Isolate class
在这篇 LinkedIn 帖子(不是我的)中,有一个如何使用它的示例,我认为这是针对您的情况的完美解决方案。

并且在此链接中有关于 Flutter/Dart 上并发的官方文档。


0
投票
  1. 使用 tflite_flutter 代替已更新的 flutter_tflite。
  2. 将isolateInterpreter与tflite_flutter结合使用。或者您可以将预处理和检测移至新的分离株。例如,你可以参考tflite_flutter中的这个例子:link
© www.soinside.com 2019 - 2024. All rights reserved.