Showing posts with label reshape. Show all posts
Showing posts with label reshape. Show all posts

Tuesday, February 06, 2007

MATLAB: reshape 3D matrix to 2D

Suppose we have an RGB image f whose size is M*N*3, now the problem is to reshape it into a 2D matrix of MN*3 elements, in which each column corresponds to R, G or B plane.

Here is a solution I saw in a master thesis on image retrieval (variable names changed):

R =f (:,:,1);% take all of the first element
G =f (:,:,2);
B =f (:,:,3);
R =R(1:end);%make it into one column matrix
G =G(1:end);
B =B(1:end);
%concentrate these R,G,B into a single 3 dimensional matrix
imf =[R;G;B];
imf =imf';

It looks like that the author made a detour. A simple solution to this problem is

imf= reshape(f, M*N, 3);

If the function 'reshape' is not used, their code can be improved as follows:

R =R(:);%make it into one vector matrix
G =G(:);
B =B(:);
%concentrate these R,G,B into a single 3 dimensional matrix
imf =[R,G,B];

Chinese version:

MATLAB: 转换三维矩阵到二维

http://time360.blogspot.com/2007/05/matlab.html