Created
June 29, 2020 14:01
-
-
Save phillies/a083106c6acd143147462ae4f975f386 to your computer and use it in GitHub Desktop.
Convert FloatArray coming from pytorch Tensor to Bitmap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun floatArrayToColorBitmap ( | |
floatArray: FloatArray, | |
width: Int, | |
height: Int, | |
alpha :Byte = (255).toByte(), | |
reverseScale :Boolean = false | |
) : Bitmap { | |
// Create empty bitmap in RGBA format (even though it says ARGB but channels are RGBA) | |
val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) | |
val byteBuffer= ByteBuffer.allocate(width*height*4) | |
// mapping smallest value to 0 and largest value to 255 | |
val maxValue = floatArray.max() ?: 1.0f | |
val minValue = floatArray.min() ?: 0.0f | |
val delta = maxValue-minValue | |
// Define if float min..max will be mapped to 0..255 or 255..0 | |
val conversion = when(reverseScale) { | |
false -> { v: Float -> ((v-minValue)/delta*255).toByte() } | |
true -> { v: Float -> (255-(v-minValue)/delta*255).toByte() } | |
} | |
var bitmapCounter = 0 | |
floatArray.forEach { value -> | |
byteBuffer.put(bitmapCounter, conversion(value)) | |
bitmapCounter++ | |
// every 4th entry is the alpha value | |
if(bitmapCounter%4 == 3) { | |
byteBuffer.put(bitmapCounter, alpha) | |
bitmapCounter++ | |
} | |
} | |
bmp.copyPixelsFromBuffer(byteBuffer) | |
return bmp | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment