## 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

1. Didn't you mean:

R =f (:,:,1);% take all of the first element
G =f (:,:,2);
B =f (:,:,3);

2. go help SQUEEZE

3. SQUEEZE is a function provided by MATLAB and can do the trick. But if you look at the code of squeeze, it uses reshape function.

4. I need to change a 3D image into 2D. However the image should stay as coloured, not gray. Because I need to generate the histogram; and imhist() only works on 2D coloured image.

Thank you

5. khi

6. If u did the transformation 3D image to 2D , please tell me how u did it ??

bcoz I also want to do it transformation ??

i am not good in matlab graphics

7. how can i converted an iamge back to rgb when i have extracted all the three component from it .... can it b reshape

8. f (:,:,1) =R;
f (:,:,2) =G;
f (:,:,3) =B;

9. Hi guys , i would first of all like to say thank you for your code and assistance .
however when using reshape ,the conversion operation goes on normally but when i go for "imshow" , to display the image after conversion , nothing besides a straight line appears .... Same goes when i apply "histeq" to the newly converted 2D image .
pls help , ...

1. Hi Wenbin
Thx for your reply , but all i got after applying the following
/