【发布时间】:2017-02-12 00:22:41
【问题描述】:
我正在计算每个前景像素到背景像素的最短距离。我尝试了一些选项,但没有按我的预期工作(有一个内置的 Matlab 函数 'bwdist' 给出了该像素和最近的非零像素之间的距离。但我正在创建自己的一个来给出 1 之间的距离-pixel 和最接近的零像素。)这是我拥有的版本之一。
说'Im'是10x10像素的原始矩阵(它是随机创建的。实际矩阵比这个大得多。)
Im =
0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 0 0
0 0 0 1 1 1 1 1 0
0 0 1 0 1 1 1 1 1
0 0 1 1 1 1 1 1 1
0 0 0 1 1 1 1 1 0
0 0 0 0 1 1 1 1 0
0 0 0 0 1 1 1 1 0
0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 0
DT = Im;%create a copy matrix of Im
for i = 1: size(DT,1)
for j = 1: size(DT,2)
%I want to select all pixels with a distance of 1 to current pixel
%(i,j), e.g. (i-1,j), (i,j-1), (i+1,j),(i,j+1) would be the case for Euclidean
%distance. The large size of matrix (say 512x512) also makes it very inefficient
%use four for-loops to find these pixels with distance of 1 to current pixel. So
%I use (i-1,j) etc instead of using
%sqrt(sum(bsxfun(@minus,[u v],[i j]).^2,2))
%to find out all (u,v)s with distance of 1 to current pixel (i,j).
%But I do believe there are thousands smart ways to make this work efficiently.
if (Im(i-1,j) == 0 || Im(i,j-1) == 0 || Im(i,j+1) == 0 || Im(i+1,j) == 0)%I want to mark all pixels with 0 to remain as 0
DT(i-1,j) = Im(i-1,j);
DT(i,j-1) = Im(i-1,j);
DT(i,j+1) = Im(i,j+1);
DT(i+1,j) = Im(i+1,j);
else
%I want to update the visited pixels with the minimum value
%of calculated distances. Apparently, here is my problem. The code is not correct.
DT(i-1,j) = min(DT(i-1,j),Im(i-1,j) + DT(i,j));
DT(i,j-1) = min(DT(i,j-1),Im(i,j-1) + DT(i,j));
DT(i,j+1) = Im(i,j+1) + DT(i,j));
DT(i+1,j) = Im(i+1,j) + DT(i,j);
end
end
end
非常感谢您提前提供的任何帮助!
【问题讨论】:
-
bwdist(1-Im)怎么样? -
它使用 bwdist(~Im) 工作。但我正在玩,看看上面的代码是否可以以同样的方式工作。
标签: matlab matrix transform distance pixels