Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a Java BufferedImage into Matlab

I'm trying to call some Java methods from MATLAB and have been successful with those that return things like Strings, Files etc. But now I have a method that returns a BufferedImage, which MATLAB doesn't have a problem with YET. But how does one visualize this BufferedImage in MATLAB ? Or at least convert it into a matrix?

I called the following method (which is in my Java class) from MATLAB :

MATLAB code:

bufferedImage = pictureObject.getBufferedImage 

MATLAB shows this...

pictureObject =

BufferedImage@9d7ae3: type = 13 IndexColorModel: #pixelBits = 8 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@eee0e3 transparency = 1 transIndex = -1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 640 height = 480 #numDataElements 1 dataOff[0] = 0

And I'm trying to convert the above thing into something visualizable in MATLAB .

like image 771
Ashwin Parcha Avatar asked Apr 08 '26 07:04

Ashwin Parcha


1 Answers

For a Java BufferedImage called jbi, you can use getData and getPixels to get a MATLAB array.

Create a test BufferedImage with im2java2d (too bad there is no java2d2im):

>> I = imread('cameraman.tif');
>> jbi = im2java2d(I)
jbi =
BufferedImage@7ed666f9: type = 0 IndexColorModel: #pixelBits = 8 numCompon<snip>

Convert back:

nrows = jbi.getHeight; ncols = jbi.getWidth;
matImg = jbi.getData.getPixels(0,0,ncols,nrows,[]);
matImg = uint8(reshape(matImg,nrows,ncols)');

The above works for the grayscale "cameraman.tif" image (pixelBits = 8).


For the color "peppers.png" image (pixelBits = 24):

data = jbi.getData.getPixels(0,0,ncols,nrows,[]);
matImg = permute(reshape(data,3,ncols,nrows),[3 2 1]);

Or

data = reshape(typecast(jbi.getData.getDataStorage, 'uint8'), [], ncols, nrows);
matImg = permute(data,[3 2 1]);

See this MathWorks answer for more tricks.

like image 198
chappjc Avatar answered Apr 10 '26 21:04

chappjc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!