Home » Android » Convert a bitmap to mat and vice versa in OpenCV

Convert a bitmap to mat and vice versa in OpenCV

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have an Android Bitmap in my code and I would like to run the
cvCanny method on it. However, it needs to be in a Mat first. How do I
convert the data to Mat, and how do I convert it back to Bitmap when
I’m done?

Answers:

First import org.opencv.android.Utils

Then use:

Mat src = new Mat();
Utils.bitmapToMat(bitmap, src);

To perform edge detection:

Mat dest = new Mat();
Imgproc.Canny(src, dest, min, max);
Bitmap edgeBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(dest, edgeBitmap);
//edgeBitmap is ready