Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting bitmap to mat in Java for image processing

Hi i want to do image processing by using openCV in my Java Android project. So now i'm having issue when reading the image file and convert it into mat. I've tried by reading the image directly and read it as Mat but still doesn't work:

//get image source from folder
    String imgPath =  Environment.getExternalStorageDirectory().toString() + "/SimpleAndroidOCR/ocr.jpg";
    Mat sourceImage = Imgcodecs.imread(imgPath);

Then I tried to get the bitmap and convert it to Mat but still doesn't work:

Bitmap bitmap1 = BitmapFactory.decodeFile(_path, options);
Mat sourceImage = new Mat();
Utils.bitmapToMat(bitmap1 , sourceImage);

Could anyone tell me what did I do wrong? Thanks in advance

like image 317
Andreas Dimas Avatar asked Mar 15 '26 06:03

Andreas Dimas


1 Answers

I found solution for my own issue. I'm referring to this Android & OpenCV : Utils.bitmapToMat crashes whereby it mentions that we need to load the library in order to use openCV related code Here is my code to load the library:

 private BaseLoaderCallback mLoaderCallBack = new BaseLoaderCallback(this) {
    @Override
    public void onManagerConnected(int status) {
        if(status == LoaderCallbackInterface.SUCCESS){

        }else{
            super.onManagerConnected(status);
        }

    }
};

public void onResume(){
    super.onResume();
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, mLoaderCallBack);
}

Please take note that you should change the opencv version to match with version that you use.

In order to convert bitmap to mat i'm referring to this https://groups.google.com/forum/#!topic/android-opencv/8EoxpTb4W3E bitmaptomat only works when we have proper bitmap format which is ARGB_8888 Here is my code:

    private Bitmap JPGtoRGB888(Bitmap img){
        Bitmap result = null;

        int numPixels = img.getWidth() * img.getHeight();
        int[] pixels = new int[numPixels];

//        get jpeg pixels, each int is the color value of one pixel
        img.getPixels(pixels,0,img.getWidth(),0,0,img.getWidth(),img.getHeight());

//        create bitmap in appropriate format
        result = Bitmap.createBitmap(img.getWidth(),img.getHeight(), Bitmap.Config.ARGB_8888);

//        Set RGB pixels
        result.setPixels(pixels, 0, result.getWidth(), 0, 0, result.getWidth(), result.getHeight());

        return result;
    }

This function will be called here

Bitmap bmp32 = JPGtoRGB888(bitmap);
Mat sourceImage = new Mat();
Utils.bitmapToMat(bmp32, sourceImage);

Then you can process the sourceImage Hope this is helpful Cheers!

like image 92
Andreas Dimas Avatar answered Mar 17 '26 20:03

Andreas Dimas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!