utils.dart 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import 'dart:async';
  2. import 'dart:typed_data';
  3. import 'dart:ui';
  4. import 'package:camera/camera.dart';
  5. import 'package:firebase_ml_vision/firebase_ml_vision.dart';
  6. import 'package:flutter/foundation.dart';
  7. typedef HandleDetection = Future<dynamic> Function(FirebaseVisionImage image);
  8. Future<CameraDescription> getCamera(CameraLensDirection dir) async {
  9. return await availableCameras().then(
  10. (List<CameraDescription> cameras) => cameras.firstWhere(
  11. (CameraDescription camera) => camera.lensDirection == dir,
  12. ),
  13. );
  14. }
  15. Uint8List concatenatePlanes(List<Plane> planes) {
  16. final WriteBuffer allBytes = WriteBuffer();
  17. planes.forEach((Plane plane) => allBytes.putUint8List(plane.bytes));
  18. return allBytes.done().buffer.asUint8List();
  19. }
  20. FirebaseVisionImageMetadata buildMetaData(
  21. CameraImage image,
  22. ImageRotation rotation,
  23. ) {
  24. return FirebaseVisionImageMetadata(
  25. rawFormat: image.format.raw,
  26. size: Size(image.width.toDouble(), image.height.toDouble()),
  27. rotation: rotation,
  28. planeData: image.planes.map(
  29. (Plane plane) {
  30. return FirebaseVisionImagePlaneMetadata(
  31. bytesPerRow: plane.bytesPerRow,
  32. height: plane.height,
  33. width: plane.width,
  34. );
  35. },
  36. ).toList(),
  37. );
  38. }
  39. Future<dynamic> detect(
  40. CameraImage image,
  41. HandleDetection handleDetection,
  42. ImageRotation rotation,
  43. ) async {
  44. return handleDetection(
  45. FirebaseVisionImage.fromBytes(
  46. concatenatePlanes(image.planes),
  47. buildMetaData(image, rotation),
  48. ),
  49. );
  50. }
  51. // 图片旋转
  52. ImageRotation rotationIntToImageRotation(int rotation) {
  53. switch (rotation) {
  54. case 0:
  55. return ImageRotation.rotation0;
  56. case 90:
  57. return ImageRotation.rotation90;
  58. case 180:
  59. return ImageRotation.rotation180;
  60. default:
  61. assert(rotation == 270);
  62. return ImageRotation.rotation270;
  63. }
  64. }