MATLAB Answers

0

How can I convert a "Java Image" object into a MATLAB image matrix?

The IM2JAVA function is available for converting a MATLAB image into a Java image. I would like to convert a Java image to a MATLAB image.

1 Answer

Answer by MathWorks Support Team on 30 Jan 2011
 Accepted Answer

There is no built-in function to convert Java images into MATLAB images. However using the Java API you can extract the data from a Java image and store it as a matrix, which is MATLAB's image representation.
Below is an example of converting a MATLAB image to Java and back to a MATLAB image. The image used in this example is part of the MATLAB demos and is on the MATLAB path. In this example, the "getPixels" function of the Java class "Raster" returns the RGB values for the image.
Depending upon the format of your Java image, additional work may be required. Java images can be stored in one of many formats; the "getPixels" function returns the pixel data in that format. For more information, see the javadoc page for the java.awt.image.Raster class at
<http://java.sun.com/j2se/1.5.0/docs/api/java/awt/image/Raster.html>
% create java image
I = imread('office_3.jpg');
javaImage = im2java(I);
% get image properties
H=javaImage.getHeight;
W=javaImage.getWidth;
% repackage as a 3D array (MATLAB image format)
B = uint8(zeros([H,W,3]));
pixelsData = uint8(javaImage.getBufferedImage.getData.getPixels(0,0,W,H,[]));
for i = 1 : H
base = (i-1)*W*3+1;
B(i,1:W,:) = deal(reshape(pixelsData(base:(base+3*W-1)),3,W)');
end
% display image
imshow(B);
The following are two other ways to implement this (in a more optimized manner):
Example 1: (Faster execution)
pixelsData = reshape(typecast(jImage.getData.getDataStorage, 'uint8'), 4, w, h);
imgData = cat(3, ...
        transpose(reshape(pixelsData(3, :, :), w, h)), ...
        transpose(reshape(pixelsData(2, :, :), w, h)), ...
        transpose(reshape(pixelsData(1, :, :), w, h)));
Example 2:
imgData = zeros([H,W,3],'uint8');
pixelsData = reshape(typecast(javaImage.getBufferedImage.getData.getDataStorage,'uint32'),W,H).';
imgData(:,:,3) = bitshift(bitand(pixelsData,256^1-1),-8*0);
imgData(:,:,2) = bitshift(bitand(pixelsData,256^2-1),-8*1);
imgData(:,:,1) = bitshift(bitand(pixelsData,256^3-1),-8*2);

  2 Comments

Image is not same as it is seen in pdf/buffer image
Hi Rajnikant,
I would suggest contacting Mathworks Technical Support if you are facing issues while using the above script to convert a Java image object to a MATLAB image matrix.

Sign in to comment.