【发布时间】:2013-09-06 14:03:48
【问题描述】:
我有一个由正值和负值组成的矩阵。我需要做这些事情。
让u(i,j) 表示矩阵u 的像素。
- 计算过零像素。如果
u(i-1,j)和u(i+1,j)的符号相反,或者u(i,j-1)和u(i,j+1)的符号相反,则这些是网格中的像素。 - 然后我需要计算这些过零像素周围的窄带。每个像素的窄带宽度为
(2r+1)X(2r+1)。我正在使用r=1,因此我必须实际获取每个过零像素的 8 个邻域像素。
我已经在一个程序中做到了这一点。请看下面。
%// calculate the zero crossing pixels
front = isfront(u);
%// calculate the narrow band of around the zero crossing pixels
band = isband(u,front,1);
我还附加了isfront 和isband 函数。
function front = isfront( phi )
%// grab the size of phi
[n, m] = size(phi);
%// create an boolean matrix whose value at each pixel is 0 or 1
%// depending on whether that pixel is a front point or not
front = zeros( size(phi) );
%// A piecewise(Segmentation) linear approximation to the front is contructed by
%// checking each pixels neighbour. Do not check pixels on border.
for i = 2 : n - 1;
for j = 2 : m - 1;
if (phi(i-1,j)*phi(i+1,j)<0) || (phi(i,j-1)*phi(i,j+1)<0)
front(i,j) = 100;
else
front(i,j) = 0;
end
end
end
function band = isband(phi, front, width)
%// grab size of phi
[m, n] = size(phi);
%// width=r=1;
width = 1;
[x,y] = find(front==100);
%// create an boolean matrix whose value at each pixel is 0 or 1
%// depending on whether that pixel is a band point or not
band = zeros(m, n);
%// for each pixel in phi
for ii = 1:m
for jj = 1:n
for k = 1:size(x,1)
if (ii==x(k)) && (jj==y(k))
band(ii-1,jj-1) = 100; band(ii-1,jj) = 100; band(ii-1,jj+1) = 100;
band(ii ,jj-1) = 100; band(ii ,jj) = 100; band(ii,jj+1) = 100;
band(ii+1,jj-1) = 100; band(ii+1,jj) = 100; band(ii+1,jj+1) = 100;
end
end
end
end
输出如下:,以及计算时间:
%// Computation time
%// for isfront function
Elapsed time is 0.003413 seconds.
%// for isband function
Elapsed time is 0.026188 seconds.
当我运行代码时,我确实得到了正确的答案,但任务的计算对我来说太过分了。有更好的方法吗?特别是isband 函数?如何进一步优化我的代码?
提前致谢。
【问题讨论】:
-
你考虑过形态学运算吗,比如
bwmorph? -
注意:
isband右下角两个相邻像素的访问编码不正确;您可能复制粘贴了,忘记将 -1 更正为 +1 和 +0。 -
@RodyOldenhuis 感谢您的评论。是的,我复制并粘贴了它,所以这是一个错误。编辑我的问题以更正它。
标签: matlab optimization image-processing neighbours