The ImageClassifier Class
Learn to implement the ImageClassifier class of an image classification Android app that utilizes a TF Lite model to classify images.
The ImageClassifier class is responsible for classifying an image into predefined categories. It takes a Bitmap image as input, resizes it to the required input size, converts it to a ByteBufferimageClassifier class.
Fields
The following code defines the fields of the ImageClassifier class.
Line 5: This imports the TF Lite interpreter,
import org.tensorflow.lite.Interpreter.Line 16: This declares the
ImageClassifierclass. It takes acontext : Contextobject as a constructor parameter, which allows access to the app’s resources, like assets, and creates a file path to store the DL model file. It’s an instance of theContextclass that holds application-specific information, resources, or context.Lines 18–27: These declare a companion object associated with the
ImageClassifierclass. It contains various constants related to the image classification model, such as the batch size, input image size, number of classes, pixel size, image mean, image standard deviation, model file name, and label file name. These constants define properties of the model and we can access them using the class name followed by the constant name, for instance,ImageClassifier.MODEL_FILE.Lines 29–31: These declare a
valpropertyinterpreterthat’s lazily initialized using thelazydelegate, meaning theinterpreterinitializes when we access it for the first time. Theinterpreteris an instance of the TF LiteInterpreterclass, which loads a pretrained DL model using theloadModelFile()function and anInterpreter.Optionsobject. The interpreter is responsible for executing the computation graph of the pretrained model, which takes the input image in the form of aByteBufferand returns the classification result.Lines 32–34: These declare another
valproperty,labelList : List, that stores the list of labels a TF Lite model can recognize. The output of the model is a probability distribution over all the possible classes, and we uselabelListto map these probabilities to their corresponding labels to notify the app user. ThelabelListproperty is of the typeList<String>that’s initialized by loading the labels associated with the image classes using theloadLabels()function.
The loadModelFile() method
The loadModelFile() method of the ImageClassifier class loads the TF ...