最近 Flutter 的官方插件 camera 加入了獲取圖像流的功能,利用該功能我們可以獲取到相機預(yù)覽的實時畫面。
我用 camera 和 tflite 插件做了一個結(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;
}
注意在不同平臺上的圖像格式并不相同:
iOS: kCVPixelFormatType_32BGRA (在 2.8.0 版本中的格式為 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, 后來在 4.0.0 版本中又改回為 32BGRA。)
由于圖像格式不同,輸出的 CameraImage 在 Android 和 iOS 端包含的信息也不一樣:
Android: planes 含有三個字節(jié)數(shù)組,分別是 Y、U 和 V 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 MobileNet 和 YOLOv2 兩種模式。
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
感謝您的閱讀 :)