Last active
March 25, 2024 13:27
-
-
Save phillies/830f52b0bf592c32fc507669694f66d8 to your computer and use it in GitHub Desktop.
Converting pytorch tensor / floatArray to Android 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 floatArrayToGrayscaleBitmap ( | |
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.maxOrNull() ?: 1.0f | |
val minValue = floatArray.minOrNull() ?: 0.0f | |
val delta = maxValue-minValue | |
var tempValue :Byte | |
// 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).toInt().toByte() } | |
true -> { v: Float -> (255-(v-minValue)/delta*255).toInt().toByte() } | |
} | |
// copy each value from float array to RGB channels and set alpha channel | |
floatArray.forEachIndexed { i, value -> | |
tempValue = conversion(value) | |
byteBuffer.put(4*i, tempValue) | |
byteBuffer.put(4*i+1, tempValue) | |
byteBuffer.put(4*i+2, tempValue) | |
byteBuffer.put(4*i+3, alpha) | |
} | |
bmp.copyPixelsFromBuffer(byteBuffer) | |
return bmp | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The function maps the smallest value in your
floatArray
to 0 (black) and the largest value to255
(white). If you want to have it the other way round, so the smallest value is white and the largest are black, thenreverseScale
should be true.I assume that your object detection function delivers a float array where background is
0
and detected objects are>0
, so if you want to have the detected objects in black and the background in white setreverseScale=true
then calling the function.