Friday, October 8, 2010

OpenCV in Android, setup an image from a Bitmap pixel buffer, converting

JNIEXPORT void JNICALL Java_com_convert(JNIEnv *env,
                                        jobject thiz,
                                        jobject bitmap) {
    const int width = 2592; // You can also get them through JNI
    const int height = 1952;
    IplImage* image = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 2);
    cvInitImageHeader(image,
                      cvSize(width, height),
                      IPL_DEPTH_8U, 2, IPL_ORIGIN_BL, 4);
    int *cv_data;
    AndroidBitmap_lockPixels(env, bitmap, (void**)&cv_data);
    cvSetData(image, cv_data, width * 2);
    IplImage* grey_img = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
    cvCvtColor(image, grey_img, CV_BGR5652GRAY);
    cvSetData(image, NULL, 0);


    image = grey_img;
    DO_WHAT_YOU_WANT_WITH_YOUR_IMAGE(&image);


    AndroidBitmap_unlockPixels(env, bitmap);
}


3 comments:

esmetaman said...

Do you have a HelloWorld example with Java using OpenCV?

I would like to use your technique.

Cheers

Marco Bonifazi said...

Hi,
this one is just a Java/Jni wrapper function that I used with Java on Android.
When you take a picture, there is a callback function which is automatically executed and gives you back an array of byte.

public void onPictureTaken(byte[] data, Camera camera) {
Bitmap pic = BitmapFactory.decodeByteArray(data, 0, data.length);
com.convert(pic);
}

I don't know what your requirements are, but it seems to me that there is a proper OpenCV Java wrapper on the web.

Ricardo said...

Hi, did code did´nt work for me, There is a special format to Android Bitmap? The code did´nt show any arror but when I save the image using cvSaveImage the program don´t follow.