The Wayback Machine - https://web.archive.org/web/20240915154525/https://www.geeksforgeeks.org/how-to-label-image-in-android-using-firebase-ml-kit/
Open In App

How to Label Image in Android using Firebase ML Kit?

Last Updated : 24 Feb, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 simple application in which we will be capturing an image of any object and from that, we will detect the objects present inside our image with the accuracy level. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Connect your app to Firebase

After creating a new project in Android Studio connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Firebase ML and then click on Use Firebase ML kit in Android. You can see the option below screenshot.  

After clicking on this option on the next screen click on Connect to Firebase option to connect your app to Firebase. 

Step 3: Adding dependency for language translation to build.gradle file

Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.   

// dependency for firebase core.

implementation’com.google.firebase:firebase-core:15.0.2′

// Firebase ML dependency

implementation ‘com.google.firebase:firebase-ml-vision:24.0.3’

implementation ‘com.google.firebase:firebase-ml-vision-image-label-model:20.0.1’

Step 4: Adding permissions to access the Internet and meta-data in your Android Apps AndroidManifest file  

Navigate to the app > AndroidManifest.xml file and add the below code to it. Comments are added in the code to get to know in more detail.  

XML




<!-- below line is use to add camera feature in our app -->
<uses-feature
  android:name="android.hardware.camera"
  android:required="true" />
  
<!-- permission for internet -->
<uses-permission android:name="android.permission.INTERNET" />


Add the below line inside your application tag. 

XML




<meta-data
  android:name="com.google.firebase.ml.vision.DEPENDENCIES"
  android:value="label" />


Below is the complete code for the AndroidManifest.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
    package="com.example.labelimage">
  
    <!-- below line is use to add camera feature in our app -->
    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
  
    <!-- permission for internet -->
    <uses-permission android:name="android.permission.INTERNET" />
  
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.LabelImage">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
  
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
  
        <meta-data
            android:name="com.google.firebase.ml.vision.DEPENDENCIES"
            android:value="label" />
          
    </application>
  
</manifest>


Step 5: 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">
  
    <!--image view for displaying our image-->
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:scaleType="centerCrop" />
  
    <LinearLayout
        android:id="@+id/idLLButtons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/image"
        android:orientation="horizontal">
  
        <!--button for capturing our image-->
        <Button
            android:id="@+id/snapbtn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_marginTop="30dp"
            android:layout_weight="1"
            android:text="SNAP"
            android:textSize="25dp"
            android:textStyle="bold" />
  
        <!--button for detecting the objects-->
        <Button
            android:id="@+id/labelBtn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_marginTop="30dp"
            android:layout_weight="1"
            android:text="Label"
            android:textSize="25dp"
            android:textStyle="bold" />
  
    </LinearLayout>
  
    <!--recycler view for displaying the list of objects-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVResults"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idLLButtons" />
  
</RelativeLayout>


Step 6: Creating a modal class for storing our data

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as DataModal and add the below code to it. Comments are added inside the code to understand the code in more detail.

Java




public class DataModal {
  
    // variables for our 
    // string and confidence.
    private String result;
    private float confidence;
  
    // constructor
    public DataModal(String result, float confidence) {
        this.result = result;
        this.confidence = confidence;
    }
  
    // getter and setter methods
    public float getConfidence() {
        return confidence;
    }
  
    public void setConfidence(float confidence) {
        this.confidence = confidence;
    }
      
    public String getResult() {
        return result;
    }
  
    public void setResult(String result) {
        this.result = result;
    }
      
}


Step 7: Creating a layout file for displaying our recycler view items

Navigate to the app > res > layout > Right-click on it > New > layout resource file and name it as result_rv_item and add below code to it. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:elevation="8dp"
    app:cardCornerRadius="8dp">
  
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp">
  
        <!--text view for our result-->
        <TextView
            android:id="@+id/idTVResult"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="3dp"
            android:text="Result"
            android:textColor="@color/black" />
  
        <!--text view for our confidence-->
        <TextView
            android:id="@+id/idTVConfidence"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVResult"
            android:padding="3dp"
            android:text="Confidence"
            android:textColor="@color/black" />
  
    </RelativeLayout>
  
</androidx.cardview.widget.CardView>


Step 8: Creating an adapter class for our RecyclerView

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as resultRVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail.

Java




