我如何将二维数组转换为FTLite所需的ByteBuffer类型?

问题描述 投票:-1回答:1

在python中,我得到了一个适用于113 * 113数组模型,并将其放入tflite中,AnZhuoDuan我得到了113 * 113的二维数组,我想知道我需要做什么才能得到2 d将数组转换为tflite模型,我看着别人写的tflite运行函数模型,使用字节缓冲区数据类型,想问一下如何操作?我的二维数组是一个双精度正负数

mobile deep-learning tensorflow-lite
1个回答
0
投票

[我将首先写出我如何将位图转换为字节缓冲区,然后为您的输入显示解决方法

将位图转换为字节缓冲区的功能:

private fun convertBitmapToByteBuffer(bitmap: Bitmap): ByteBuffer {
    // Pre-process the input: convert a Bitmap instance to a ByteBuffer instance
    // containing the pixel values of all pixels in the input image.
    // We use ByteBuffer because it is faster than a Kotlin native float 
    multidimensional array.
    val byteBuffer = ByteBuffer.allocateDirect(modelInputSize)
    byteBuffer.order(ByteOrder.nativeOrder())

    val pixels = IntArray(inputImageWidth * inputImageHeight)
    bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)

    for (pixelValue in pixels) {
        val r = (pixelValue shr 16 and 0xFF)
        val g = (pixelValue shr 8 and 0xFF)
        val b = (pixelValue and 0xFF)

        // Normalize pixel value to [0..1].
        val normalizedPixelValue = (r + g + b) / 255.0F
        byteBuffer.putFloat(normalizedPixelValue)
    }

    return byteBuffer
}

其中modelInputSize为:

modelInputSize = FLOAT_TYPE_SIZE * inputImageWidth *
            inputImageHeight * PIXEL_SIZE

// modelInputSize指示我们应该分配多少字节的内存来存储TensorFlow Lite模型的输入。

// FLOAT_TYPE_SIZE表示我们的输入数据类型将需要多少字节。我们使用float32,所以它是4个字节。

// PIXEL_SIZE指示每个像素中有多少个颜色通道。我们的输入图像是彩色图像,因此我们有3个颜色通道。

// inputImageWidth和inputImageHeight是大多数预训练模型使用的宽度和高度,通常为224x224。

因此,从上面的代码中,如果我们想将数组转换为字节缓冲区,我们必须使用如下所示的内容:

private fun convertArrayToByteBuffer(twoDArray: FloatArray?): ByteBuffer {

    // We use ByteBuffer because it is faster than a Kotlin native float 
    multidimensional array.
    // FLOAT_TYPE_SIZE * WIDTH * HEIGHT
    val byteBuffer = ByteBuffer.allocateDirect(4 * 113 * 113)
    byteBuffer.order(ByteOrder.nativeOrder())

    if (twoDArray != null) {
        // Use [0] if this is 2D array or without [0] if it is one dimension array
        for (input in twoDArray[0]) {

            byteBuffer.putFloat(input)
        }
    }

    return byteBuffer
}

[您还应该检查数组是double还是float,并进行相应的转换以应用于FLOAT_TYPE_SIZE的上述代码(在我的示例中float的值为4)。

检查长度为40的2Darray的项目file

并且投影file,其彩色位图为224 * 224尺寸。

祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.