#30 Passing arrays via JNI, Java to Matlab

closed
None
5
2010-11-23
2010-11-23
Leo Pape
No

I found that the Java interface (with SWIG) to YARP is very slow for image transfer. This is because SWIG only allows for direct access to primitives, not arrays. The current solution is to treat an image as a collection of pixels, where each pixel is a Java object. Transferring a simple 320x240-pixel image from YARP through the Java Native Interface (JNI) to Java is very slow, and can take up to 1 second.
It would be better to directly pass arrays through the JNI, but for this, one needs to change the SWIG configuration file <yarp.i> below "IFDEF SWIGJAVA" with:

%include "carrays.i"
%array_class(unsigned char, charArray);

This will create some helper functions for passing arrays. Now you can access images in Matlab using the following Java method (not sure whether this counts as a patch, since it adds new functionality, so I just post the code):

/** converts color YARP image into a vector.
* Returns a [H*W*P] vector which contains the 'justaposition' of the
* three color planes of the image. This array can be copied into a
* Matlab matrix:
* From OUT you can create a Matlab image [HxWxP] by typing:
* IMG = reshape(uint8(OUT), [H W P]);
*/
public static short[] getRawImg(Image img)
{
int pixelsize = img.getPixelSize();
int width = img.width();
int height = img.height();
int imgsize = img.getRawImageSize();
short [] vec1ds = new short [imgsize];

charArray car = charArray.frompointer(img.getRawImage());

// in MATLAB, USE: reshape(OUT, [height width pixelsize]);
for(int r=0; r<height; r++)
for(int c=0; c<width; c++)
for(int p=0; p<pixelsize; p++)
vec1ds[(c * height) + r + (p * width * height)] = (short) car.getitem((r * width * pixelsize) + (c * pixelsize) + p);
return vec1ds;
}

Of course this example can easily be extended to other types of arrays.

Discussion

  • Paul Fitzpatrick

    • assigned_to: nobody --> eshuy
    • status: open --> closed
     
  • Paul Fitzpatrick

    Committed, thanks! If you come up with any other optimizations, please do send them along :-)

     

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks