How can I convert a "Java Image" object into a MATLAB image matrix?
조회 수: 14 (최근 30일)
이전 댓글 표시
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.
채택된 답변
MathWorks Support Team
2011년 1월 30일
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);
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Convert Image Type에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!