2007年5月17日星期四

MATLAB: 转换三维矩阵到二维

假设我们有一幅 RGB 图像,矩阵大小是M*N*3。 现在的问题是转换三维矩阵到二维维 (大小MN*3,每一列对应一个平面 R,G,B)。

这里有一段代码,是从一篇硕士论文上复制来的 (变量名字已经改变):

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

其实这段代码冗长,可以简写为

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

如果不使用函数 'reshape' , 代码同样可以改进:

R =R(:);%make it into one vector matrix
G =G(:);
B =B(:);
imf =[R,G,B];

英文版:

MATLAB: reshape 3D matrix to 2D

http://nw360.blogspot.com/2007/02/matlab-reshape-3d-matrix-to-2d.html

没有评论: