火曜日, 3月 12, 2024

【google_ml_kit】flutterでcameraimageからinputimageに変換する方法【2024年版】

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;
}

管理者用

Menu

色々あってメモ帳がわりのブログ的なものを作ることになりましたが、wordpressアレルギーなるものが発病したので代わりにflatpressという物を使って作ってみました。

プログラム関連のことを書いていこうと思っています。

ちなみに作った物やwebサイトはここに置いています。

flatpressの初期のテーマがどうしても気に入らなくて色々探しているうちに何が何だかわからなくなって、

ブログにふさわしいテーマってなんだ?

と自問自答しているうちに結局デフォルトのものに近い物を使ってしまった。
なんかいいテーマないですかね?

About

shimaumaと名乗っています。
なんとなく趣味でプログラムを書いてみたりしている人です。