Solution to Creating an Image Classifier
Tags: machinelearning
Published: 2022-04-13 08:10:47

I don't know if it's the same for you, but I always get frustrated when sorting through my phone's album. It seems to take forever before I can find the image that I want to use. As a coder, I can't help but wonder if there's a solution for this. Is there a way to organize an entire album? Well, let's take a look at **how to develop an image classifier using a service called image classification**.

## Development Preparations
1.Configure the Maven repository address for the SDK to be used.
```
repositories {
    maven { 
url'https://cmc.centralrepo.rnd.huawei.com/artifactory/product_maven/' }
}
```
2.Integrate the image classification SDK.
```
dependencies {
    // Import the base SDK.
    implementation 'com.huawei.hms:ml-computer-vision-classification:3.3.0.300'
    // Import the image classification model package.
    implementation 'com.huawei.hms:ml-computer-vision-image-classification-model:3.3.0.300'
```
## Project Configuration
1.Set the authentication information for the app.
This information can be set through an API key or access token.
Use the **setAccessToken** method to set an access token during app initialization. This needs to be set only once.
```
MLApplication.getInstance().setAccessToken("your access token");
```
Or, use **setApiKey** to set an API key during app initialization. This needs to be set only once.
```
MLApplication.getInstance().setApiKey("your ApiKey");
```
2.Create an image classification analyzer in on-device static image detection mode.
```
// Method 1: Use customized parameter settings for device-based recognition.
MLLocalClassificationAnalyzerSetting setting = 
    new MLLocalClassificationAnalyzerSetting.Factory()
        .setMinAcceptablePossibility(0.8f)
        .create(); 
MLImageClassificationAnalyzer analyzer = MLAnalyzerFactory.getInstance().getLocalImageClassificationAnalyzer(setting);
// Method 2: Use default parameter settings for on-device recognition.
MLImageClassificationAnalyzer analyzer = MLAnalyzerFactory.getInstance().getLocalImageClassificationAnalyzer();
```
3.Create an MLFrame object.
```
// Create an MLFrame object using the bitmap which is the image data in bitmap format. JPG, JPEG, PNG, and BMP images are supported. It is recommended that the image dimensions be greater than or equal to 112 x 112 px.
MLFrame frame = MLFrame.fromBitmap(bitmap);
```
4.Call asyncAnalyseFrame to classify images.
```
Task<List<MLImageClassification>> task = analyzer.asyncAnalyseFrame(frame); 
task.addOnSuccessListener(new OnSuccessListener<List<MLImageClassification>>() {
    @Override
    public void onSuccess(List<MLImageClassification> classifications) {
        // Recognition success.
        // Callback when the MLImageClassification list is returned, to obtain information like image categories.
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        // Recognition failure.
        try {
            MLException mlException = (MLException)e;
            // Obtain the result code. You can process the result code and customize relevant messages displayed to users.
            int errorCode = mlException.getErrCode();
            // Obtain the error message. You can quickly locate the fault based on the result code.
            String errorMessage = mlException.getMessage();
        } catch (Exception error) {
            // Handle the conversion error.
        }
    }
});
```
5.Stop the analyzer after recognition is complete.
```
try {
    if (analyzer != null) {
       analyzer.stop();
    }
} catch (IOException e) {
    // Exception handling.
}
```
## Demo
![Demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bciehosnhjdylklm80v0.png)

## Remarks
The image classification capability supports the on-device static image detection mode, on-cloud static image detection mode, and camera stream detection mode. The demo here illustrates only the first mode.

I came up with a bunch of application scenarios to use image classification, for example: **education apps**. With the help of image classification, such an app enables its users to categorize images taken in a period into different albums; **travel apps**. Image classification allows such apps to classify images according to where they are taken or by objects in the images; **file sharing apps**. Image classification allows users of such apps to upload and share images by image category.

Image classification [Development Guide](https://developer.huawei.com/consumer/en/doc/development/hiai-Guides/image-classification-0000001050040095?ha_source=hms1)
[Reddit](https://www.reddit.com/r/HMSCore/) to join developer discussions
[GitHub](https://github.com/HMS-Core) to download the sample code
[Stack Overflow](https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Votes) to solve integration problems