google_ml_kitを使って画像認識の処理をするときにカメラからの画像データはCameraImageで渡されますがInputImageに変換する必要があります。CameraImageからInputImageに変換する方法を書いた記事はインターネット上にそこそこありますが、変換に使うライブラリの一つであるgoogle_mlkit_commonsが0.4.0から大規模な変更があったためほとんどのコードがコピペでは使えません。
https://pub.dev/pack … it_commons/changelog
そのため、最新のgoogle_mlkit_commonsに合わせた変換のコードを書いてみたので好きにコピペするなりしてください
pubspec.yaml
camera: ^0.10.5+9 google_ml_kit: ^0.16.3 google_mlkit_commons: ^0.6.1
import 'dart:async';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:google_ml_kit/google_ml_kit.dart';
Future<InputImage> convertCameraImageToInputImage(
CameraImage cameraImage, CameraDescription camera) async {
final WriteBuffer allBytes = WriteBuffer();
for (final Plane plane in cameraImage.planes) {
allBytes.putUint8List(plane.bytes);
}
final bytes = allBytes.done().buffer.asUint8List();
final Size imageSize =
Size(cameraImage.width.toDouble(), cameraImage.height.toDouble());
final camera = widget.cameras.firstWhere(
(camera) => camera.lensDirection == CameraLensDirection.front,
);
final InputImageRotation imageRotation =
_rotationIntToImageRotation(camera.sensorOrientation);
final InputImageFormat inputImageFormat =
InputImageFormatValue.fromRawValue(cameraImage.format.raw) ??
InputImageFormat.nv21;
final inputImageData = InputImageMetadata(
size: imageSize,
rotation: imageRotation,
format: inputImageFormat,
bytesPerRow: cameraImage.planes[0].bytesPerRow,
);
final result = InputImage.fromBytes(bytes: bytes, metadata: inputImageData);
return result;
}
InputImageRotation _rotationIntToImageRotation(int rotation) {
switch (rotation) {
case 0:
return InputImageRotation.rotation0deg;
case 90:
return InputImageRotation.rotation90deg;
case 180:
return InputImageRotation.rotation180deg;
case 270:
return InputImageRotation.rotation270deg;
}
return InputImageRotation.rotation0deg;
}