camera.dart 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import 'dart:ui';
  2. import 'package:camera/camera.dart';
  3. import 'package:flutter/foundation.dart';
  4. import 'package:google_mlkit_object_detection/google_mlkit_object_detection.dart';
  5. /// 图片预处理
  6. /// [camera] 相机
  7. /// [image] 图片
  8. /// [onImage] 回调函数
  9. Future<InputImage?> processCameraImage(
  10. CameraDescription camera,
  11. CameraImage image,
  12. void Function(InputImage inputImage) onImage,
  13. ) async {
  14. final WriteBuffer allBytes = WriteBuffer();
  15. for (final Plane plane in image.planes) allBytes.putUint8List(plane.bytes);
  16. final bytes = allBytes.done().buffer.asUint8List();
  17. final Size imageSize = Size(image.width.toDouble(), image.height.toDouble());
  18. final imageRotation = InputImageRotationValue.fromRawValue(camera.sensorOrientation);
  19. if (imageRotation == null) return null;
  20. final inputImageFormat = InputImageFormatValue.fromRawValue(image.format.raw);
  21. if (inputImageFormat == null) return null;
  22. final planeData = image.planes
  23. .map((Plane plane) => InputImagePlaneMetadata(
  24. bytesPerRow: plane.bytesPerRow,
  25. height: plane.height,
  26. width: plane.width,
  27. ))
  28. .toList();
  29. final inputImageData = InputImageData(
  30. size: imageSize,
  31. imageRotation: imageRotation,
  32. inputImageFormat: inputImageFormat,
  33. planeData: planeData,
  34. );
  35. final inputImage = InputImage.fromBytes(bytes: bytes, inputImageData: inputImageData);
  36. onImage(inputImage);
  37. }