在 Flutter 中实现实时图像检测

最近 Flutter 的官方插件 camera 加入了获取图像流的功能,利用该功能我们可以获取到相机预览的实时画面。

我用 cameratflite 插件做了一个结合 TensorFlow Lite 的 Flutter 实时图像识别的 demo。

项目地址: https://github.com/shaqian/flutter_realtime_detection

以下是在 iPad 上的演示视频:

《在 Flutter 中实现实时图像检测》

使用 camera 插件的图像流功能:

首先按照 camera 插件 的文档在项目中加入相机功能。

然后调用 camera controller 的 startImageStream 方法获取图像流。这个方法在每次有新的帧时会被触发。

controller.startImageStream((CameraImage img) { <YOUR CODE> });

方法的输出为 CameraImage,有 4 个属性: 图像格式, 高度, 宽度以及 planes ,planes 包含图像具体信息。

class CameraImage {
  final ImageFormat format;
  final int height;
  final int width;
  final List planes;
}

注意在不同平台上的图像格式并不相同:

由于图像格式不同,输出的 CameraImage 在 Android 和 iOS 端包含的信息也不一样:

  • Android: planes 含有三个字节数组,分别是 YUV plane。

  • iOS:planes 只包含一个字节数组,即图像的 RGBA 字节。

了解输出的图像流之后,我们就可以将图像输入到 TensorFlow Lite 中了。

解析 CameraImage:

理论上使用 Dart 代码也可以解析图像,但是目前为止 dart 的 image 插件在 iOS 上速度很慢。 为了提高效率我们用原生代码来解析图像。

  • iOS:

因为图像已经是 RGBA 格式了,我们只需要获取红绿蓝三个通道的字节,然后输入到 TensorFlow Interpreter 的 input tensor 中。

const FlutterStandardTypedData* typedData = args[@"bytesList"][0];
uint8_t* in = (uint8_t*)[[typedData data] bytes];
float* out = interpreter->typed_tensor<float>(input);
for (int y = 0; y < height; ++y) {
  const int in_y = (y * image_height) / height;
  uint8_t* in_row = in + (in_y * image_width * image_channels);
  float* out_row = out + (y * width * input_channels);
  for (int x = 0; x < width; ++x) {
    const int in_x = (x * image_width) / width;
    uint8_t* in_pixel = in_row + (in_x * image_channels);
    float* out_pixel = out_row + (x * input_channels);
    for (int c = 0; c < input_channels; ++c) {
      out_pixel[c] = (in_pixel[c] - input_mean) / input_std;
    }
  }
}
  • Android:

首先我们需要把 YUV planes 转换成 RGBA 格式的 bitmap。简单的方法是用 render script 实现转换。

ByteBuffer Y = ByteBuffer.wrap(bytesList.get(0));
ByteBuffer U = ByteBuffer.wrap(bytesList.get(1));
ByteBuffer V = ByteBuffer.wrap(bytesList.get(2));

int Yb = Y.remaining();
int Ub = U.remaining();
int Vb = V.remaining();

byte[] data = new byte[Yb + Ub + Vb];

Y.get(data, 0, Yb);
V.get(data, Yb, Vb);
U.get(data, Yb + Vb, Ub);

Bitmap bitmapRaw = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
Allocation bmData = renderScriptNV21ToRGBA888(
    mRegistrar.context(),
    imageWidth,
    imageHeight,
    data);
bmData.copyTo(bitmapRaw);

NV21 转换为 RGBA 的代码,参考了 https://stackoverflow.com/a/36409748

public Allocation renderScriptNV21ToRGBA888(Context context, int width, int height, byte[] nv21) {
  RenderScript rs = RenderScript.create(context);
  ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));

  Type.Builder yuvType = new Type.Builder(rs, Element.U8(rs)).setX(nv21.length);
  Allocation in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);

  Type.Builder rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height);
  Allocation out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);

  in.copyFrom(nv21);

  yuvToRgbIntrinsic.setInput(in);
  yuvToRgbIntrinsic.forEach(out);
  return out;
}

接下来再把 bitmap 调整为需要的尺寸,获取红绿蓝通道的字节,输入到 input tensor 中。


ByteBuffer imgData = ByteBuffer.allocateDirect(1 * inputSize * inputSize * inputChannels * bytePerChannel);
imgData.order(ByteOrder.nativeOrder());

Matrix matrix = getTransformationMatrix(bitmapRaw.getWidth(), bitmapRaw.getHeight(),
    inputSize, inputSize, false);
