How to Load an Image using OpenCV in Android?
Last Updated :
24 Apr, 2025
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:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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:
Similar Reads
How to Use Picasso Image Loader Library in Android?
Picasso is open source and one of the widely used image download libraries in Android. It is created and maintained by Square. It is among the powerful image download and caching library for Android. Picasso simplifies the process of loading images from external URLs and displays them on your applic
7 min read
How to Load SVG from URL in Android ImageView?
It is seen that many Android apps require to use of high-quality images that will not get blur while zooming. So we have to use high-quality images. But if we are using PNG images then they will get blur after zooming because PNG images are made up of pixels and they will reduce their quality after
4 min read
How to Label Image in Android using Firebase ML Kit?
We have seen many apps in Android in which we will detect the object present in the image whether it may be any object. In this article, we will take a look at the implementation of image labeling in Android using Firebase ML Kit. What we are going to build in this article? We will be building a s
9 min read
How to Use Universal Image Loader Library in Android?
UIL (Universal Image Loader) is a similar library to that of Picasso and Glide which performs loading images from any web URL into ImageView of Android. This image loading library has been created to provide a powerful, flexible, and customizable solution to load images in Android from Server. This
4 min read
How to Select an Image from Gallery in Android?
Selecting an image from a gallery in Android is required when the user has to upload or set their image as a profile picture or the user wants to send a pic to the other. So in this article, it's been discussed step by step how to select an image from the gallery and preview the selected image. Have
4 min read
How to Use COIL Image Loader Library in Android Apps?
COIL is an acronym for Coroutine Image Loader. COIL is one of the famous image loading libraries from URLs in Android. It is a modern library for loading images from the server. This library is used to load images from servers, assets folder as well as from the drawable folder in Android project. Th
4 min read
How to Add Image on EditText in Android?
In Android, An EditText is an overlay over a TextView that makes it editable using text by invoking a soft keyboard in run time. It is generally implemented to collect text data from the user. EditText is most commonly used in forms that require users to fill in details and for passing a search quer
3 min read
How to Animate Image Rotation in Android?
In Android, ImageView is used to display images. Images can be locally stored in the program or fetched from a network and can be displayed using the ImageView. Animations can be applied to ImageView via many techniques. We can create animations in XML files and apply them to the ImageView. Follow t
2 min read
How to Load Image From URL in Android using Jetpack Compose?
Most of the applications in android use images for displaying some useful information within the applications. Images are considered as easy to convey information to the user. An android application uses more than 100 different types of images. So it is not practically possible to add all the images
4 min read
How to Use Glide Image Loader Library in Android Apps?
Glide, like Picasso, can load and display images from many sources, while also taking care of caching and keeping a low memory impact when doing image manipulations. Official Google apps (like the app for Google I/O 2015) are using Glide. In this article, we're going to explore the functionalities o
4 min read