4

On Android , I use MediaCodec to create mp4 video file from captured images.

I am getting the OpenCV Mat data using

Image i = reader.acquireLatestImage();
ByteBuffer byteBuffer = i.getPlanes()[0].getBuffer();
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
Mat mImageGrab = Imgcodecs.imdecode(new MatOfByte(bytes), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED); <= bytes from Image object

I have checked and the bitmap images are correctly showing(with some colors wrong translation)

this is the code that tests the Bitmaps:

Mat nv21 = new Mat();
Imgproc.cvtColor(mImageGrab, nv21, Imgproc.COLOR_RGB2YUV_I420);<= NV21 is mat was created
Bitmap bmp = Bitmap.createBitmap(mImageGrab.cols(), mImageGrab.rows(), Bitmap.Config.ARGB_8888);
Mat bmpMat = new Mat();
Imgproc.cvtColor(nv21,bmpMat, Imgproc.COLOR_YUV420sp2RGB);<= transfer NV21 to Bitmap
Utils.matToBitmap(bmpMat, bmp);<= great bitmap result

However the MediaCodec mp4 expects byte array of NV21 image and not bitmap. How can I transform the Mat to NV21? or the bitmap to NV21? I want to perform some image processing to the images before sending those images to the MediaCodec.

I can also use the "encodeYUV420SP" function that was mentioned here Link to encode NV21 but it is too slow for video.

other option - render scripts - support for those supposes to be deprecated - so - I prefer not to. But I am ready to try : bitmap to NV21 render script that is androidx compatible.()

kfir
  • 635
  • 8
  • 27
  • Did you try posting on openCV platform? They can guide you better. – Haider Saleem Aug 28 '22 at 12:35
  • Consider using [sws_scale](https://www.tabnine.com/code/java/methods/org.bytedeco.javacpp.swscale/sws_scale). `sws_scale` supports conversions between most pixel formats. I know the [C interface](https://ffmpeg.org/doxygen/3.1/group__libsws.html) of `swscale`, but I don't know the JAVA interface. I don't know if there is support for Android, and I don't know the execution performance on ARM. – Rotem Sep 02 '22 at 09:13
  • Dear Rotem, thanks - but as I said , I want to get closer to 30 FPS otherwise I would have use the Java link I mentioned "EncodeYUV420SP" which is faster the then the 100 ms of the sws_scale. (the sws_scale is part of the FFmpeg which is not really real time friendly). as written in this link https://ffmpeg.org/pipermail/libav-user/2015-August/008348.html – kfir Sep 02 '22 at 09:43

0 Answers0