'In Android, Kotlin, TFLite blocks the UI thread when running in viewModelScope
When viewModelScope executes, the UI is frozen and screen turns black. For some reason, this only happens when trying to process an image through my tflite model. Is this due to a memory/CPU problem in my emulator or because I am using an incorrect thread somehow?
fun processImage(context: Context, bitmap: Bitmap) {
viewModelScope.launch{
ObjectRecognition.processImage(context, bitmap)
}
}
object ObjectRecognition {
fun processImage(context : Context, bitmap : Bitmap) : List<DetectionResult>{
val confidLevel = 0.3f
// Step 1: Create TFLite's TensorImage object
val image = TensorImage.fromBitmap(bitmap)
// Step 2: Initialize the detector object
val options = ObjectDetector.ObjectDetectorOptions.builder()
.setMaxResults(5)
.setScoreThreshold(confidLevel)
.build()
val detector = ObjectDetector.createFromFileAndOptions(
context,
"spade8_2.tflite",
options
)
// Step 3: Feed given image to the detector
val results = detector.detect(image)
// Step 4: Parse the detection result and show it
val resultToDisplay = results.map {
// Get the top-1 category and craft the display text
val category = it.categories.first()
val text = "${category.label}, ${category.score.times(100).toInt()}%"
// Create a data object to display the detection result
DetectionResult(it.boundingBox, text)
}
Log.i(ContentValues.TAG, "result.. $resultToDisplay" )
return resultToDisplay
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
