当前位置:网站首页>【Android,Kotlin,TFLite】移动设备集成深度学习轻模型TFlite(物体检测篇)
【Android,Kotlin,TFLite】移动设备集成深度学习轻模型TFlite(物体检测篇)
2022-06-30 22:10:00 【mozhimen】
深度学习.Tensorflow.TFLite.移动设备集成深度学习轻模型TFlite.图像分类篇
Why i create it?
为了创建一个易用且易于集成的TFlite加载库, 所以TFLiteLoader应运而生
- 开源Github项目地址 TFLiteLoader
集成 ObjectDetector
依赖
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.mozhimen.TFLiteLoader:objectdetector:1.0.2'
}
接入
- 全局声明
private lateinit var _tfLiteObjectDetector: TFLiteObjectDetector
- 在onCreate中进行初始化
_tfLiteObjectDetector = TFLiteObjectDetector.create("efficientdet-lite0.tflite", listener = _objectDetectorListener)
- 异步声明_objectDetectorListener
private val _objectDetectorListener: IObjectDetectorListener = object : IObjectDetectorListener {
override fun onError(error: String) {
runOnUiThread {
error.showToast()
}
}
override fun onResults(imageWidth: Int, imageHeight: Int, inferenceTime: Long, results: MutableList<Detection>?) {
runOnUiThread {
results?.let {
vb.objectDetectionOverlay.setObjectRect(imageWidth, imageHeight, results)
}
}
}
}
- 物体检测
_tfLiteObjectDetector.detect({你的Bitmap}, 0)
- 对返回数据的处理示例, 可以pull代码参考demo, 这是回调中的处理
override fun onResults(imageWidth: Int, imageHeight: Int, inferenceTime: Long, results: MutableList<Detection>?) {
runOnUiThread {
results?.let {
vb.objectDetectionOverlay.setObjectRect(imageWidth, imageHeight, results)
}
}
}
- 结果
对于返回值的说明
- MutableList{Detection}
@AutoValue
@UsedByReflection("object_detection_jni.cc")
public abstract class Detection {
public Detection() {
}
@UsedByReflection("object_detection_jni.cc")
public static Detection create(RectF boundingBox, List<Category> categories) {
return new AutoValue_Detection(new RectF(boundingBox), Collections.unmodifiableList(new ArrayList(categories)));
}
//检测物体在画面的位置信息
public abstract RectF getBoundingBox();
//类别集合
public abstract List<Category> getCategories();
}
完整demo代码
@PermissionKAnnor(permissions = [Manifest.permission.CAMERA])
class ObjectDetectionActivity : BaseKActivity<ActivityObjectDetectionBinding, BaseKViewModel>(R.layout.activity_object_detection) {
private lateinit var _tfLiteObjectDetector: TFLiteObjectDetector
private val _objectDetectorListener: IObjectDetectorListener = object : IObjectDetectorListener {
override fun onError(error: String) {
runOnUiThread {
error.showToast()
}
}
override fun onResults(imageWidth: Int, imageHeight: Int, inferenceTime: Long, results: MutableList<Detection>?) {
runOnUiThread {
results?.let {
vb.objectDetectionOverlay.setObjectRect(imageWidth, imageHeight, results)
}
}
}
}
override fun initData(savedInstanceState: Bundle?) {
PermissionK.initPermissions(this) {
if (it) {
initView(savedInstanceState)
} else {
PermissionK.applySetting(this)
}
}
}
override fun initView(savedInstanceState: Bundle?) {
initLiteLoader()
initCamera()
}
private fun initLiteLoader() {
_tfLiteObjectDetector = TFLiteObjectDetector.create("efficientdet-lite0.tflite", listener = _objectDetectorListener)
// _tFLiteLabelImageClassifier = TFLiteLabelImageClassifier.create("?", "labels.txt", modelType = ModelType.QUANTIZED_EFFICIENTNET)
// _tFImageClassifier = TFImageClassifier.create("output_graph.pb", "output_labels.txt", "input", 299, "output", 128f, 128f, 0.1f, 1)
}
private fun initCamera() {
vb.objectDetectionPreview.initCamera(this, CameraSelector.DEFAULT_BACK_CAMERA)
vb.objectDetectionPreview.setImageAnalyzer(_frameAnalyzer)
vb.objectDetectionPreview.startCamera()
}
private val _frameAnalyzer: ImageAnalysis.Analyzer by lazy {
object : ImageAnalysis.Analyzer {
private val _reentrantLock = ReentrantLock()
@SuppressLint("UnsafeOptInUsageError", "SetTextI18n")
override fun analyze(image: ImageProxy) {
try {
_reentrantLock.lock()
val bitmap: Bitmap = if (image.format == ImageFormat.YUV_420_888) {
ImageConverter.yuv2Bitmap(image)!!
} else {
ImageConverter.jpeg2Bitmap(image)
}
val rotateBitmap = UtilKBitmap.rotateBitmap(bitmap, 90)
_tfLiteObjectDetector.detect(rotateBitmap, 0)
} finally {
_reentrantLock.unlock()
}
image.close()
}
}
}
}
关于这里的框架代码, 可以参考我另一个开源框架库: SwiftKit ,不过因为还未完成, 没有完整的wiki, 过段时间推出
- 本示例代码所持引用:
implementation 'com.github.mozhimen.SwiftKit:basick:1.1.1'
implementation('com.github.mozhimen.SwiftKit:abilityk:1.1.1') {
exclude group: 'com.mozhimen.abilityk.scank'
exclude group: 'com.huawei.hms'
}
implementation 'com.github.mozhimen.SwiftKit:componentk:1.1.1'
综上所述: 集成是不是很简单, 那赶快试试吧
边栏推荐
- 【BSP视频教程】BSP视频教程第19期:单片机BootLoader的AES加密实战,含上位机和下位机代码全开源(2022-06-26)
- Analysis of PostgreSQL storage structure
- 阿婆做的臭豆腐
- Inventory the six second level capabilities of Huawei cloud gaussdb (for redis)
- Uniapp routing uni simple router
- Look at the top 10 capabilities of alicloud cipu
- Introduction and example of template method mode
- 请指教同花顺软件究竟是什么?另外想问,现在在线开户安全么?
- When unittest automatically tests multiple use cases, the logging module prints repeatedly to solve the problem
- Installing jupyter notebook under Anaconda
猜你喜欢
腾讯3年,功能测试进阶自动化测试,送给在手工测试中迷茫的你
dba
京东与腾讯续签三年战略合作协议;起薪涨至26万元,韩国三星SK争相加薪留住半导体人才;Firefox 102 发布|极客头条
How to use data sets in machine learning?
PostgreSQL存储结构浅析
看阿里云 CIPU 的 10 大能力
Label Contrastive Coding based Graph Neural Network for Graph Classification
[introduction to MySQL] the first conversation · first time in the "database" Mainland
Go language learning notes - Gorm usage - database configuration, table addition | web framework gin (VII)
Nansen double disk encryption giant self rescue: how to prevent the collapse of billions of dominoes
随机推荐
Vite2 is compatible with lower versions of chrome (such as Sogou 80). Some grammars requiring higher versions are processed through polyfills
What if the taskbar is blank after win11 update? Solution to blank and stuck taskbar after win11 update
How to change the win11 computer name? Win11 method of changing computer name
Uniapp rich text editor
在启牛开的股票账户安全吗?如何申请低佣金的股票账户?
2022-06-30:以下golang代码输出什么?A:0;B:2;C:运行错误。 package main import “fmt“ func main() { ints := make
Ml & DL: Introduction à l’optimisation des hyperparamètres, indice d’évaluation, phénomène de surajustement et introduction détaillée aux méthodes d’optimisation des paramètres couramment utilisées da
[micro service ~nacos] configuration center of Nacos
Nansen double disk encryption giant self rescue: how to prevent the collapse of billions of dominoes
The programmer's girlfriend gave me a fatigue driving test
WinDbg debugging tool introduction
Do a scrollbar thinking
Nansen复盘加密巨头自救:如何阻止百亿多米诺倾塌
部门新来了个阿里25K出来的,让我见识到了什么是天花板
Inventory the six second level capabilities of Huawei cloud gaussdb (for redis)
交易所系统开发如何开发?数字货币交易所系统开发成熟技术案例
将Nagios监控信息存入MySQL
5G 在智慧医疗中的需求
When unittest automatically tests multiple use cases, the logging module prints repeatedly to solve the problem
机器学习中如何使用数据集?