Opencv C ++ creates Mat object from nvidia android image data buffer

I have implemented an Android application that launches the camera and sends the entire preview buffer to its own components using the JNI interface. Since the preview data is in NV21 image format, I need to create a cv :: Mat instance from it. I searched for it and found the following solution:

cv::Mat _yuv(height, width, CV_8UC1, (uchar *) imagebuffer); where imagebuffer is jbyte* 

However, do not get the expected image in the output image. All of this is filled with some random lines, etc. Does anyone know how exactly I can do this?

+6
source share
2 answers

You need to convert the YUV image to the RGBA image.

 cv::Mat _yuv(height+height/2, width, CV_8UC1, (uchar *)imagebuffer); cv::cvtColor(_yuv, _yuv, CV_YUV2RGBA_NV21); 

Typically, YUV images are 1 channel images with 1.5*height (if it was an RGB or grayscale image).

Or you can create a new Mat and pass jint array for the built-in function and use this array to set the pixels of the bitmap.

 jint *_out = env->GetIntArrayElements(out, 0); cv::Mat _yuv(height + height/2, width, CV_8UC1, (uchar*)imagebuffer); cv::Mat _rgba(height, width, CV_8UC4, (uchar *)_out); cv::cvtColor(_yuv, _rgba, CV_YUV2RGBA_NV21); env->ReleaseIntArrayElements(out, _out, 0); 

In Java,

 bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); pixels = new int[width * height]; native_function(height, width, bytedata, pixels); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); 
+13
source

The 1st answer may not work as the correct color image. this code is my answer.

  cv::Mat yuv(height+height/2, width, CV_8UC1,(uchar *)nv21ImageBuffer); cv::Mat converted(height, width, CV_8UC3); cv::cvtColor(yuv, converted, CV_YUV2BGR_NV21); cv::imwrite("anywhere/colorImage.jpg",converted); 
0
source

All Articles