OpenCV is an open-source library that can be used for image processing, computer vision, machine learning, etc. OpenCV 4 can be easily integrated into Android via Gradle using com.quickbirdstudios:opencv
dependency. It doesn't require Android NDK toolset.
This tutorial provides step by step how to set up OpenCV 4 in Android project.
- Open Android Studio and start a new project.
- Choose empty activity.
- Provide application name, package name and location where project should be saved. Choose Java or Kotlin language.
- Open module's
build.gradle
file and add OpenCV 4 dependency independencies
section.
dependencies {
// Other dependencies
// ...
implementation 'com.quickbirdstudios:opencv:4.5.3.0'
}
- Open a layout XML file and add
ImageView
.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/myImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
- Copy the test image into
app/src/main/res/drawable
directory. - In the
MainActivity
class, initialize OpenCV withOpenCVLoader
. - Use the method
Utils.loadResource()
to load a resource. We useorange.png
image for testing. It stored in thedrawable
directory. - Android
Bitmap
use RGB color channels. By default, OpenCVMat
use BGR color channels. Use the methodImgproc.cvtColor
to convert color channels. - Initialize a bitmap with the specified width and height using the method
Bitmap.createBitmap()
. The configARGB_8888
defines that each channel (RGB and alpha) is stored with 8 bits of precision. - Use the method
Utils.matToBitmap()
to convert OpenCVMat
to AndroidBitmap
. - To display an image in the
ImageView
use methodsetImageBitmap()
.
package com.example.app
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import org.opencv.android.OpenCVLoader
import org.opencv.android.Utils
import org.opencv.imgproc.Imgproc
class MainActivity : AppCompatActivity()
{
companion object {
init {
if (OpenCVLoader.initDebug()) {
Log.d("MY_APP", "OpenCV loaded")
}
}
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mat = Utils.loadResource(this, R.drawable.orange)
Imgproc.cvtColor(mat, mat, Imgproc.COLOR_BGR2RGB)
val bitmap = Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888)
Utils.matToBitmap(mat, bitmap)
val myImageView: ImageView = findViewById(R.id.myImageView)
myImageView.setImageBitmap(bitmap)
}
}
Leave a Comment
Cancel reply