Flutter猫头鹰检测相机插件owl_detection_camera的使用

Flutter猫头鹰检测相机插件owl_detection_camera的使用

OWL Face和QRCode检测相机库用于Flutter

一个允许访问设备摄像头以自动检测面部和QR码的Flutter插件。

iOS:

image

Android:

image

特性

  • 在小部件中显示实时摄像头预览。
  • 捕获面部照片。
  • 获取QR码内容结果。
  • 调整屏幕亮度。
  • 在前摄像头和后摄像头之间切换。
  • 支持Android上的横屏模式。

安装

pubspec.yaml文件中添加以下依赖:

dependencies:
  owl_detection_camera: ^0.2.7

iOS

owl_detection_camera功能适用于iOS 13.0或更高版本。如果编译版本低于13.0,则在使用任何owl_detection_camera插件功能之前,确保检查设备上运行的iOS版本。例如,可以使用permission_handler插件来检查权限。

ios/Runner/Info.plist中添加以下几行:

  • Privacy - Camera Usage Description…
  • Privacy - Photo Library Additions Usage Description.
  • Privacy - Photo Library Usage Description.

Android

在你的android/app/build.gradle文件中将最低Android SDK版本更改为23(或更高)。

minSdkVersion 23

使用

查看示例。

许可证

AGPL-3.0 许可证


示例代码

example/lib/main.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:owl_detection_camera/owl_detection_camera.dart';
import 'package:owl_detection_camera/owl_camera_defines.dart';
import 'package:permission_handler/permission_handler.dart';

