avatarMostafa Ahmed

Summary

The website provides a comprehensive guide on integrating YOLOv8/9 object detection models into a Flutter application using TensorFlow Lite (.tflite), detailing the setup process, code implementation, and real-time object detection via a mobile device's camera.

Abstract

The article titled "YOLOv8/9 object detection in Flutter with TensorFlow Lite (.tflite) 2024" discusses the implementation of YOLO (You Only Look Once) object detection models within a Flutter mobile application framework. It explains the concept of object detection and how YOLO frames it as a regression problem, distinguishing it from image classification or recognition. The text highlights YOLO's advantages, such as speed, accuracy, generalization, and its open-source nature. The guide then walks through the necessary steps to deploy a YOLO model into a Flutter app, including setting up the environment, integrating the model, initializing the camera, and coding the user interface and detection functions. It also provides code snippets and instructions for loading the YOLO model, processing video streams, and displaying bounding boxes around detected objects. The article concludes with a list of sources and materials for further reference, including the flutter_vision and camera packages from Flutter's package repository.

Opinions

  • The author suggests that YOLO is a leading object detection model due to its speed, detection accuracy, generalization capabilities, and open-source availability.
  • The use of TensorFlow Lite for deploying YOLO models on mobile devices is emphasized for its efficiency and ease of use.
  • The article provides a subjective recommendation to use a pre-trained Yolov8 model for testing purposes, which is made available via a Google Drive link.
  • The author implies that the Flutter framework, combined with YOLO and TensorFlow Lite, is a robust solution for real-time object detection applications on mobile devices.
  • The inclusion of specific code examples and configuration settings indicates the author's confidence in the provided instructions for integrating YOLO models into Flutter apps.

YOLOv8/9 object detection in Flutter with TensorFlow Lite (.tflite) 2024

Object detection is a technique used in computer vision for the identification and localization of objects within an image or a video. Image Localization is the process of identifying the correct location of one or multiple objects using bounding boxes, which correspond to rectangular shapes around the objects.

This process is sometimes confused with image classification or image recognition, which aims to predict the class of an image or an object within an image into one of the categories or classes.

YOLO developers frame the object detection problem as a regression problem instead of a classification task by spatially separating bounding boxes and associating probabilities to each of the detected images using a single convolutional neural network (CNN) as shown here.

Separating images into small units and associating probabilities to each of the detected images

Some of the reasons why YOLO is leading the competition include its:

  • Speed
  • Detection accuracy
  • Good generalization
  • Open-source

Deploying YOLO model into flutter app to recognize objects by the phone camera:

- Create new project & Setup Your Environment:

In android/app/build.gradle, add the following setting in android block.

android{
        aaptOptions {
            noCompress 'tflite'
            noCompress 'lite'
        }
    }

In the same path of android/app/build.gradle, adjust “minSdkVersion”, “targetSdkVersion” and “compileSdkVersion” in android block as following:

android/app/build.gradle --> android block

In android/build.gradle, adjust “ext.kotlin_version” buildscript block to be as this:

buildscript {
    ext.kotlin_version = '1.7.10'
    repositories {
        google()
        mavenCentral()
    }

- Add your Yolov8 model into the project environment:

The model must be exported in form of “.tflite” to easy deployed on edge-device like the mobile phone. If you want to train your custom Yolov model in Python and export it in .tflite instead of .pt, you must follow the instructions here. I’ll insert here a ready pre-trained Yolov8 model for object detection for testing.

In your Flutter project: 1. Create a assets folder and place your labels file and model file in it. In pubspec.yaml add:

assets:
   - assets/labels.txt
   - assets/yolov8n.tflite

2. Import the required Packages flutter_vision / camera:

import 'package:flutter_vision/flutter_vision.dart';
import 'package:camera/camera.dart';

- Start Coding:

  1. Initialize the camera in your project as the following:
late List<CameraDescription> camerass;

2. Create “YoloVideo” class:

class YoloVideo extends StatefulWidget {
  const YoloVideo({Key? key}) : super(key: key);

  @override
  State<YoloVideo> createState() => _YoloVideoState();
}

class _YoloVideoState extends State<YoloVideo> {
// Here we start writing our code.
}

3. In “YoloVideo” class, declare the needed variables:

  late CameraController controller;
  late FlutterVision vision;
  late List<Map<String, dynamic>> yoloResults;
  
  CameraImage? cameraImage;
  bool isLoaded = false;
  bool isDetecting = false;
  double confidenceThreshold = 0.5;

4. Initialize the model and the camera:

  @override
  void initState() {
    super.initState();
    init();
  }
  init() async {
    camerass = await availableCameras();
    vision = FlutterVision();
    controller = CameraController(camerass[0], ResolutionPreset.high);
    controller.initialize().then((value) {
      loadYoloModel().then((value) {
        setState(() {
          isLoaded = true;
          isDetecting = false;
          yoloResults = [];
        });
      });
    });
  }
  @override
  void dispose() async {
    super.dispose();
    controller.dispose();
    await vision.closeYoloModel();
  }

5. Simple UI and determine Video Stream size

@override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;

    if (!isLoaded) {
      return const Scaffold(
        body: Center(
          child: Text("Model not loaded, waiting for it"),
        ),
      );
    }
    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: [
          AspectRatio(
            aspectRatio: controller.value.aspectRatio,
            child: CameraPreview(
              controller,
            ),
          ),
          ...displayBoxesAroundRecognizedObjects(size),
          Positioned(
            bottom: 75,
            width: MediaQuery.of(context).size.width,
            child: Container(
              height: 80,
              width: 80,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                    width: 5, color: Colors.white, style: BorderStyle.solid),
              ),
              child: isDetecting
                  ? IconButton(
                      onPressed: () async {
                        stopDetection();
                      },
                      icon: const Icon(
                        Icons.stop,
                        color: Colors.red,
                      ),
                      iconSize: 50,
                    )
                  : IconButton(
                      onPressed: () async {
                        await startDetection();
                      },
                      icon: const Icon(
                        Icons.play_arrow,
                        color: Colors.white,
                      ),
                      iconSize: 50,
                    ),
            ),
          ),
        ],
      ),
    );
  }

