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

Mobile 如何将二维数组转换为FTLite所需的ByteBuffer类型?,mobile,deep-learning,tensorflow-lite,Mobile,Deep Learning,Tensorflow Lite,在python中,我得到了一个适用于113*113数组的模型,它已经被放入tflite中,安卓端我得到了113*113的二维数组,我想知道我需要做什么才能将二维数组放到tflite模型中,我看着其他人编写了模型的tflite运行函数,使用bytebuffer数据类型,想问一下如何操作? 我的二维数组是一个双重的,正的和负的我将首先写下我是如何将位图转换为bytebuffer的,然后我将为您的输入显示一个解决方法 将位图转换为bytebuffer的函数: private fun convertBi

在python中,我得到了一个适用于113*113数组的模型,它已经被放入tflite中,安卓端我得到了113*113的二维数组,我想知道我需要做什么才能将二维数组放到tflite模型中,我看着其他人编写了模型的tflite运行函数,使用bytebuffer数据类型,想问一下如何操作?
我的二维数组是一个双重的,正的和负的

我将首先写下我是如何将位图转换为bytebuffer的,然后我将为您的输入显示一个解决方法

将位图转换为bytebuffer的函数:

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个字节

//像素大小表示每个像素中有多少颜色通道。我们的输入图像是彩色图像,所以我们有3个彩色通道

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

因此,从上面的代码中,如果我们想将数组转换为bytebuffer,我们必须使用如下内容:

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的数组检查项目

并使用224*224尺寸的彩色位图进行投影

祝你好运