Android Studio How to read image file in OpenCV using resources?

I am trying to read image file using OpenCV Imgcodecs.imread(img) but the image Mat is always empty, I’m using this code:

package com.halocdz.qreagle;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.objdetect.QRCodeDetector;

public class MainActivity extends AppCompatActivity {

    TextView detectedData_text;
    TextView detectStatus_text;

    static
    {
        if (!OpenCVLoader.initDebug())
            Log.e("OpenCv", "Unable to load OpenCV");
        else
            Log.d("OpenCv", "OpenCV loaded");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize
        detectStatus_text = (TextView)findViewById(R.id.detectStatus_text);
        detectedData_text = (TextView)findViewById(R.id.detectedData_text);
    }

    @SuppressLint("SetTextI18n")
    public void onClickDetect(View view)
    {
        String path = getResources().getResourceName(R.drawable.qrcode);
        Mat img = Imgcodecs.imread(path + ".png");
        Mat points = new Mat();

        QRCodeDetector qrdetector = new QRCodeDetector();
        detectStatus_text.setText("Detecting QRCode, standby...");
        String data;

        if (img.empty())
        {
            detectStatus_text.setText("Error could not load image file!");
            return;
        }

        if (!qrdetector.detect(img, points))
        {
            detectStatus_text.setText("Error detecting QRCode!");
            return;
        }
        data = qrdetector.decode(img, points);

        if (data.isEmpty())
        {
            detectStatus_text.setText("Error decoding QRCode!");
            return;
        }

        detectedData_text.append(path +"\n\n");
        detectStatus_text.setText("QRCode successfully detected!");
    }
}

It appears that Imgcodecs.imread() not finding the file path to load the file, if so I don’t know how to get file correct path in app resources.

Note: I put qrcode.png file in app\src\main\res\drawable\qrcode.png.

Leave a Comment