void main()
{
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver
{
  [@override](/user/override)
  void initState()
  {
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
  }

  [@override](/user/override)
  void dispose() {
    WidgetsBinding.instance!.removeObserver(this);
    super.dispose();
  }

  [@override](/user/override)
  void didChangeAppLifecycleState(AppLifecycleState state)
  {
    // 不会立即调用。
    print("didChangeAppLifecycleState $state");

    if (state == AppLifecycleState.resumed) // 需要在Android版本中调用resume事件。
    {
      if(Theme.of(context).platform == TargetPlatform.android)
      {
        OwlDetectionCamera.onResumeEvent();
      }
    }
    else if(state == AppLifecycleState.paused) // 需要在Android版本中调用pause事件。
    {
      if(Theme.of(context).platform == TargetPlatform.android)
      {
        OwlDetectionCamera.onPauseEvent();
      }
    }
    super.didChangeAppLifecycleState(state);
  }

  [@override](/user/override)
  Widget build(BuildContext context)
  {
    return MaterialApp(
        home: Preview()
    );
  }
}

class Preview extends StatefulWidget
{
  [@override](/user/override)
  _PreviewState createState() => _PreviewState();
}

class _PreviewState extends State<Preview>
{
  bool mIsDetectSuccess = false;
  bool mIsQRcode = false;

  bool mIsBrightness = true;
  bool mIsDisableHint = true;

  String mImagePath = "";
  String mQRcodeResult = "";

  PermissionData mPermissionData = PermissionData(PermissionsState.checking);
  List<Permission> mPermission = [];

  [@override](/user/override)
  void initState()
  {
    super.initState();

    OwlDetectionCamera.onImageCallbacks = (name, path)
    {
      if(!mIsDetectSuccess)
      {
        mImagePath = path;
        mIsDetectSuccess = true;
        setState(() {});
      }
    };

    /// iOS可能需要设备像素比来进行实际屏幕像素的计算。
    OwlDetectionCamera.onFaceRectangleCallback = (Rect aValue)
    {
      print("Face Rectangle :$aValue");
    };

    OwlDetectionCamera.onQRcodeCallback = (String aValue)
    {
      if(!mIsQRcode)
      {
        mQRcodeResult = aValue;
        mIsQRcode = true;
        setState(() {});
      }
    };

    OwlDetectionCamera.onOnWriteSettingPermissionCallback = (bool aValue)
    {
      print("WriteSettingPermissionCallback has:${aValue}");
    };

    OwlDetectionCamera.writeSettingPermission();
  }

  void checkPermission(List<Permission> aPermissions) async
  {
    if(mPermission.isEmpty)
    {
      mPermission = aPermissions;
    }

    Permission temp = mPermission.removeLast();

    if(await temp.request().isGranted)
    {
      if(!mPermission.isEmpty)
      {
        checkPermission(mPermission);
      }
      else{
        mPermissionData.mPermissionsState = PermissionsState.grainted;
        setState(() {});
      }
    }else
    {
      mPermissionData.mPermissionsState = PermissionsState.deny;
      mPermissionData.mPermissionName = temp.toString();
      setState(() {});
    }
  }

  Widget check(List<Permission> aPermission)
  {
    checkPermission(aPermission);
    return const Center(
      child: Text("Loading..."),
    );
  }

  Widget pleaseGivePermission()
  {
    return const Center(
      child: Text("Please give permissions."),
    );
  }

  Widget successImage(String aFilePath)
  {
    updateView();
    return Image.file(File(aFilePath),
      scale: 4,
      fit: BoxFit.fill,
    );
  }

  Widget centerText(String aText)
  {
    updateView();
    return Center(
      child: Text(aText),
    );
  }

  void updateView() async
  {
    await Future.delayed(const Duration(milliseconds: 2000), ()
    {
      setState(() {
        mIsDetectSuccess = false;
        mIsQRcode= false;
        OwlDetectionCamera.startDetection();
      });
    });
  }

  Widget preview(var size, var ratio)
  {
    var faceFrameWidth = 0.0, faceFrameHeight = 0.0;
    if(size.width < size.height)
    {
      faceFrameWidth = size.width / 1.5;
      faceFrameHeight = faceFrameWidth * 1.25;
    }
    else
    {
      faceFrameHeight = size.height / 1.5;
      faceFrameWidth = faceFrameHeight * 1.25;
    }

    var pendingWidth = size.width - faceFrameWidth;
    var pendingHeight = size.height - faceFrameHeight;

    if(Theme.of(context).platform == TargetPlatform.android)
    {
      OwlDetectionCamera.passFaceFrameSize((faceFrameWidth.toInt() * ratio).toInt(), (faceFrameHeight.toInt() * ratio).toInt());
    }
    else
    {
      OwlDetectionCamera.passFaceFrameSize(faceFrameWidth.toInt(), faceFrameHeight.toInt());
    }

    return Stack(
        children: [
          OwlDetectionCamera(),
          Positioned(
              left: pendingWidth / 2,
              top: pendingHeight / 2,
              child:
              mIsDetectSuccess ?
              Image.asset("assets/face_v3_success.png",
                  fit: BoxFit.scaleDown,
                  width: faceFrameWidth,
                  height: faceFrameHeight)
                  :
              Image.asset("assets/face_v3_normal.png",
                  fit: BoxFit.scaleDown,
                  width: faceFrameWidth,
                  height: faceFrameHeight)
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              width: size.width,
              child:
              Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Expanded(
                        flex: 1,
                        child:  ElevatedButton(
                            child:
                            Text("Start", style: TextStyle(fontSize: 10),),
                            onPressed: (){
                              OwlDetectionCamera.startDetection();
                            }),
                      ),
                      Expanded(
                        flex: 1,
                        child:  ElevatedButton(
                            child:
                            Text("Stop", style: TextStyle(fontSize: 10)),
                            onPressed: (){
                              OwlDetectionCamera.stopDetection();
                            }),
                      ),
                      Expanded(
                        flex: 1,
                        child: ElevatedButton(
                            child:
                            Text("Brightness", style: TextStyle(fontSize: 10)),
                            onPressed: (){
                              OwlDetectionCamera.screenBright(mIsBrightness ? OwlCameraDefine.SCREEN_DARK : OwlCameraDefine.SCREEN_BRIGHT);
                              mIsBrightness = !mIsBrightness;
                            }),
                      ),
                      Expanded(
                        flex: 1,
                        child: ElevatedButton(
                            child:
                            Text("Disable Hint", style: TextStyle(fontSize: 10)),
                            onPressed: (){
                              OwlDetectionCamera.disableHint(mIsDisableHint);
                              mIsDisableHint = !mIsDisableHint;
                            }),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Expanded(
                        flex: 1,
                        child: ElevatedButton(
                            child:
                            Text("Detect QRcode", style: TextStyle(fontSize: 10)),
                            onPressed: ()
                            {
                              OwlDetectionCamera.setDetectionMode(OwlCameraDefine.QRCODE_MODE);
                            }) ,
                      ),
                      Expanded(
                        flex: 1,
                        child: ElevatedButton(
                            child:
                            Text("Detect Face", style: TextStyle(fontSize: 10)),
                            onPressed: ()
                            {
                              OwlDetectionCamera.setDetectionMode(OwlCameraDefine.FACE_MODE);
                            }),
                      ),
                      Expanded(
                        flex: 1,
                        child: ElevatedButton(
                            child:
                            Text("Blend mode", style: TextStyle(fontSize: 10)),
                            onPressed: ()
                            {
                              OwlDetectionCamera.setDetectionMode(OwlCameraDefine.BLEND_MODE);
                            }),
                      ),
                      Expanded(
                        flex: 1,
                        child: ElevatedButton(
                            child:
                            Text("Switch Camera", style: TextStyle(fontSize: 10)),
                            onPressed: ()
                            {
                              OwlDetectionCamera.switchCamera();
                            }),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          Align(
            child: mIsDetectSuccess ? successImage(mImagePath) : Text(""),
          ),
          Align(
            child: mIsQRcode ? centerText(mQRcodeResult) : Text(""),
          )
        ]
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context)
  {
    Size size = MediaQuery.of(context).size;

    var ratio = MediaQuery.of(context).devicePixelRatio;

    return Theme.of(context).platform == TargetPlatform.android
        ?
    Scaffold(
      resizeToAvoidBottomInset: false,
      body:
      mPermissionData.mPermissionsState == PermissionsState.checking ?
      check(Constants.sPermission)
          :
      mPermissionData.mPermissionsState == PermissionsState.grainted ?
      preview(size, ratio)
          :
      centerText("Please give permissions."),
    )
        :
    Scaffold(
      resizeToAvoidBottomInset: false,
      body: preview(size, ratio),
    );
  }
}

enum PermissionsState
{
  checking,
  grainted,
  deny
}

class PermissionData
{
  String? mPermissionName;
  PermissionsState mPermissionsState;
  PermissionData(this.mPermissionsState, {this.mPermissionName});
}

class Constants
{
  static List<Permission> sPermission = [Permission.camera, Permission.phone];
}

更多关于Flutter猫头鹰检测相机插件owl_detection_camera的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter猫头鹰检测相机插件owl_detection_camera的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用Flutter猫头鹰检测相机插件 owl_detection_camera 的示例代码。这个示例假设你已经有一个基本的Flutter项目结构,并且已经添加了 owl_detection_camera 插件到你的 pubspec.yaml 文件中。

首先,确保你的 pubspec.yaml 文件中包含以下依赖项:

dependencies:
  flutter:
    sdk: flutter
  owl_detection_camera: ^最新版本号  # 请替换为实际的最新版本号

然后,运行 flutter pub get 来安装依赖项。

接下来,在你的 main.dart 文件中,你可以按照以下步骤设置猫头鹰检测相机功能:

import 'package:flutter/material.dart';
import 'package:owl_detection_camera/owl_detection_camera.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Owl Detection Camera Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: OwlDetectionCameraScreen(),
    );
  }
}

class OwlDetectionCameraScreen extends StatefulWidget {
  @override
  _OwlDetectionCameraScreenState createState() => _OwlDetectionCameraScreenState();
}

class _OwlDetectionCameraScreenState extends State<OwlDetectionCameraScreen> {
  OwlDetectionCameraController? _controller;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();
    _initializeCamera();
  }

  Future<void> _initializeCamera() async {
    _controller = OwlDetectionCameraController(
      // 配置你的相机参数,例如分辨率等
      resolutionPreset: ResolutionPreset.high,
      enableAudio: false,
      imageFormatGroup: ImageFormatGroup.yuv420,
    );

    // 当相机初始化完成时,设置监听器
    _controller!.initialize().then((_) {
      if (!mounted) return;
      setState(() {});
    }).catchError((Object error) {
      if (mounted) {
        ScaffoldMessenger.of(_scaffoldKey.currentContext!)
            .showSnackBar(SnackBar(content: Text('Error: $error')));
      }
    });
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('Owl Detection Camera'),
      ),
      body: _controller!.value.isInitialized
          ? AspectRatio(
              aspectRatio: _controller!.value.aspectRatio,
              child: OwlDetectionCameraPreview(_controller!),
            )
          : Container(
              child: Center(child: CircularProgressIndicator()),
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          try {
            final OwlDetectionResult? result = await _controller!.captureOwlDetectionImage();
            if (result != null) {
              // 处理检测结果,例如显示猫头鹰检测框
              // 这里假设 result.boxes 是一个包含检测框的列表
              print('Owl detected with boxes: ${result.boxes}');
              // 你可以在这里显示检测结果,或者进行进一步处理
            }
          } catch (e) {
            print('Error capturing image: $e');
          }
        },
        tooltip: 'Capture Owl Detection Image',
        child: Icon(Icons.camera_alt),
      ),
    );
  }
}

请注意,OwlDetectionCameraControllerOwlDetectionCameraPreview 是假设的类名,实际使用时请参照 owl_detection_camera 插件的文档来确定正确的类名和方法。同时,OwlDetectionResultboxes 属性也是假设的,你需要根据插件的实际API来调整代码。

此外,这个示例代码没有包含猫头鹰检测的具体实现细节,因为 owl_detection_camera 插件可能会使用机器学习模型来在后台进行图像分析。你需要确保插件已经包含了必要的模型,并且已经正确配置。

在实际应用中,你可能还需要处理权限请求(例如相机权限),这通常可以通过插件提供的辅助函数或者Flutter的权限插件来完成。

回到顶部