PyTorch Mobile FloatArray 转 Bitmap (Android/Kotlin)

'org.pytorch:pytorch_android:1.7.0'的
TensorImageUtils.imageYUV420CenterCropToFloat32Tensor()

是真的天坑,进来的图像RGB是扭曲的(目前),希望 PyTorch Mobile 以后会改。 。

用 PyTorch Mobile 最后要生成图片之前必须要用

TensorImageUtils.bitmapToFloat32Tensor()

至于读进来yuv格式图片的同学们要自己想办法yuv转bitmap辽

出来 FloatArray 用下面的函数转 Bitmap 就好了(改自phillies ),输出张量格式NCHW:

private fun floatArrayToBitmap(floatArray: FloatArray, width: Int, height: Int) : Bitmap {

        // Create empty bitmap in RGBA format
        val bmp: Bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val pixels = IntArray(width * height * 4)

        // mapping smallest value to 0 and largest value to 255
        val maxValue = floatArray.max() ?: 1.0f
        val minValue = floatArray.min() ?: -1.0f
        val delta = maxValue-minValue

        // Define if float min..max will be mapped to 0..255 or 255..0
        val conversion = { v: Float -> ((v-minValue)/delta*255.0f).roundToInt()}

        // copy each value from float array to RGB channels and set alpha channel
        for (i in 0 until width * height) {
            val r = conversion(floatArray[i])
            val g = conversion(floatArray[i+width*height])
            val b = conversion(floatArray[i+2*width*height])
            pixels[i] = rgb(r, g, b)
        }
        bmp.setPixels(pixels, 0, width, 0, 0, width, height)

        return bmp
    }

 

 

 

 

 

 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值