将长垂直 RGB 图像阵列重塑为 Octave 中的分层水平部分

Reshaping long vertical RGB image array into layered horizontal sections in Octave

我正在尝试将长的垂直图像阵列(多维 RGB 阵列)重塑为 Octave 中的分层水平部分。

我有一个很长的垂直图像阵列 (32734x1x3)。 我如何重塑图像阵列,以便我 长垂直图像转换为 52x640x3 的分层水平图像阵列,同时填充阵列的其余部分加入 0 使其成为“正方形”

我正在查看 reshape,但无法弄清楚如何在创建分层水平部分的同时在多个维度上重塑数组。

简单示例:数组中剩余的space用零填充。

我的 logic/test 是:

a=[1:32734]';

num_cols_wanted=640
num_of_rows_calc=ceil(size(a,1)/num_cols_wanted) %use ceil to get whole number rounded up
num_cells_to_add=mod(size(a,1),num_cols_wanted) %extra cells needed to even array out

b = zeros(num_of_rows_calc, num_cols_wanted); %preallocate 

b=reshape(a,[num_of_rows_calc,num_cols_wanted]); %place reshaped a array into preallocated b array

在测试脚本的末尾,我在将原始 array a 重塑为更大的预分配 array b 时遇到了问题。我得到一个错误 can't reshape 32734x1

PS:我正在使用 Octave 5.2

使用 reshape 时,输入元素的数量必须等于输出(整形)元素的数量。

在您的情况下:length(a) 必须等于 num_of_rows_calc*num_cols_wanted


执行b = zeros(...)然后b = reshape(...)只是覆盖b的值(填充b 带零没有帮助)。


  • 您可以用零填充 b(创建一个“长”向量),然后将 a 个元素复制到 a 的开头:

     b = zeros(num_of_rows_calc*num_cols_wanted, 1);
     b(1:length(a)) = a;
    
  • b 具有正确数量的元素后,我们可以重塑 b:

      b = reshape(b, [num_cols_wanted, num_of_rows_calc])';
    

    注意: 在 OCTAVE 中重塑向量首先按列(从上到下)排列元素。
    对于按行排序,我们可能会重新整形为 cols x 行并转置结果。


完整代码示例:

%a=[1:32734]';
a = (1:10)';

num_cols_wanted=3; %640;
num_of_rows_calc=ceil(size(a,1)/num_cols_wanted); %use ceil to get whole number rounded up
num_cells_to_add=mod(size(a,1),num_cols_wanted); %extra cells needed to even array out

b = zeros(num_of_rows_calc*num_cols_wanted, 1); %Create a vector of zeros with desired number of elements.

b(1:length(a)) = a; %Copy a into the b - keeping the zeros at the end of b (we could also add zero padding at the end of a).

%Reshape to num_cols_wanted x num_of_rows_calc and transpose, because OCTAVE ordering is "column major".
b = reshape(b, [num_cols_wanted, num_of_rows_calc])'; %reshape b array into preallocated b array

结果:

b =

    1    2    3
    4    5    6
    7    8    9
   10    0    0

3D 输出示例:

a = cat(3, (1:10)', (21:30)', (31:40)');

a = squeeze(a); % Remove redunded dimentsion

num_cols_wanted=4;%640;
num_of_rows_calc=ceil(size(a,1)/num_cols_wanted); %use ceil to get whole number rounded up
num_cells_to_add=mod(size(a,1),num_cols_wanted); %extra cells needed to even array out

b = zeros(num_of_rows_calc*num_cols_wanted, 3); %Create 3 columns matrix of zeros with desired number of elements.

b(1:length(a), :) = a; %Copy a into the b - keeping the zeros at the end of b (we could also add zero padding at the end of a).

%Reshape to 3 x num_cols_wanted x num_of_rows_calc and permute, because OCTAVE ordering is "column major".
b = reshape(b, [num_cols_wanted, num_of_rows_calc, 3]); %reshape b array into preallocated b array
b = permute(b, [2, 1, 3]);