以特定顺序将图像(3D阵列)转换为2D矩阵

时间:2019-09-11 00:03:52

标签: matlab

假设您有一幅200像素的图像。这将是一个10 x 20 x 3的数组,其中页面是颜色(红色,绿色和蓝色)的层。如何将其转换为3(行)x N(例如2000列),以使每一行代表颜色(行1为红色,行2为绿色等),而列代表像素

我尝试过重塑,但是得到的是3 x N矩阵,它向下而不是水平地填充行(因此,每一行都是颜色的混合,而不是特定的颜色)。

1 个答案:

答案 0 :(得分:2)

您使用reshape的想法是正确的,但是如您所知,数组维的顺序很重要。幸运的是,您可以使用permute进行操作。因此,在您的情况下,应将“颜色信息”(即三维尺寸)设置为第一维,以使#include <iostream> #include <iomanip> int main() { std::cout << std::setprecision(0) << 12.500 << "\n"; } 正常工作。

让我们看看下面的代码片段:

reshape

为进行简单比较,我分别获取了“颜色信息”,请参见。向量% Set up dimensions rows = 10; cols = 20; % Generate artificial image img = uint8(255 * rand(rows, cols, 3)); % Get color independently for each channel r = reshape(img(:, :, 1), 1, rows * cols); g = reshape(img(:, :, 2), 1, rows * cols); b = reshape(img(:, :, 3), 1, rows * cols); % Reshape image with previous dimension permuting img2 = reshape(permute(img, [3 1 2]), 3, rows * cols); % Compare results rOK = (sum(r == img2(1, :)) == rows * cols) gOK = (sum(g == img2(2, :)) == rows * cols) bOK = (sum(b == img2(3, :)) == rows * cols) rg。然后,如上所述,对原始b进行排列,根据需要将其重塑为img矩阵,并将每行与3 x Nrg进行比较。

希望有帮助!