Ask Your Question

Revision history [back]

Modifying pixels efficiently in Java

There are a series of topics covering how to efficiently modify pixels in Java:

http://answers.opencv.org/question/5/how-to-get-and-modify-the-pixel-of-mat-in-java/ http://answers.opencv.org/question/20638/best-way-to-access-pixel-value-from-a-single/ http://answers.opencv.org/question/14961/using-get-and-put-to-access-pixel-values-in-java/

These threads suggest copying the Mat image to a temporary array (byte[]), working with the array, and copying back the array to the image. But that has the additional cost of copying the image twice (img to array, array to img). That can impact the performance if a lot of processing steps are required, especially if we need to mix OpenCV functions and custom processing.

In the JavaCV wrapper, there is the possibility of accessing directly the image pixels using java.nio.ByteBuffers:

https://groups.google.com/forum/#!searchin/javacv/bytebuffer$20pixel/javacv/14EPaKP__cM/oDqDs2Hte_kJ

Would it be possible in OpenCV to create a ByteBuffer that points to the data of the image? I was considering something like this

    ByteBuffer mybb = ByteBuffer.wrap(new MatOfByte(myMat).toArray());

but I am afraid MatOfByte.toArray() will create a copy of the image anyway, instead of returning the original data.

ByteBuffer requires a byte[] for its constructor, so Mat.dataAddr() does not work.