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

3

我有一个名为 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

在上述给出的位置中,某些位置是重复的,例如:位置[1 1]。我可以使用以下代码来识别唯一的位置。
[uniquerow, ~, rowidx] = unique(a, 'rows'); 
noccurrences = accumarray(rowidx, 1);

我需要通过对图像位置值求和来更新唯一的图像位置。例如:位置[1 1]重复两次,相应的b中的值为17。因此,

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

如何在MATLAB中实现此算法而不使用for循环?


当你执行 final_img(a(:,1), a(:,2)) = final_img(a(:,1), a(:,2)) + b 时会发生什么? - Mad Physicist
@MadPhysicist:这样行不通。。 - manoos
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));

在我的情况下,final_img 是一个3x3的矩阵,但是当我使用你的建议时,我得到了一个3x2的矩阵。我该如何将其用于任何大小的final_img? - manoos

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;

2
然后使用 sub2ind 将图像转换为线性索引,然后使用 final_vals 更新这些位置。 - Cris Luengo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接