Open In App

How to Load an Image using OpenCV in Android?

Last Updated : 01 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library which is used for image and video processing. In this article, we are going to build an application that shows the demonstration of how we can load images in OpenCV on Android.

Mat Class in OpenCV

The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It can be used to store real or complex-valued vectors and matrices, grayscale or color images, etc.

Prerequisite: It is very important to integrate OpenCV in Android Studio to make this application. If you haven’t done it then you can go through the below article: How to Add OpenCV library into Android Application using Android Studio?

What we are going to build in this article?

In this article, we will be creating an application with two features i.e to select and capture images in OpenCV and then perform a small operation of converting them images from RGB to Gray. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1. Create a New Project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • Name the application at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?

Step 2. Adding permissions required

 Navigate to app > manifests > AndroidManifest.xml file and paste the following piece of code to add camera permission

<uses-permission android:name="android.permission.CAMERA"/>

Step 3: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <ImageView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:id="@+id/imageView"
        android:background="#000"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        />
  
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select"
        android:id="@+id/select"
        android:layout_below="@id/imageView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        />
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Camera"
        android:id="@+id/Camera"
        android:layout_below="@id/select"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        />
  
</RelativeLayout>


After implementing the above code design of activity_main.xml file will look like this-

 

Step 4: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




package com.example.open_cv;
  
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
  
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
  
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
  
import java.io.IOException;
  
public class MainActivity extends AppCompatActivity {
  
    // initializing variables
    Button select,camera;
    ImageView imageView;
    Bitmap bitmap;
    int select_code=100,camera_code=102;
    Mat mat;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
          // to check if openCV is loaded
        getPermission();
        if(OpenCVLoader.initDebug())
            Log.d("Loaded","success");
        else
            Log.d("Loaded","error");
  
        camera=findViewById(R.id.Camera);
        select=findViewById(R.id.select);
        imageView=findViewById(R.id.imageView);
  
        // for select button
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent,select_code);
            }
        });
  
        // for the camera button
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent,camera_code);
            }
        });
    }
  
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
  
        if(requestCode==select_code && data!=null)
        {
            try {
                bitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(),data.getData());
                imageView.setImageBitmap(bitmap);
  
                  // using mat class
                mat=new Mat();
                Utils.bitmapToMat(bitmap,mat);
  
                  // converting RGB to gray
                Imgproc.cvtColor(mat,mat,Imgproc.COLOR_RGB2GRAY);
  
                Utils.matToBitmap(mat,bitmap);
                imageView.setImageBitmap(bitmap);
  
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
  
        if(requestCode==camera_code && data!=null)
        {
            bitmap=(Bitmap) data.getExtras().get("data");
            imageView.setImageBitmap(bitmap);
  
              // using mat class
            mat=new Mat();
            Utils.bitmapToMat(bitmap,mat);
            Imgproc.cvtColor(mat,mat,Imgproc.COLOR_RGB2GRAY);
  
            Utils.matToBitmap(mat,bitmap);
            imageView.setImageBitmap(bitmap);
        }
    }
  
      // get camera permission
    void getPermission()
    {
        if(checkSelfPermission(Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED)
        {
            requestPermissions(new String[]{Manifest.permission.CAMERA},101);
        }
    }
  
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  
        if(requestCode==101 && grantResults.length>0)
        {
            if(grantResults[0]!=PackageManager.PERMISSION_GRANTED)
            {
                getPermission();
            }
        }
    }
}


Here is the final output of our application.

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads