8邻域元素的设计特征矩阵

问题描述 投票:0回答:1

我有一个大小为m x n的矩阵(图像),我试图以不同的方式重新排列。我想设计一个大小为(m x n)x 9的特征矩阵,其中每一行对应一个以其8个邻域元素为中心的矩阵元素。我的尝试是依次循环遍历原始矩阵的每个元素以提取邻域值,但是此方法在计算上过于繁琐,并且由于矩阵大小非常大而执行起来所需的时间太长。反正有成本效益地做到这一点吗?

尝试

M_feat = nan(size(img,1)*size(img,2), 9);
temp = zeros(size(img)+2);
temp(2:end-1,2:end-1) = double(img);

for i = 2:size(img,1)+1

    for j = 2:size(img,2)+1

         neighbors = temp(i-1:i+1, j-1:j+1); % read 3-by-3 mini-matrix
         neighbors = reshape(neighbors, 1, []);
         M_feat((i-2)*size(img,1) + (j-1),:) = neighbors; % store row-wise

    end

end
matlab matrix image-manipulation neighbours
1个回答
0
投票

知道了!

new_img = zeros(size(img)+2);
new_img(2:end-1,2:end-1) = double(img);

% Image boundary coordinates without first/last row/column
inner_coord = [2 2; size(new_img,1)-1 size(new_img,2)-1];

% 9x2 matrix with 1 row for the relative shift to reach neighbors
[d2, d1] = meshgrid(-1:1, -1:1);
d = [d1(:) d2(:)];

% Cell array to store all 9 shifted images
temp = {};

for i = 1:size(d,1)
    % x-indices of the submatrix when shifted by d(i,1)
    coord_x = (inner_coord(1,1):inner_coord(2,1)) + d(i,1);
    % y-indices of the submatrix when shifted by d(i,2)
    coord_y = (inner_coord(1,2):inner_coord(2,2)) + d(i,2);
    % image matrix resulting from shift by d(i,)
    temp{i} = reshape(new_img(coord_x, coord_y), 1, []);
end

% Column-wise bind all 9 shifted images (as vectors) from the array
M_feat = vertcat(temp{:}).';
© www.soinside.com 2019 - 2024. All rights reserved.