将不需要的值替换为最接近的恰好为正的索引值

Replacing indices with an unwanted value with their the nearest index's value that happens to be positive

本题与上一题不同()。 上一个问题是用同一行上最接近的正索引值替换索引不需要的值

这道题是在整个矩阵中(不仅限于同一行)用它最接近的正索引值替换不需要的值

例如,如果不需要负值,

[-255  4  6;
   -5 -4  5;
 -400  3  6;
   -6 -7 -8;
    3 -5  4]

变成

[4 4 6;
 4 5 5;
 3 3 6;
 3 3 6;
 3 4 4]

(答案不一定必须是这样,因为它随机取最接近的值(right/left/up/down 无论如何,如果通过增加一些一致性使事情变得更容易,那也很好。))

目的:我试图这样做是为了在不破坏图像清晰度的情况下去除观察到的图像矩阵中的大尺寸噪声孔。

感谢您的支持!

以下代码将每个负数替换为最接近的非负数。如果在相同的最小距离处有多个非负数,则使用线性顺序中的第一个

没有循环

这将构建一个非常大的矩阵作为中间结果。由于内存限制,它可能不适用于大输入。

matrix = [-255 4 6; -5 -4 5; -400 3 16; -6 -7 -8; 13 -5  14];
[r_use, c_use] = find(matrix>=0); % row and column indices of useful values
z_use = r_use+1j*c_use; % same as complex number
[r_neg, c_neg] = find(matrix<0); % row and column indices of negative values
z_neg = r_neg+1j*c_neg; % same as complex number
[~, ind_min] = min(abs(bsxfun(@minus, z_use, z_neg.')), [], 1); % compute distance
    % between each useful value and each negative value. For each negative value, 
    % give  index of nearest useful value. This index is referred to r_use, c_use
ind_use = sub2ind(size(matrix), r_use(ind_min), c_use(ind_min)); % linear indices 
    % of useful values that will replace the negative values
ind_neg = sub2ind(size(matrix), r_neg, c_neg); % linear indices of negative values
matrix(ind_neg) = matrix(ind_use); % replace

之前:

matrix =
  -255     4     6
    -5    -4     5
  -400     3    16
    -6    -7    -8
    13    -5    14

之后:

matrix =
     4     4     6
     4     4     5
     3     3    16
    13     3    16
    13    13    14

有循环

这通过使用循环一次处理一个负值来减少内存消耗。

matrix = [-255 4 6; -5 -4 5; -400 3 16; -6 -7 -8; 13 -5  14];
[r_use, c_use] = find(matrix>=0); % row and column indices of useful values
z_use = r_use+1j*c_use; % same as complex number
[r_neg, c_neg] = find(matrix<0); % row and column indices of negative values
z_neg = r_neg+1j*c_neg; % same as complex number
for k = 1:numel(z_neg) % for each negative value
    [~, ind_min_k] = min(abs(z_use-z_neg(k))); % compute distance between
    % each useful value and this negative value. Give index of nearest
    % useful value. This index is referred to r_use, c_use
    ind_use_k = sub2ind(size(matrix), r_use(ind_min_k), c_use(ind_min_k));
    % linear index of useful value that will replace this negative value
    ind_neg_k = sub2ind(size(matrix), r_neg(k), c_neg(k)); % linear index
    % of this negative value
    matrix(ind_neg_k) = matrix(ind_use_k); % replace
end

如果您有图像处理工具箱,您可以使用 bwdist 的第二个输出来找到最接近的正索引值。

matrix = [-255  4  6;
          -5   -4  5;
          -400  3  6;
          -6   -7 -8;
           3   -5  4];
bw = matrix >= 0;
[~, idx] = bwdist(bw);

result = matrix;
result(~bw) = result(idx(~bw));

结果将是:

result =
   4   4   6
   3   4   5
   3   3   6
   3   3   6
   3   3   4

这里的结果是根据euclidean距离计算的。您可以将 bwdist 与其他距离度量一起使用以产生不同的结果。