import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class resultRVAdapter extends RecyclerView.Adapter<resultRVAdapter.ViewHolder> {
      
    // arraylist for storing our data and context
    private ArrayList<DataModal> dataModalArrayList;
    private Context context;
  
    // constructor for our variables
    public resultRVAdapter(ArrayList<DataModal> dataModalArrayList, Context context) {
        this.dataModalArrayList = dataModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // inside on create view holder method we are inflating our layout file which we created.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.result_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // inside on bind view holder method we are setting
        // data to each item of recycler view.
        DataModal modal = dataModalArrayList.get(position);
        holder.resultTV.setText(modal.getResult());
        holder.confidenceTV.setText("" + modal.getConfidence());
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return dataModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our text view.
        private TextView resultTV, confidenceTV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our views with their ids.
            resultTV = itemView.findViewById(R.id.idTVResult);
            confidenceTV = itemView.findViewById(R.id.idTVConfidence);
        }
    }
}


Step 9: 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




import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.label.FirebaseVisionImageLabel;
import com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler;
  
import java.util.ArrayList;
import java.util.List;
  
public class MainActivity extends AppCompatActivity {
  
    // variables for our image view, image bitmap,
    // buttons, recycler view, adapter and array list.
    private ImageView img;
    private Button snap, labelBtn;
    private Bitmap imageBitmap;
    private RecyclerView resultRV;
    private resultRVAdapter resultRvAdapter;
    private ArrayList<DataModal> dataModalArrayList;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing all our variables for views
        img = (ImageView) findViewById(R.id.image);
        snap = (Button) findViewById(R.id.snapbtn);
        labelBtn = findViewById(R.id.labelBtn);
        resultRV = findViewById(R.id.idRVResults);
          
        // initializing our array list
        dataModalArrayList = new ArrayList<>();
          
        // initializing our adapter class.
        resultRvAdapter = new resultRVAdapter(dataModalArrayList, MainActivity.this);
          
        // layout manager for our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
          
        // on below line we are setting layout manager 
        // and adapter to our recycler view.
        resultRV.setLayoutManager(manager);
        resultRV.setAdapter(resultRvAdapter);
  
        // adding on click listener for our label button.
        labelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calling method 
                // to label images.
                labelImage();
            }
        });
        // adding on click listener for our snap button.
        snap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calling a method 
                // to capture an image.
                dispatchTakePictureIntent();
            }
        });
    }
  
    static final int REQUEST_IMAGE_CAPTURE = 1;
  
    private void dispatchTakePictureIntent() {
        // inside this method we are calling an implicit intent to capture an image.
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // calling a start activity for result when image is captured.
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
  
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // inside on activity result method we are setting
        // our image to our image view from bitmap.
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            imageBitmap = (Bitmap) extras.get("data");
            // on below line we are setting our
            // bitmap to our image view.
            img.setImageBitmap(imageBitmap);
        }
    }
  
    private void labelImage() {
        
        // inside the label image method we are calling a 
        // firebase vision image and passing our image bitmap to it.
        FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(imageBitmap);
          
        // on below line we are creating a labeler for our image bitmap
        // and creating a variable for our firebase vision image labeler.
        FirebaseVisionImageLabeler labeler = FirebaseVision.getInstance().getOnDeviceImageLabeler();
          
        // calling a method to process an image and adding on success listener method to it.
        labeler.processImage(image).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionImageLabel>>() {
            @Override
            public void onSuccess(List<FirebaseVisionImageLabel> firebaseVisionImageLabels) {
                  
                  // inside on success method we are running a loop to get the data from our list.
                for (FirebaseVisionImageLabel label : firebaseVisionImageLabels) {
                    
                    // on below line we are getting text from our list.
                    String text = label.getText();
                      
                    // on below line we are getting its entity id
                    String entityId = label.getEntityId();
                      
                    // on below line we are getting the
                    // confidence level of our modal.
                    float confidence = label.getConfidence();
                     
                    // after getting all data we are passing it to our array list.
                    dataModalArrayList.add(new DataModal(text, confidence));
                      
                    // after adding a new data we are notifying 
                    // our adapter that data has been updated.
                    resultRvAdapter.notifyDataSetChanged();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // error handling for on failure method
                Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();
            }
        });
    }
}


Now run your app and see the output of the app. 

Output:

Note: If you are facing the following NDK at ~/Library/Android/sdk/ndk-bundle did not have a source.properties file error then please refer to this article. 



Similar Reads

