You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Google ML Kit检测眼睛开合概率始终为null的问题

问题原因

你当前使用的是默认配置的FaceDetector,默认情况下不会计算并返回眼睛开合概率,所以leftEyeOpenProbability和rightEyeOpenProbability会返回null。

解决方法

需要创建FaceDetectorOptions并启用眼睛开合概率检测,再用这个配置初始化FaceDetector。

修改后的完整代码如下:

Future<void> detectFacesInImage(String imagePath) async {
  final File imageFile = File(imagePath);
  final InputImage inputImage = InputImage.fromFile(imageFile);
  
  // 配置FaceDetector,启用眼睛开合概率检测
  final options = FaceDetectorOptions(
    enableEyeOpenProbability: true,
    // 可选:启用其他检测特征,比如微笑概率
    // enableSmileProbability: true,
    // 可选:切换到精准模式,提升检测精度但速度稍慢
    // performanceMode: FaceDetectorMode.accurate,
  );
  
  final FaceDetector faceDetector = GoogleMlKit.vision.faceDetector(options);

  try {
    final List<Face> faces = await faceDetector.processImage(inputImage);
    if (faces.isEmpty) {
      print('No faces detected in the image');
      showCustomSnackbar(title: 'error', message: 'No faces detected in the image', backgroundColor: Colors.red);
      return;
    }

    for (Face face in faces) {
      print('enter in face');
      final double? leftEyeOpenProbability = face.leftEyeOpenProbability;
      if (leftEyeOpenProbability != null) {
        print('Left eye open probability: $leftEyeOpenProbability');
      } else {
        print('Left eye open probability: $leftEyeOpenProbability');
        showCustomSnackbar(title: 'error', message: 'Left eye open probability not available', backgroundColor: Colors.red);
        return;
      }
      
      final double? rightEyeOpenProbability = face.rightEyeOpenProbability;
      if (rightEyeOpenProbability != null) {
        print('Right eye open probability: $rightEyeOpenProbability');
      } else {
        print('Right eye open probability: $rightEyeOpenProbability');
        showCustomSnackbar(title: 'error', message: 'Right eye open probability not available', backgroundColor: Colors.red);
        return;
      }
    }
  } catch (e) {
    showCustomSnackbar(title: 'error', message: 'Error detecting faces', backgroundColor: Colors.red);
    print('Error detecting faces: $e');
  } finally {
    faceDetector.close();
  }
}
注意事项
  • 确保你的Google ML Kit依赖版本为最新,避免版本兼容问题导致配置不生效
  • 若检测结果精度不足,可尝试将performanceMode设置为FaceDetectorMode.accurate,以牺牲少量速度为代价提升检测准确性

内容的提问来源于stack exchange,提问作者Sohail Anwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 02:55:02