6. Loading of our model

  Future<void> loadYoloModel() async {
    await vision.loadYoloModel(
        labels: 'assets/CLASSES.txt',
        modelPath: 'assets/curr_float32.tflite',
        modelVersion: "yolov8",
        numThreads: 1,
        useGpu: true);
    setState(() {
      isLoaded = true;
    });
}


// Real-time object detection function by yoloOnFrame
  Future<void> yoloOnFrame(CameraImage cameraImage) async {
    final result = await vision.yoloOnFrame(
        bytesList: cameraImage.planes.map((plane) => plane.bytes).toList(),
        imageHeight: cameraImage.height,
        imageWidth: cameraImage.width,
        iouThreshold: 0.4,
        confThreshold: 0.4,
        classThreshold: 0.5);
    if (result.isNotEmpty) {
      setState(() {
        yoloResults = result;
      });
    }
  }

7. functions of Starting Video Stream & Start or Stop detection

  Future<void> startDetection() async {
    setState(() {
      isDetecting = true;
    });
    if (controller.value.isStreamingImages) {
      return;
    }
    await controller.startImageStream((image) async {
      if (isDetecting) {
        cameraImage = image;
        yoloOnFrame(image);
      }
    });
  }
  Future<void> stopDetection() async {
    setState(() {
      isDetecting = false;
      yoloResults.clear();
    });
  }

8. Bounding boxes around the detected objects

  List<Widget> displayBoxesAroundRecognizedObjects(Size screen) {
    if (yoloResults.isEmpty) return [];
    double factorX = screen.width / (cameraImage?.height ?? 1);
    double factorY = screen.height / (cameraImage?.width ?? 1);

    Color colorPick = const Color.fromARGB(255, 50, 233, 30);

    return yoloResults.map((result) {
      double objectX = result["box"][0] * factorX;
      double objectY = result["box"][1] * factorY;
      double objectWidth = (result["box"][2] - result["box"][0]) * factorX;
      double objectHeight = (result["box"][3] - result["box"][1]) * factorY;
      
      speak() {
        String currentResult = result['tag'].toString();
        DateTime currentTime = DateTime.now();

        if (currentResult != previousResult ||
            currentTime.difference(previousSpeechTime) >= repeatDuration) {
          tts.flutterSpeak(currentResult);
          previousResult = currentResult;
          previousSpeechTime = currentTime;
        }
      }
      speak();

      return Positioned(
        left: objectX,
        top: objectY,
        width: objectWidth,
        height: objectHeight,
        child: Container(
          decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(10.0)),
            border: Border.all(color: Colors.pink, width: 2.0),
          ),
          child: Text(
            "${result['tag']} ${(result['box'][4] * 100)}",
            style: TextStyle(
              background: Paint()..color = colorPick,
              color: const Color.fromARGB(255, 115, 0, 255),
              fontSize: 18.0,
            ),
          ),
        ),
      );
    }).toList();
  }
}

Finally, you can call the YoloVideo class as a function in Main.dart to start video stream and real-time object detection when starting the application to as the following:

main() async {
  WidgetsFlutterBinding.ensureInitialized();


  runApp(
    const MaterialApp(
      home: YoloVideo(),
    ),
  );
}
Screenshots from my Yolov8 Flutter app

Sources & Materials:

  1. flutter_vision | Flutter package (pub.dev)
  2. https://drive.google.com/drive/folders/15LU4lWiMx8DjBXE7q7Efx65OF4Zb-5ZA?usp=sharing
  3. YOLO Object Detection Explained: A Beginner’s Guide | DataCamp
  4. camera | Flutter package (pub.dev)
  5. Flutter AI | Flutter Realtime Object Detection | Flutter Deep Learning | Flutter TensorFlow | TFlite (youtube.com)
  6. TFLite — Ultralytics YOLOv8 Docs
  7. https://github.com/AarohiSingla/Object-Detection-Android-App
Mobile App Development
Flutter
TensorFlow
Tensorflow Lite
Object Detection
Recommended from ReadMedium