Skip to content

Instantly share code, notes, and snippets.

@phillies
Last active March 25, 2024 13:27
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save phillies/830f52b0bf592c32fc507669694f66d8 to your computer and use it in GitHub Desktop.
Save phillies/830f52b0bf592c32fc507669694f66d8 to your computer and use it in GitHub Desktop.
Converting pytorch tensor / floatArray to Android Bitmap
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
}
@phillies
Copy link
Author

The function maps the smallest value in your floatArray to 0 (black) and the largest value to 255 (white). If you want to have it the other way round, so the smallest value is white and the largest are black, then reverseScale 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 set reverseScale=true then calling the function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment