我正在尝试检测demo from github之后在Android应用中使用tensorflow segmentation
的人。演示包含如何检测相机中的分割,但是仅在特定尺寸下才有效!我的要求是使用静态图像而不是实时预览。因此,我使用了特定的图像并尝试从中生成输出。
MainActivity.kt
:
class MainActivity : AppCompatActivity() {
private lateinit var mBinding: ActivityMainBinding
private lateinit var mContext: Activity
private val scope = CoroutineScope(Dispatchers.IO)
private var bitmap: Bitmap? = null
private val TAG = "ImageDetect>>>"
private lateinit var imageSegmentationModel: ImageSegmentationModelExecutor
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mBinding.root)
mContext = this
imageSegmentationModel = ImageSegmentationModelExecutor(this, true)
Glide.with(this)
.load(R.drawable.sample)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
setLoading(false)
return false
}
override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
bitmap = (resource as BitmapDrawable).bitmap
setLoading(false)
return false
}
})
.into(mBinding.ivSample)
mBinding.btnDetect.setOnClickListener {
bitmap?.let {
setLoading(true)
try {
val bm = ImageUtils.scaleBitmapAndKeepRatio(it, 257, 257)
scope.launch {
val resultBitmap = imageSegmentationModel.execute(bm)
withContext(Dispatchers.Main) {
mBinding.ivSample.setImageBitmap(resultBitmap.bitmapMaskOnly)
setLoading(false)
}
}
} catch (exc: Exception) {
setLoading(false)
Log.e(TAG, Log.getStackTraceString(exc))
}
}
}
}
private fun setLoading(isShow: Boolean) {
if (isShow) mBinding.pbLoading.visibility = View.VISIBLE
else mBinding.pbLoading.visibility = View.GONE
}
}
ImageSegmentationModelExecutor.kt,ImageUtils.kt和ModelExecutionResult.kt是按照github代码编写的,没有任何变化。之后,我正在执行代码,它抛出错误并陷入ImageSegmentationModelExecutor.kt
类某处出错:y必须为ImageSegmentationModelExecutor
试图从原始文件生成scaledBitmap
,并试图从ByteBuffer
生成掩码。因此,错误必须仅在这两个函数中。我也了解Tensorflow
仅使用特定大小的输入来分析图像(此处指定为257),因此,我也已经将原来的bitmap
转换为257大小。但是仍然为位图抛出错误!对于具有差异大小的此类静态图像有什么解决方案吗?
答案 0 :(得分:0)
您可以尝试Imgproc.resize(matSegment, matSegment, new Size(257,257));
生成比例位图