Skip to Main Content Skip to Search
Home |   Select Country  Choose Country  |  Contact Us  |  Cart Store 
Create Account | Log In
Products & Services Solutions Academia Support User Community Company
spacer spacer spacer spacer spacer spacer

Technical Solutions

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


Date Last Modified: Friday, June 26, 2009
Solution ID:   1-2WPAYR
Product:   MATLAB
Reported in Release:   No Release
Platform:   All Platforms
Operating System:   All OS
 

Subject:

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

Problem Description:

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.

Solution:

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 is more optimized code (but probably less understandable):

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);

Please provide feedback to help us improve this Solution
Contact support
E-mail this page
Print this page