{"id":26714232,"url":"https://github.com/azizbekeshpolatov/face_detection_example","last_synced_at":"2026-04-13T18:02:16.233Z","repository":{"id":284216428,"uuid":"954212357","full_name":"AzizbekEshpolatov/face_detection_example","owner":"AzizbekEshpolatov","description":"google_mlkit_face_detection package-dan foydalangan xolda userning yuz qiyofasini aniqlaydigan kichik test project.","archived":false,"fork":false,"pushed_at":"2025-03-24T18:29:19.000Z","size":17,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-24T19:34:32.685Z","etag":null,"topics":["camera","dart","flutter","google-ml-kit","permission-handler"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AzizbekEshpolatov.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-24T18:22:54.000Z","updated_at":"2025-03-24T18:30:56.000Z","dependencies_parsed_at":"2025-03-24T19:45:00.630Z","dependency_job_id":null,"html_url":"https://github.com/AzizbekEshpolatov/face_detection_example","commit_stats":null,"previous_names":["azizbekeshpolatov/face_detection_example"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/AzizbekEshpolatov/face_detection_example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AzizbekEshpolatov%2Fface_detection_example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AzizbekEshpolatov%2Fface_detection_example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AzizbekEshpolatov%2Fface_detection_example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AzizbekEshpolatov%2Fface_detection_example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AzizbekEshpolatov","download_url":"https://codeload.github.com/AzizbekEshpolatov/face_detection_example/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AzizbekEshpolatov%2Fface_detection_example/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259749898,"owners_count":22905796,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["camera","dart","flutter","google-ml-kit","permission-handler"],"created_at":"2025-03-27T13:18:48.710Z","updated_at":"2026-04-13T18:02:16.199Z","avatar_url":"https://github.com/AzizbekEshpolatov.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Face Detection Example  \nBu loyiha Flutter va Google ML Kit yordamida yuzni aniqlash uchun ishlatiladi. Ilova kameradan foydalangan holda foydalanuvchi yuzining turli holatlarini aniqlaydi va ko‘rsatmalar beradi.  \n---\n\n## Dependencies\nLoyiha quyidagi paketlardan foydalanadi:  \n```yaml\ndependencies:\n  flutter:\n    sdk: flutter\n  google_mlkit_face_detection: ^0.9.1\n  camera: ^0.10.5+9\n  permission_handler: ^11.3.0\n```\n## 🌍 Tilga Mos Tarjimalar (Translations)  \nLoyiha uch tilda qo'llab-quvvatlaydi: **Uzbek, English, Russian**  \n\n## Code\n```dart\nimport 'dart:math';\nimport 'package:car_land/core/common/words.dart';\nimport 'package:car_land/core/extension/message_extension.dart';\nimport 'package:car_land/core/extension/size_extension.dart';\nimport 'package:flutter/foundation.dart';\nimport 'package:flutter/material.dart';\nimport 'package:camera/camera.dart';\nimport 'package:google_mlkit_face_detection/google_mlkit_face_detection.dart';\nimport 'package:permission_handler/permission_handler.dart';\n\nclass FaceDetectionPage extends StatefulWidget {\n  const FaceDetectionPage({super.key});\n\n  @override\n  State\u003cFaceDetectionPage\u003e createState() =\u003e _FaceDetectionPageState();\n}\n\nclass _FaceDetectionPageState extends State\u003cFaceDetectionPage\u003e {\n  CameraController? _cameraController;\n  FaceDetector? _faceDetector;\n  bool _isDetecting = false;\n  List\u003cFace\u003e _faces = [];\n  String _currentTask = 'take_action';\n  String _displayMessage = Words.faceNotDetected.tr();\n  int _countdown = 0;\n  bool _isCountingDown = false;\n  final List\u003cString\u003e _tasks = [\n    \"look_left\",\n    \"look_right\",\n    \"look_up\",\n    \"look_down\",\n    \"smile\",\n    \"close_eyes\"\n  ];\n  final Random _random = Random();\n  bool _isCameraInitialized = false;\n\n  @override\n  void initState() {\n    super.initState();\n    _initializeFaceDetector();\n    _requestCameraPermission();\n  }\n\n  void _initializeFaceDetector() {\n    final options = FaceDetectorOptions(\n      enableContours: true,\n      enableLandmarks: true,\n      enableClassification: true,\n      performanceMode: FaceDetectorMode.fast,\n    );\n    _faceDetector = FaceDetector(options: options);\n  }\n\n  Future\u003cvoid\u003e _requestCameraPermission() async {\n    var status = await Permission.camera.status;\n    if (!status.isGranted) status = await Permission.camera.request();\n\n    if (status.isGranted) {\n      _initializeCamera();\n    } else if (status.isDenied) {\n      showErrors(Words.cameraPermissionDenied.tr());\n    } else if (status.isPermanentlyDenied) {\n      showErrors(Words.cameraPermissionPermanentlyDenied.tr());\n      await openAppSettings();\n    }\n  }\n\n  Future\u003cvoid\u003e _initializeCamera() async {\n    try {\n      final cameras = await availableCameras();\n      if (cameras.isEmpty) {\n        showErrors(Words.noCameraFound.tr());\n        return;\n      }\n\n      final frontCamera = cameras.firstWhere(\n        (camera) =\u003e camera.lensDirection == CameraLensDirection.front,\n        orElse: () =\u003e cameras.first,\n      );\n\n      _cameraController = CameraController(\n        frontCamera,\n        ResolutionPreset.high,\n        enableAudio: false,\n        imageFormatGroup: defaultTargetPlatform == TargetPlatform.android\n            ? ImageFormatGroup.nv21\n            : ImageFormatGroup.jpeg,\n      );\n\n      await _cameraController!.initialize();\n      if (mounted) {\n        setState(() =\u003e _isCameraInitialized = true);\n      }\n      _cameraController?.startImageStream(_processCameraImage);\n    } catch (e) {\n      showErrors(\"${Words.cameraInitError.tr()}:${e.toString()}\");\n    }\n  }\n\n  Future\u003cvoid\u003e _processCameraImage(CameraImage image) async {\n    if (_isDetecting || _isCountingDown) return;\n    _isDetecting = true;\n    try {\n      final WriteBuffer allBytes = WriteBuffer();\n      for (final Plane plane in image.planes) {\n        allBytes.putUint8List(plane.bytes);\n      }\n      final Uint8List bytes = allBytes.done().buffer.asUint8List();\n\n      final Size imageSize = Size(\n        image.width.toDouble(),\n        image.height.toDouble(),\n      );\n\n      final InputImageRotation imageRotation = _getImageRotation();\n\n      final bytesPerRow = image.planes[0].bytesPerRow;\n      if (bytesPerRow == 0) {\n        debugPrint(\"Xatolik: bytesPerRow 0 ga teng. Buni tuzatish lozim.\");\n        _isDetecting = false;\n        return;\n      }\n\n      final inputImageData = InputImageMetadata(\n        size: imageSize,\n        rotation: imageRotation,\n        format: defaultTargetPlatform == TargetPlatform.android\n            ? InputImageFormat.nv21\n            : InputImageFormat.bgra8888,\n        bytesPerRow: bytesPerRow,\n      );\n\n      final inputImage = InputImage.fromBytes(\n        bytes: bytes,\n        metadata: inputImageData,\n      );\n\n      final List\u003cFace\u003e faces = await _faceDetector!.processImage(inputImage);\n\n      if (faces.isNotEmpty) {\n        _checkTaskCompletion(faces.first, inputImage.filePath);\n        setState(() {\n          _faces = faces;\n          if (_currentTask != 'hold_still') {\n            _displayMessage = _currentTask == 'take_action'\n                ? Words.takeAction.tr()\n                : _currentTask == 'done'\n                    ? Words.done.tr()\n                    : _currentTask == 'look_left'\n                        ? Words.lookLeft.tr()\n                        : _currentTask == 'look_right'\n                            ? Words.lookRight.tr()\n                            : _currentTask == 'look_up'\n                                ? Words.lookUp.tr()\n                                : _currentTask == 'look_down'\n                                    ? Words.lookDown.tr()\n                                    : _currentTask == 'smile'\n                                        ? Words.smile.tr()\n                                        : Words.closeEyes.tr();\n          }\n        });\n      } else {\n        setState(() {\n          _faces = [];\n          _displayMessage = Words.faceNotDetected.tr();\n        });\n      }\n      debugPrint('Aniqlangan yuzlar soni: ${faces.length}');\n    } catch (e) {\n      debugPrint(\"Rasmni qayta ishlashda xato: $e\");\n      setState(() =\u003e _displayMessage = 'Xato: $e');\n    } finally {\n      _isDetecting = false;\n    }\n  }\n\n  void _checkTaskCompletion(Face face, String? path) {\n    bool taskCompleted = false;\n    switch (_currentTask) {\n      case \"look_right\":\n        if (face.headEulerAngleY != null \u0026\u0026 face.headEulerAngleY! \u003c -15) {\n          _tasks.remove(\"look_right\");\n          taskCompleted = true;\n        }\n        break;\n      case \"look_left\":\n        if (face.headEulerAngleY != null \u0026\u0026 face.headEulerAngleY! \u003e 15) {\n          _tasks.remove(\"look_left\");\n          taskCompleted = true;\n        }\n        break;\n      case \"look_up\":\n        if (face.headEulerAngleX != null \u0026\u0026 face.headEulerAngleX! \u003e 15) {\n          _tasks.remove(\"look_up\");\n          taskCompleted = true;\n        }\n        break;\n      case \"look_down\":\n        if (face.headEulerAngleX != null \u0026\u0026 face.headEulerAngleX! \u003c -15) {\n          _tasks.remove(\"look_down\");\n          taskCompleted = true;\n        }\n        break;\n      case \"smile\":\n        if (face.smilingProbability != null \u0026\u0026 face.smilingProbability! \u003e 0.7) {\n          _tasks.remove(\"smile\");\n          taskCompleted = true;\n          _startCountdown();\n        }\n        break;\n      case \"close_eyes\":\n        if ((face.leftEyeOpenProbability != null \u0026\u0026\n                face.leftEyeOpenProbability! \u003c 0.3) \u0026\u0026\n            (face.rightEyeOpenProbability != null \u0026\u0026\n                face.rightEyeOpenProbability! \u003c 0.3)) {\n          _tasks.remove(\"close_eyes\");\n          taskCompleted = true;\n        }\n        break;\n    }\n\n    if (taskCompleted || _currentTask == 'take_action') {\n      if (_currentTask != 'smile') {\n        setState(() {\n          _currentTask = _tasks.isNotEmpty\n              ? _tasks[_random.nextInt(_tasks.length)]\n              : 'done';\n        });\n      }\n    }\n\n    if (_tasks.isEmpty \u0026\u0026 !_isCountingDown) _startCountdown();\n  }\n\n  void _startCountdown() {\n    setState(() {\n      _currentTask = 'hold_still';\n      _isCountingDown = true;\n      _countdown = 0;\n      _displayMessage = Words.holdStillCountdown.tr();\n    });\n    Future.doWhile(() async {\n      await Future.delayed(const Duration(seconds: 1));\n      setState(() {\n        _countdown++;\n        _displayMessage = '${Words.holdStillCountdown.tr()} $_countdown';\n      });\n\n      if (_countdown == 3) {\n        _takePictureAndSendToBackend();\n        return false;\n      }\n      return true;\n    });\n  }\n\n  Future\u003cvoid\u003e _takePictureAndSendToBackend() async {\n    try {\n      final XFile? picture = await _cameraController?.takePicture();\n      if (picture != null) {\n        debugPrint(\"Backendga yuborildi: ${picture.path}\");\n        showSuccess(\"Success action!\");\n      } else {\n        debugPrint(\"Rasm olishda xato: Rasm topilmadi\");\n        showErrors('Rasm olishda xato: Rasm topilmadi');\n      }\n    } catch (e) {\n      debugPrint(\"Rasm olishda xato: $e\");\n      showErrors('Rasm olishda xato: $e');\n    } finally {\n      setState(() {\n        _isCountingDown = false;\n        _currentTask = 'done';\n        _displayMessage = Words.done.tr();\n      });\n    }\n  }\n\n  InputImageRotation _getImageRotation() {\n    final int sensorOrientation =\n        _cameraController!.description.sensorOrientation;\n    switch (sensorOrientation) {\n      case 90:\n        return InputImageRotation.rotation90deg;\n      case 180:\n        return InputImageRotation.rotation180deg;\n      case 270:\n        return InputImageRotation.rotation270deg;\n      default:\n        return InputImageRotation.rotation0deg;\n    }\n  }\n\n  @override\n  void dispose() {\n    _cameraController?.dispose();\n    _faceDetector?.close();\n    super.dispose();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    if (!_isCameraInitialized ||\n        _cameraController == null ||\n        !_cameraController!.value.isInitialized) {\n      return const Scaffold(\n        body: Center(child: CircularProgressIndicator()),\n      );\n    }\n\n    final size = MediaQuery.of(context).size;\n    final cameraPreviewSize = Size(\n      _cameraController!.value.previewSize!.height,\n      _cameraController!.value.previewSize!.width,\n    );\n\n    return Scaffold(\n      body: Stack(\n        fit: StackFit.expand,\n        children: [\n          CameraPreview(_cameraController!),\n          Positioned(\n            top: 50,\n            left: 0,\n            right: 0,\n            child: Center(\n              child: Container(\n                padding: const EdgeInsets.all(10),\n                decoration: BoxDecoration(\n                  color: Colors.black54,\n                  borderRadius: BorderRadius.circular(10),\n                ),\n                child: Text(\n                  _displayMessage,\n                  style: const TextStyle(color: Colors.white, fontSize: 20),\n                ),\n              ),\n            ),\n          ),\n          ..._faces.map((face) {\n            final rect = face.boundingBox;\n\n            final scaleX = size.width / cameraPreviewSize.width;\n            final scaleY = size.height / cameraPreviewSize.height;\n\n            return Positioned(\n              left: rect.left * scaleX,\n              top: rect.top * scaleY,\n              width: rect.width * scaleX,\n              height: rect.height * scaleY,\n              child: Container(\n                decoration: BoxDecoration(\n                  border: Border.all(color: Colors.red, width: 2.w),\n                ),\n              ),\n            );\n          }),\n        ],\n      ),\n    );\n  }\n}\n\n```\n\n### tarjimalar  \n```dart\nfinal Map\u003cString, String\u003e taskMessagesUz = {\n  'takeAction': \"Harakatni boshlash\",\n  'done': \"Tugallandi\",\n  'lookLeft': \"Chapga qarang\",\n  'lookRight': \"O‘ngga qarang\",\n  'lookUp': \"Tepaga qarang\",\n  'lookDown': \"Pastga qarang\",\n  'smile': \"Tabassum qiling\",\n  'closeEyes': \"Ko‘zingizni yuming\",\n  'holdStill': \"Qimirlamang\",\n  'faceNotDetected': \"Yuz aniqlanmadi\",\n  'cameraPermissionPermanentlyDenied': \n      \"Kamera ruxsati doimiy rad etilgan. Iltimos, sozlamalardan ruxsat bering.\",\n  'cameraPermissionDenied': \"Kamera ruxsati berilmadi! Iltimos, ruxsat bering.\",\n  'noCameraFound': \"Hech qanday kamera topilmadi!\",\n  'cameraInitError': \"Kamera initsializatsiyasida xato:\",\n  'holdStillCountdown': \"Qimirlamay turing: \",\n};\nfinal Map\u003cString, String\u003e taskMessagesRu = {\n  'takeAction': \"Начните действие\",\n  'done': \"Завершено\",\n  'lookLeft': \"Посмотрите налево\",\n  'lookRight': \"Посмотрите направо\",\n  'lookUp': \"Посмотрите вверх\",\n  'lookDown': \"Посмотрите вниз\",\n  'smile': \"Улыбайтесь\",\n  'closeEyes': \"Закройте глаза\",\n  'holdStill': \"Замрите\",\n  'faceNotDetected': \"Лицо не обнаружено\",\n  'cameraPermissionPermanentlyDenied': \n      \"Доступ к камере был отклонен навсегда. Разрешите доступ в настройках.\",\n  'cameraPermissionDenied': \"Доступ к камере отклонен! Пожалуйста, разрешите доступ.\",\n  'noCameraFound': \"Камера не найдена!\",\n  'cameraInitError': \"Ошибка инициализации камеры:\",\n  'holdStillCountdown': \"Замрите: \",\n};\nfinal Map\u003cString, String\u003e taskMessagesEn = {\n  'takeAction': \"Start the action\",\n  'done': \"Completed\",\n  'lookLeft': \"Look to the left\",\n  'lookRight': \"Look to the right\",\n  'lookUp': \"Look up\",\n  'lookDown': \"Look down\",\n  'smile': \"Smile\",\n  'closeEyes': \"Close your eyes\",\n  'holdStill': \"Hold still\",\n  'faceNotDetected': \"Face not detected\",\n  'cameraPermissionPermanentlyDenied': \n      \"Camera permission is permanently denied. Please allow it from settings.\",\n  'cameraPermissionDenied': \"Camera permission denied! Please allow access.\",\n  'noCameraFound': \"No camera found!\",\n  'cameraInitError': \"Camera initialization error:\",\n  'holdStillCountdown': \"Hold still: \",\n};\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fazizbekeshpolatov%2Fface_detection_example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fazizbekeshpolatov%2Fface_detection_example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fazizbekeshpolatov%2Fface_detection_example/lists"}