首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Firebase ML-Kit并行运行多个人脸检测会话

问Firebase ML-Kit并行运行多个人脸检测会话
EN

Stack Overflow用户
提问于 2020-03-07 23:32:16
回答 1查看 688关注 0票数 1

作为我的ML项目的一部分,我希望使用人脸检测器Google Firebase ML-Kit人脸检测库生成用于从不同图像中分析多个人面部的训练数据。我创建了一个非常简单的服务类来封装初始化和启动人脸检测过程:

代码语言:javascript
复制
class FaceDetectorService(private val act: MainActivity)  {

private var opts: FirebaseVisionFaceDetectorOptions? = null
private var detector: FirebaseVisionFaceDetector? = null


init {
    FirebaseApp.initializeApp(act)

    opts = FirebaseVisionFaceDetectorOptions.Builder()
        .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
        .setLandmarkMode(FirebaseVisionFaceDetectorOptions.NO_LANDMARKS)
        .setClassificationMode(FirebaseVisionFaceDetectorOptions.NO_CLASSIFICATIONS)
        .setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS)
        .build()

    detector = FirebaseVision.getInstance()
        .getVisionFaceDetector(opts!!)
}


suspend fun analyzeAsync(cont: Context, uri: Uri) : Pair<String, Task<List<FirebaseVisionFace>>> {
    val image = FirebaseVisionImage.fromFilePath(cont, uri)

    // this is for the UI thread
    withContext(Main){
        act.addItemToAnalyze(uri.lastPathSegment)
    }

    // return the filename too
    return Pair(uri.lastPathSegment, detector!!.detectInImage(image))
}

}

函数检测器!!.detectInImage (FirebaseVisionImage.detectInImage返回表示异步操作的任务 )。

在我的onResume()函数的MainActivity中,在CoroutineScope中,我启动库并开始迭代图像,首先将它们转换为Uri,然后将其传递给人脸检测器:

代码语言:javascript
复制
CoroutineScope(IO).launch {
        val executeTime = measureTimeMillis {
            for (uri in uris){

                    val fileNameUnderAnalysis = uri.lastPathSegment
                    //val tsk = withContext(IO) {
                    //    detector!!.analyzeAsync(act, uri)
                    //}
                val tsk = detector!!.analyzeAsync(act, uri)
                tsk.second.addOnCompleteListener { task ->
                    if (task.isSuccessful && task.result!!.isNotEmpty()) {
                        try {
                           // my best
                        } catch (e: IllegalArgumentException) {
                           // fire
                        }
                    } else if (task.result!!.isEmpty()) {
                       // not today :(
                    }

                }

                tsk.second.addOnFailureListener { e ->
                    // on error
                }
            }

        }
        Log.i("MILLIS", executeTime.toString())
    }

现在,虽然我的实现同时运行(也就是说,同时开始),但我实际上想要的是并行运行它们(根据在模拟器上的线程数(在我的例子中是4个线程)在同一时间运行),所以我的目标是获取可用线程的数量,并为每个线程分配一个分析操作,每个线程占用执行时间。

到目前为止,我尝试的是在CoroutineScope(IO).launch块中,将对库的调用封装在一个任务中:

代码语言:javascript
复制
val tsk = async {
    detector!!.analyzeAsync(act, uri)
}

val result = tsk.await()

一份工作:

代码语言:javascript
复制
val tsk = withContext(IO) {
   detector!!.analyzeAsync(act, uri)
}

但是,我手动启动的异步操作只有在启动Firebase任务时才能持续,而不是等待内部任务运行到完成。我还尝试添加不同的上下文(.)和...launch {}类FaceDetectorService中的变量,但都没有效果。

显然,我对科特林合作公司非常陌生,所以我想我错过了一些非常基本的东西,但我就是不能把我的头绕在这上面。

(PS:请不要评论代码的草率,这只是一个原型:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-08 16:37:58

analyzeAsync()是一个suspend fun,并且还返回一个类似未来的Task对象。相反,它应该返回Task.await()的结果,基本上可以通过分解addOnCompleteListener调用来实现这个结果:

代码语言:javascript
复制
suspend fun <T> Task<T>.await(): T = suspendCancellableCoroutine { cont ->
    addOnCompleteListener {
        val e = exception
        when {
            e != null -> cont.resumeWithException(e)
            isCanceled -> cont.cancel()
            else -> cont.resume(result)
        }
    }
}

优化后的版本在kotlinx-coroutines-play-services模块中可用)。

因为脸检测API已经是异步的,它意味着调用它的线程是无关的,它在内部处理它的计算资源。因此,您不需要在IO dispatcher中启动,您可以在任何时候使用Main并自由地执行GUI工作,不需要上下文切换。

至于你的要点:我找不到明确的细节,但很可能单个人脸检测呼叫已经使用了智能手机上所有可用的CPU,甚至是专用的ML电路,这意味着没有什么可以从外部并行化的。仅仅是一个人脸检测请求就已经得到了所有的资源。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60583180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档