Text Detector in Android using Firebase ML Kit
Nowadays many apps using Machine Learning inside their apps to make most of the tasks easier. We have seen many apps that detect text from any image. This image may include number plates, images, and many more. In this article, we will take a look at the implementation of Text Detector in Android using Firebase ML Kit. What we are going to build in
6 min read
How to Create Language Detector in Android using Firebase ML Kit?
We have seen many apps providing different language supports inside their application and we also have seen many ML apps in which we will get to see that we can detect the language of the text which is entered by the user. In this article, we will create an application in which we will detect the language of the entered text in our Android App. So
5 min read
How to Create Language Translator in Android using Firebase ML Kit?
In the previous article, we have seen using Language detector in Android using Firebase ML kit. In this article, we will take a look at the implementation of Language translator in Android using Firebase ML Kit in Android. What we are going to build in this article? We will be building a simple application in which we will be showing an EditText fi
5 min read
How to create a Face Detection Android App using Machine Learning KIT on Firebase
Pre-requisites: Firebase Machine Learning kitAdding Firebase to Android AppFirebase ML KIT aims to make machine learning more accessible, by providing a range of pre-trained models that can use in the iOS and Android apps. Let's use ML Kit’s Face Detection API which will identify faces in photos. By the end of this article, we’ll have an app that c
9 min read
How to Setup Firebase Local Emulators for using Firebase Console and All Firebase Services?
Firebase Emulators are used to test our projects on the local firebase server (Emulator). It provides all the services of the Firebase Console. It is most useful for firebase functions because to use firebase functions we have to take the Blaze plan of firebase means we must have a credit card, here is a solution to this problem we can test our mob
4 min read
How to Use Firebase ML Kit Smart Replies in Android?
We have seen using chatbots in Android for replying to the most common questions from the users. In this article, we will take a look at the implementation of Firebase ML Kit smart replies in Android. Firebase ML Kit smart replies are used to provide smart replies to the questions asked by the users using the Firebase ML Kit. What we are going to b
8 min read
Face Detection in Flutter using Firebase ML Kit
Face detection is a technique by which we can locate the human faces in the image given. Face detection is used in many places nowadays, especially websites hosting images like Picasa, Photobucket, and Facebook. The automatic tagging feature adds a new dimension to sharing pictures among the people who are in the picture and also gives the idea to
5 min read
Firebase Machine Learning kit
Back in the days, using machine learning capabilities was only possible over the cloud as it required a lot of compute power, high-end hardware etc… But mobile devices nowadays have become much more powerful and our Algorithms more efficient. All this has led to on-device machine learning a possibility and not just a science fiction theory. Firebas
2 min read
Android - Detect Open or Closed Eyes Using ML Kit and CameraX
Google's ML kit is one of the best-trained models for face detection and its characteristics. Integrating with your own CameraX library can be quite a challenging task. so we are going to build an Android app that will detect whether a person's eyes are open or closed in real time. This process going to be long so without delay let's deep dive into
10 min read
Multi-Label Image Classification - Prediction of image labels
There are so many things we can do using computer vision algorithms: Object detectionImage segmentationImage translationObject tracking (in real-time), and a whole lot more. What is Multi-Label Image Classification? Let’s understand the concept of multi-label image classification with an intuitive example. If I show you an image of a ball, you'll e
8 min read
Android: How to Upload an image on Firebase storage?
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for Firebase application. This article explains how to build an Android application with the ability to select the image from the mobile gallery and uploa
5 min read
How to Retrieve Image from Firebase in Realtime in Android?
When we are creating an android app then instead of inserting an image manually we want to get that from the internet and using this process the app size will become less. So, using firebase we can do this. We can create our storage bucket and we can insert our image there and get it directly into our app. But what if we want to change that image a
4 min read
How to Implement Image only Message Layout of Firebase In-App Messaging in Android?
Prerequisite: How to Push Notification in Android using Firebase In-App Messaging? We have seen the implementation of Firebase In-App Messaging in Android. In that article, we have implemented the Card Message Layout. In this article, we will take a look at the implementation of the Image only Message Layout. A sample image is given below to get an
3 min read
Android Jetpack Compose - Retrieve Image From Firebase in Realtime
When we are creating an android app then instead of inserting an image manually we want to get that from the internet and using this process the app size will become less. So, using firebase we can do this. We can create our storage bucket and we can insert our image there and get it directly into our app. But what if we want to change that image a
7 min read
How to Compress Image in Android Before Uploading it to Firebase Storage?
Usually, in an app we make users upload images like profile images or others. But there is a chance that the uploaded image is only for display purposes, that too in a short frame. So, these images do not have to be stored in a high-resolution format. Hence even if the user uploads a high-resolution pic, the image must be compressed before storing
4 min read
How to Create Dynamic Auto Image Slider in Android with Firebase?
We have seen many apps that display images in the slider format as that of banners which slide automatically. This type of feature of the auto image slider is seen in many E-commerce sites. This feature is seen in many apps which are having images in them. In this article, we will take a look at How to Create a dynamic Auto Image Slider in Android.
9 min read
Android - Upload an Image on Firebase Storage with Kotlin
Firebase Cloud Storage stores files in the Google Cloud Storage bucket and makes them accessible through both Firebase and Google Cloud. It allows us to upload and download files from mobile clients through the Firebase SDKs, and perform server-side processing such as image filtering or video transcoding using the Google Cloud Platform. In this art
6 min read
How to Add Firebase Analytics to Android App in Android Studio?
Analytics is one of the important tools that developers should definitely used while building their applications. It is very helpful to target your apps for various audience ranges and to track on which screen the users are spending a long time. So it is one of the important features which one should not miss adding while building any Android Appli
4 min read
Flutter - On-Device Machine Learning using ML Kit
Machine Learning is being used widely in projects today. It requires knowledge of Machine Learning to create models, for application developers who want to use Machine Learning in the project but don't know how to create a model. In Flutter, certain developments have been done by Google to help developers create the application they want. Although
7 min read
Download and Install Java Development Kit (JDK) on Windows, Mac, and Linux
Setting up a Suitable Development Environment is necessary before one can begin creating Android Applications. It makes it easier for developers to use the tools required to create any Application and ensures that all Operations or Processes run smoothly. Download and Install JDK in order to create Android Application Source Files using the Java or
5 min read
How to populate RecyclerView with Firebase data using FirebaseUI in Android Studio
Firebase is one of the most popular online databases in use today and will be the same for at least a few years to come. Firebase offers a Realtime Database that can be used to store and retrieve data in real-time to all users. In this post, let's connect the Realtime Database with an Android application and show the data in RecyclerView using the
7 min read
How to Build a QR Code Android App using Firebase?
QR (Quick Response) code is a type of two-dimensional barcode that contains information encoded in a pattern of black and white squares. It was first developed in 1994 by a company named Denso Wave. Qr codes can be scanned by a smartphone or a dedicated QR code scanner, which uses the device's camera to read the code and extract the information sto
6 min read
How to Change Password of User in Android using Firebase?
In many apps, we got a feature to login using our email and password. Sometimes it happens that we forget the password and most of the time there reset our password. Here we are going to implement the same feature to Reset our password using Firebase Authentication. You may refer to the following article User authentication using Firebase in Androi
3 min read
Phone Number Verification using Firebase in Android
Phone number Firebase Authentication is used to sign in a user by sending an SMS message to the user's phone. The user signs in using a one-time code contained in the SMS message. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. [v
6 min read
How to Push Notification in Android using Firebase In-App Messaging?
We have seen using Firebase push notifications in Android which is used to send push notifications to our users when our user is online. These notifications are being displayed inside the notifications tab in the top section of our phone. In this article, we will take a look at the implementation of Firebase In-App Messaging to display messages to
6 min read
How to Update User's Profile After Signing Through GitHub using Firebase in Android?
In this article, we will learn to update user's profiles who signed in to the app through GitHub. The profile will be updated through the user's GitHub information like GitHub Id, name, followers, following, etc. Let's start! Step 1: First set up your app so that users can be signed in through GitHub. So you need to authenticate the user using GitH
7 min read
How to Upload a Video in Firebase Database using Android Studio?
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for the Firebase application. This article explains how to build an Android application with the ability to select a video from the mobile gallery and upl
3 min read
Login and Registration in Android using Firebase in Kotlin
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building the backend for user authentication. In this article, we will learn the firebase authentication feature. Using it we can
4 min read
How to Upload Android APK to Testers Group in Firebase Using GitHub Actions?
Testing is always required whenever we build an app to ensure it functions properly in production. It might be time-consuming and inconvenient to send the application to the testers every time new code is merged into the codebase. So to solve this problem, CD pipelines can be used to deliver the software to the testers. In this article, we'll be le
3 min read
Android Jetpack Compose - Create Dynamic WebView using Firebase Realtime Database
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView that we have to load. So if you are looking for loading a website into your app which can be changed dynam
8 min read