Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android jpeg pictureCallback to grayscale Opencv Mat

I'm trying to decode android pictureCallback to grayscale mat:

Firstly I tried to use rawPicture callback but always I get null pointer.

 mCamera.takePicture(null, mPicture, null);

JpegCalback gives me not null byte[] array, but cvtColor conversion doesn't work.

mCamera.takePicture(null, null, mPicture);

My preview callback is this

Camera.PictureCallback mPicture = new Camera.PictureCallback() {
    @Override
        public void onPictureTaken(byte[] data, Camera camera) {

        Toast.makeText(getApplicationContext(),"picture taken",Toast.LENGTH_SHORT);
        int res=JniManager.setImage(data,m_width,m_height);
        mCamera.stopPreview();
        mCamera.startPreview();
    }
};

c++ JNI function:

    Java_pidaas_vicomtech_org_facerec_viulib_JniManager_setImage(JNIEnv *env,
                                                    jobject instance,
                                                    jbyteArray image,
                                                    jint width,
                                                    jint height)
     jbyte* _yuv  = env->GetByteArrayElements(image, 0);
     int len = env->GetArrayLength (image);
     unsigned char* buf = new unsigned char[len];
     env->GetByteArrayRegion (image, 0, len, reinterpret_cast<jbyte*>(buf));
     Mat rawData (cv::Size(width,height), CV_8UC3, buf );
            cv::Mat test =imdecode(rawData,CV_LOAD_IMAGE_COLOR);
            cv::Mat grey;
            cv::cvtColor(test, grey, cv::COLOR_BGR2GRAY);
            bool flag = imwrite("/sdcard/graypg.jpg", grey);
    env->ReleaseByteArrayElements(image, _yuv, 0);
}

I have found some answers but none of them works.

  • What format is for Android camera with raw pictureCallback?
  • How can I convert a cv::Mat to a gray scale in OpenCv?
  • opencv read jpeg image from buffer

I write image on sdcard because of testing, but it writes an empty image of 0 bytes.

So, anybody knows how do I should get jpeg pixels as gray format?

like image 630
uelordi Avatar asked Nov 09 '22 13:11

uelordi


1 Answers

Maybe the getarraylenght is not working propertly and is returning 0. I usually use lenght as width x height, parameters provided to calculate the array size. That will copy propertly the data from camera buffer to memory.

Warning: If something is wrong with the size, you will have an Signal 11 exception!

like image 115
vgonisanz Avatar answered Nov 15 '22 13:11

vgonisanz