微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flutter - 尝试使用 Tensorflowlite - FloatEfficientNet

如何解决Flutter - 尝试使用 Tensorflowlite - FloatEfficientNet

我正在尝试使用在原生 swift 和 android/java 中都成功进行推理的模型在 Flutter 中执行相同的操作,特别是它的 android 方面。

在这种情况下,我收到的值相差甚远。

到目前为止我做了什么:

  1. 我使用了 tensorflowlite android 示例 github 存储库:https://github.com/tensorflow/examples/tree/master/lite/examples/image_classification/android,发现 FloatEfficientNet 选项准确地为我的模型提供了值。

  2. 我使用了 Flutter_tflite 库,并对其进行了修改,以便 android 代码的推理部分与上面的 tensorflow 示例相匹配: https://github.com/shaqian/flutter_tflite

  3. 我使用了本教程并包含了使用上述库通过平台通道推断 tensorflow 的 repo: https://github.com/flutter-devs/tensorflow_lite_flutter

通过 Flutter 教程,我使用了相机插件,它可以从相机的实时馈送中流式传输 Cameraimage 对象。我将它传递到修改后的 Flutter tensorflow 库中,该库使用平台通道将图像传递到 android 层。它以字节数组列表的形式执行此操作。 (3 架飞机,YuvImage)。 tensorflow android 示例(1) 与工作的 floatefficientnet 代码,示例一个位图。所以我用这个方法来转换:

    public Bitmap imagetoBitmap(List<byte[]> planes,float rotationdegrees,int width,int height) {

        // NV21 is a plane of 8 bit Y values followed by interleaved  Cb Cr
        ByteBuffer ib = ByteBuffer.allocate(width * height * 2);

        ByteBuffer y = ByteBuffer.wrap(planes.get(0));
        ByteBuffer cr = ByteBuffer.wrap(planes.get(1));
        ByteBuffer cb = ByteBuffer.wrap(planes.get(2));
        ib.put(y);
        ib.put(cb);
        ib.put(cr);

        YuvImage yuvImage = new YuvImage(ib.array(),ImageFormat.NV21,width,height,null);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        yuvImage.compresstoJpeg(new Rect(0,height),50,out);
        byte[] imageBytes = out.toByteArray();
        Bitmap bm = BitmapFactory.decodeByteArray(imageBytes,imageBytes.length);
        Bitmap bitmap = bm;

        // On android the camera rotation and the screen rotation
        // are off by 90 degrees,so if you are capturing an image
        // in "portrait" orientation,you'll need to rotate the image.
        if (rotationdegrees != 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(rotationdegrees);
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bm,bm.getWidth(),bm.getHeight(),true);
            bitmap = Bitmap.createBitmap(scaledBitmap,scaledBitmap.getWidth(),scaledBitmap.getHeight(),matrix,true);
        }
        return bitmap;
    }

推理成功,我能够将值返回给 Flutter 并显示结果,但它们还有很长的路要走。使用同一款安卓手机,结果完全不同,相差甚远。

我怀疑该缺陷与将 Cameraimage 数据格式转换为 Bitmap 相关,因为它是整个链中唯一我无法独立测试的部分。如果有人遇到类似问题可以提供帮助,我很困惑。

解决方法

我认为原因是因为 matrix.postRotate() 方法需要一个整数,但你给它一个浮点数,所以你有一个从浮点数到整数的隐式转换,这把它搞砸了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。