如何通过在MATLAB中识别唯一位置来更新图像值?

问题描述 投票:3回答:2

我有一个名为final_img的图像矩阵。我有图像位置矩阵,行和列如下

a =

     1     1
     1     2
     2     1
     2     2
     3     1
     3     2
     1     1
     2     2

和这些位置的价值是

b =

     1
     2
     3
     4
     5
     6
     7
     8

在上面给出的位置,有些正在重复,例如:location [1 1]。我可以使用以下代码识别唯一的位置

[uniquerow, ~, rowidx] = unique(a, 'rows'); 
noccurrences = accumarray(rowidx, 1);

我需要通过对图像位置值求和来更新唯一的图像位置。例如:位置[1 1]重复twiceb中的相应值是17。所以

final_img(1,1)应该是1+7=8;

如何在不使用for循环的情况下在MATLAB中实现此算法?

matlab
2个回答
4
投票

您可以使用sparse函数,该函数会自动添加与相同坐标对应的所有值:

final_img = full(sparse(a(:,1), a(:,2), b));

这将根据输入创建尽可能小的矩阵。


如果您希望输出尽可能小,并且限制为正方形:

M = max(a(:));
final_img = full(sparse(a(:,1), a(:,2), b, M, M));

如果要指定输出的大小:

M = 3;
N = 3;
final_img = full(sparse(a(:,1), a(:,2), b, M, N));

2
投票

你非常亲密:

[final_coords, ~, rowidx] = unique(a, 'rows'); 
final_vals = accumarray(rowidx, b);

然后将其转换为图像形式:

% empty matrix with size of your image
final_img = zeros(max(final_coords,[],1));
% get linear indexes from coordinates
ind = sub2ind(size(final_img), final_coords(:,1), final_coords(:,2));
% fill image
final_img(ind) = final_vals;
© www.soinside.com 2019 - 2024. All rights reserved.