Bitmap bitmap = Bitmap.createBitmap(inputSize, inputSize, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(bitmapRaw, matrix, null);
int[] intValues = new int[inputSize * inputSize];
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

int pixel = 0;
for (int i = 0; i < inputSize; ++i) {
  for (int j = 0; j < inputSize; ++j) {
    int pixelValue = intValues[pixel++];
    imgData.putFloat((((pixelValue >> 16) & 0xFF) - mean) / std);
    imgData.putFloat((((pixelValue >> 8) & 0xFF) - mean) / std);
    imgData.putFloat(((pixelValue & 0xFF) - mean) / std);
  }
}

使用 tflite 插件做目标检测:

tflite 插件封装了 iOS 和 Android 的 TensorFlow Lite 接口,并用原生代码实现了常用模型的输入和输出,目标检测当前支持 SSD MobileNetYOLOv2 两种模式。

tflite 插件提供的 detectObjectOnFrame 方法可以自动解析 camera 插件生成的图像流(底层实现同上文所述),执行模型并返回结果。

我们只需要将 CameraImage 的 planes 字节数组传给该方法,就可以实现图像检测。

检测到的物体输出格式如下:

{
  detectedClass: “hot dog”,
  confidenceInClass: 0.123,
  rect: {
    x: 0.15,
    y: 0.33,
    w: 0.80,
    h: 0.27
  }
}

x, y, w, h 为物体位置的左偏移、上偏移、高度、宽度。 值的区间为 [0, 1],我们可以用图像的高度和宽度等比例放大。

显示检测结果:

camera 插件有个小问题是预览画面和屏幕不是等比例的。一般推荐把预览放在 AspectRatio 组件里防止画面变形,但这样会在屏幕上留出空白。

如果需要让相机预览撑满整个屏幕,我们可以把预览放在 OverflowBox 组件里:先比较预览画面和屏幕的高宽比,然后将预览画面按屏幕高度或屏幕宽度放大至充满屏幕。

Widget build(BuildContext context) {
  var tmp = MediaQuery.of(context).size;
  var screenH = math.max(tmp.height, tmp.width);
  var screenW = math.min(tmp.height, tmp.width);
  tmp = controller.value.previewSize;
  var previewH = math.max(tmp.height, tmp.width);
  var previewW = math.min(tmp.height, tmp.width);
  var screenRatio = screenH / screenW;
  var previewRatio = previewH / previewW;

  return OverflowBox(
    maxHeight:
        screenRatio > previewRatio ? screenH : screenW / previewW * previewH,
    maxWidth:
        screenRatio > previewRatio ? screenH / previewH * previewW : screenW,
    child: CameraPreview(controller),
  );
}

同时在画框的时候,也要按比例放大 x, y, w, h 。注意 x 或 y 需要减去放大宽度(或高度)与屏幕宽度(或高度)的差值,因为有一部分的预览在 OverflowBox 中超出屏幕范围了。

var _x = re["rect"]["x"];
var _w = re["rect"]["w"];
var _y = re["rect"]["y"];
var _h = re["rect"]["h"];
var scaleW, scaleH, x, y, w, h;

if (screenH / screenW > previewH / previewW) {
  scaleW = screenH / previewH * previewW;
  scaleH = screenH;
  var difW = (scaleW - screenW) / scaleW;
  x = (_x - difW / 2) * scaleW;
  w = _w * scaleW;
  if (_x < difW / 2) w -= (difW / 2 - _x) * scaleW;
  y = _y * scaleH;
  h = _h * scaleH;
} else {
  scaleH = screenW / previewW * previewH;
  scaleW = screenW;
  var difH = (scaleH - screenH) / scaleH;
  x = _x * scaleW;
  w = _w * scaleW;
  y = (_y - difH / 2) * scaleH;
  h = _h * scaleH;
  if (_y < difH / 2) h -= (difH / 2 - _y) * scaleH;
}

每帧的检测时间:

我在 iPad 和 Android 手机上测试了样例代码,SSD MobileNet 在两个平台上速度都可以,但是 Tiny YOLOv2 在 Android 端速度较慢。

  • iOS (A9)
    SSD MobileNet: ~100 ms
    Tiny YOLOv2: 200~300ms
  • Android (Snapdragon 652):
    SSD MobileNet: 200~300ms
    Tiny YOLOv2: ~1000ms

感谢您的阅读 :)

    原文作者:三少ZZzzz
    原文地址: https://www.jianshu.com/p/580ccd25d4ca
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