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.gradlefile and add OpenCV 4 dependency independenciessection.
app/build.gradle
dependencies {
// Other dependencies
// ...
implementation 'com.quickbirdstudios:opencv:4.5.3.0'
}
- Open a layout XML file and add
ImageView.
app/src/main/res/layout/activity_main.xml
<?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/drawabledirectory. - In the
MainActivityclass, initialize OpenCV withOpenCVLoader. - Use the method
Utils.loadResource()to load a resource. We useorange.pngimage for testing. It stored in thedrawabledirectory. - Android
Bitmapuse RGB color channels. By default, OpenCVMatuse BGR color channels. Use the methodImgproc.cvtColorto convert color channels. - Initialize a bitmap with the specified width and height using the method
Bitmap.createBitmap(). The configARGB_8888defines that each channel (RGB and alpha) is stored with 8 bits of precision. - Use the method
Utils.matToBitmap()to convert OpenCVMatto AndroidBitmap. - To display an image in the
ImageViewuse methodsetImageBitmap().
app/src/main/java/com/example/app/MainActivity.kt
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