First time here? Check out the FAQ!

Ask Your Question
0

convert cv::Mat (C++, native Code) to Bitmap (Android, Java)

asked Mar 6 '13

stephanmg gravatar image

Dear OpenCV Users,

I have the following C++ native code which I use to get an image from my (native) camera:

string Java_com_example_hellojni_HelloJni_getImageNative(JNIEnv* env, jobject thiz) {
   // first camera available
   cv::VideoCapture capture(CV_CAP_ANDROID + 0);
   // set captuer properties
   capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
   capture.set(CV_CAP_PROP_FRAME_HEIGHT, 480);

   // check if capture is opened
   if( !capture.isOpened()) return env->NewStringUTF("Capture not opened!");

   //  grab frame
   cv::Mat frame;
  capture >> frame;

// how to return the image as Bitmap to Android??
}

How would I return a Bitmap to Android Code in Java via JNI?

All the best, Stephan

Preview: (hide)

Comments

I Think this simple function code should help you much :

private void ExportMatToBitmap(Mat img_mat, String name) {
    Bitmap bmp = Bitmap.createBitmap(img_mat.cols(), img_mat.rows(),
            Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(img_mat, bmp);
    try {
        FileOutputStream out = new FileOutputStream(name);
        bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
baharsan gravatar imagebaharsan (Apr 13 '13)edit

1 answer

Sort by » oldest newest most voted
1

answered Mar 6 '13

I recommend you to pass to native code and return Mat objects. Mat object has Mat.nativeObj that holds pointer to native OpenCV Mat object you can pass it to native methods. After that you can call Utils.matToBitmap() method from OpenCV to convert OpenCV Mat object to Android Bitmap. See tutorial-2-mixedprocessing for details.

Preview: (hide)

Comments

Thank you for your quick response again! I found that article: http://stackoverflow.com/questions/9818936/display-iplimage-as-android-bitmap

I cannot proceed as you suggested because of our project's design. Is the way described in the stackoverflow post the way to go then?

all the best, Stephan

stephanmg gravatar imagestephanmg (Mar 6 '13)edit

@Alexander Smorkalov So, is there no way to do that without the android sdk? I just use opencv c++ in my Android Project and want to pass a converted Mat back to android to save it (Testing reasons, want to check if the Image is converted right). Could't I Pass back the Mat.data and use Bitmap.decodeByteArray()?

Vintez gravatar imageVintez (Nov 10 '16)edit

Question Tools

Stats

Asked: Mar 6 '13

Seen: 11,846 times

Last updated: Mar 06 '13