FaceDetection.dart 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import 'package:firebase_ml_vision/firebase_ml_vision.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:image_picker/image_picker.dart';
  4. class FaceDetectionView extends StatefulWidget {
  5. FaceDetectionView({Key? key}) : super(key: key);
  6. @override
  7. _FaceDetectionViewState createState() => _FaceDetectionViewState();
  8. }
  9. class _FaceDetectionViewState extends State<FaceDetectionView> {
  10. late PickedFile filePath;
  11. @override
  12. void initState() {
  13. super.initState();
  14. }
  15. chooseImage() async {
  16. XFile? xfile = await ImagePicker().pickImage(
  17. source: ImageSource.gallery,
  18. imageQuality: 100,
  19. maxWidth: MediaQuery.of(context).size.width);
  20. var availableImage = filePath;
  21. // final FirebaseVisionImageMetadata metadata = FirebaseVisionImageMetadata(
  22. // rawFormat: availableImage.format.raw,
  23. // size: Size(
  24. // availableImage.width.toDouble(), availableImage.height.toDouble()),
  25. // planeData: availableImage.planes
  26. // .map((currentPlane) => FirebaseVisionImagePlaneMetadata(
  27. // bytesPerRow: currentPlane.bytesPerRow,
  28. // height: currentPlane.height,
  29. // width: currentPlane.width))
  30. // .toList(),
  31. // rotation: ImageRotation.rotation90);
  32. final FirebaseVisionImage visionImage =
  33. FirebaseVisionImage.fromFilePath(filePath.path);
  34. final FaceDetector detector = FirebaseVision.instance.faceDetector();
  35. final List<Face> faces = await detector.processImage(visionImage);
  36. print(faces[0].boundingBox);
  37. setState(() {
  38. filePath = filePath;
  39. });
  40. }
  41. @override
  42. Widget build(BuildContext context) {
  43. return Stack(children: [
  44. ElevatedButton(
  45. child: Text("选择图片"),
  46. onPressed: () {
  47. chooseImage();
  48. },
  49. ),
  50. filePath == null
  51. ? Container()
  52. : Container(
  53. child: Image.asset(
  54. filePath.path,
  55. fit: BoxFit.fitWidth,
  56. ),
  57. )
  58. ]);
  59. }
  60. }
  61. class FaceMain extends StatelessWidget {
  62. const FaceMain({Key? key}) : super(key: key);
  63. @override
  64. Widget build(BuildContext context) {
  65. return Scaffold(
  66. body: FaceDetectionView(),
  67. );
  68. }
  69. }