在 Flutter 中實現(xiàn)實時圖像檢測

最近 Flutter 的官方插件 camera 加入了獲取圖像流的功能,利用該功能我們可以獲取到相機預(yù)覽的實時畫面。

我用 cameratflite 插件做了一個結(jié)合 TensorFlow Lite 的 Flutter 實時圖像識別的 demo。

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

以下是在 iPad 上的演示視頻:

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

首先按照 camera 插件 的文檔在項目中加入相機功能。

然后調(diào)用 camera controller 的 startImageStream 方法獲取圖像流。這個方法在每次有新的幀時會被觸發(fā)。

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 含有三個字節(jié)數(shù)組,分別是 YUV plane。

  • iOS:planes 只包含一個字節(jié)數(shù)組,即圖像的 RGBA 字節(jié)。

了解輸出的圖像流之后,我們就可以將圖像輸入到 TensorFlow Lite 中了。

解析 CameraImage:

理論上使用 Dart 代碼也可以解析圖像,但是目前為止 dart 的 image 插件在 iOS 上速度很慢。 為了提高效率我們用原生代碼來解析圖像。

  • iOS:

因為圖像已經(jīng)是 RGBA 格式了,我們只需要獲取紅綠藍三個通道的字節(jié),然后輸入到 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 轉(zhuǎn)換成 RGBA 格式的 bitmap。簡單的方法是用 render script 實現(xiàn)轉(zhuǎn)換。

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 轉(zhuǎn)換為 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 調(diào)整為需要的尺寸,獲取紅綠藍通道的字節(jié),輸入到 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 插件做目標(biāo)檢測:

tflite 插件封裝了 iOS 和 Android 的 TensorFlow Lite 接口,并用原生代碼實現(xiàn)了常用模型的輸入和輸出,目標(biāo)檢測當(dāng)前支持 SSD MobileNetYOLOv2 兩種模式。

tflite 插件提供的 detectObjectOnFrame 方法可以自動解析 camera 插件生成的圖像流(底層實現(xiàn)同上文所述),執(zhí)行模型并返回結(jié)果。

我們只需要將 CameraImage 的 planes 字節(jié)數(shù)組傳給該方法,就可以實現(xiàn)圖像檢測。

檢測到的物體輸出格式如下:

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

x, y, w, h 為物體位置的左偏移、上偏移、高度、寬度。 值的區(qū)間為 [0, 1],我們可以用圖像的高度和寬度等比例放大。

顯示檢測結(jié)果:

camera 插件有個小問題是預(yù)覽畫面和屏幕不是等比例的。一般推薦把預(yù)覽放在 AspectRatio 組件里防止畫面變形,但這樣會在屏幕上留出空白。

如果需要讓相機預(yù)覽撐滿整個屏幕,我們可以把預(yù)覽放在 OverflowBox 組件里:先比較預(yù)覽畫面和屏幕的高寬比,然后將預(yù)覽畫面按屏幕高度或屏幕寬度放大至充滿屏幕。

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 需要減去放大寬度(或高度)與屏幕寬度(或高度)的差值,因為有一部分的預(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

感謝您的閱讀 :)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,410評論 4 61
  • 今夜我住宿在縣城的姐家(大姑姐)半夜我醒了說什么也睡不著了,心里不知不覺有種莫名其妙的想家的感覺,想起我們不大的房...
  • 如果還不開始寫,估計都不記得去了哪里看了什么的系列之一 BY TXL 半年過去,我有點想不起來,曼殊院長什么樣子了...
    xltian_07閱讀 1,609評論 2 6
  • —— 那,就這樣。 ——嗯,好的,就這樣。 應(yīng)該有一天會有這樣的對白,如果我不是,又一次突然放棄的話。 其實本沒有...
    Bridget2017閱讀 271評論 0 0

友情鏈接更多精彩內(nèi)容