欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

玩转Android OpenCV(23):理解并应用Sobel算子进行边缘识别

最编程 2024-02-06 22:27:16
...
/** * Sobel算子-边缘检测 * * @author yidong * @date 2020-01-07 */ class SobelEdgeDetectionActivity : AppCompatActivity() { private lateinit var mBinding: ActivityEdgeDetectionBinding private lateinit var mRgb: Mat override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mBinding = DataBindingUtil.setContentView(this, R.layout.activity_edge_detection) val bgr = Utils.loadResource(this, R.drawable.lena) mRgb = Mat() Imgproc.cvtColor(bgr, mRgb, Imgproc.COLOR_BGR2RGB) showMat(mBinding.ivLena, mRgb) } private fun showMat(view: ImageView, source: Mat) { val bitmap = Bitmap.createBitmap(source.width(), source.height(), Bitmap.Config.ARGB_8888) bitmap.density = 360 Utils.matToBitmap(source, bitmap) view.setImageBitmap(bitmap) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_sobel, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.sobel_edge_detection_x -> { edgeDetectionX() } R.id.sobel_edge_detection_y -> { edgeDetectionY() } R.id.sobel_edge_detection_x_y -> { edgeDetectionXAndY() } } return true } private fun edgeDetectionX() { title = "X轴方向边缘检测" val resultX = Mat() Imgproc.Sobel(mRgb, resultX, CvType.CV_16S, 2, 0, 1) Core.convertScaleAbs(resultX, resultX) showMat(mBinding.ivResult, resultX) } private fun edgeDetectionY() { title = "Y轴方向边缘检测" val resultY = Mat() Imgproc.Sobel(mRgb, resultY, CvType.CV_16S, 0, 1, 3) Core.convertScaleAbs(resultY, resultY) showMat(mBinding.ivResult, resultY) } private fun edgeDetectionXAndY() { title = "X和Y轴方向边缘检测" val resultX = Mat() Imgproc.Sobel(mRgb, resultX, CvType.CV_16S, 2, 0, 1) Core.convertScaleAbs(resultX, resultX) showMat(mBinding.ivResult, resultX) val resultY = Mat() Imgproc.Sobel(mRgb, resultY, CvType.CV_16S, 0, 1, 3) Core.convertScaleAbs(resultY, resultY) showMat(mBinding.ivResult, resultY) val resultXY = Mat() Core.add(resultX, resultY, resultXY) showMat(mBinding.ivResult, resultXY) resultX.release() resultY.release() resultXY.release() } }