2

我有一个名为 A 的 m×n 矩阵,其值为 1s 和 0s。如果 8 个相邻像素中至少有 5 个是 1,我想将所有 0 值转换为 1。我尝试的是使用该nlfilter功能,但我不知道fun应该如何使用 arg,我需要帮助。我创建了一个函数作为句柄,nlfilter如下所示:

function b = gap_fill(A)
b=A;
index= A([1 2 3 4 6 7 8 9]);
if sum(index)>=5
b(5)= 1
end
end

然后我尝试这样做:

B= nlfilter(A,[3 3],@gap_fill)

但它给出了这个错误:

??? Subscripted assignment dimension mismatch.

Error in ==> nlfilter at 75
    b(i,j) = feval(fun,x,params{:});

有什么建议吗?主要问题是我不习惯处理函数。

= 更新 =

我终于想出了一个好结果。我将函数更改为输出标量,当我将其用作funarg 时,nlfilter它按我想要的方式工作。这是我的代码,感谢您的帮助,我希望它对任何人都有用:

function b = gap_fill(A)
index= A([1 2 3 4 6 7 8 9]);
if sum(index)>=5
A(5)= 1;
end
b=A(5);
end

在 MATLAB 中:

b= nlfilter (A,[3 3],'gap_fill')
4

4 回答 4

3

您可以在一行中完成blockproc

B = blockproc(A,[1 1],@(x)sum(x.data(:)),'BorderSize',[1 1],'TrimBorder',0)-A>=5;

例如,

A =

     1     0     1     1     0
     0     0     0     1     1
     1     1     1     1     1
     0     1     0     1     1

给出结果

B =

     0     0     0     0     0
     0     1     1     1     0
     0     0     1     1     1
     0     0     1     0     0

请注意,由于使用'BorderSize'blockproc.

要将原始的保留在 中A,请应用最终的“或”操作:

B = B|A;
于 2014-01-27T17:52:51.043 回答
2

我认为这是因为文档nlfilter说用户函数必须返回一个标量,而您正试图返回一个矩阵。

B = nlfilter(A, [m n], fun) applies the function fun to each m-by-n sliding block 
of the grayscale image A. fun is a function that accepts an m-by-n matrix as input
and returns a scalar (!!!) result.
于 2014-01-27T17:44:40.043 回答
1

对于比 略快的解决方案blockproc,您可以使用 2D 卷积:

mask = ones(3);
mask(5) = 0;
B = conv2(A,mask,'same') >= 5;

为了使这更快(如果数组变大,您只会注意到这一点),您可以利用平均过滤器可分离的事实:

B = conv2(conv2(A,ones(1,3),'same'),ones(3,1),'same') - A >= 5;
于 2014-01-27T20:10:57.473 回答
0

在您返回矩阵的情况下,有趣的函数必须返回一个标量。来自matlab

B = nlfilter(A, [mn], fun) 将函数 fun 应用于灰度图像 A 的每个 m×n 滑动块。 fun 是一个接受 m×n 矩阵作为输入并返回标量的函数结果。

c = fun(x)

所以你的代码应该有更好的编码方法,特别是使用 amtrix 但遵循你的示例:

function b = gap_fill(A)
index= A([1 2 3 4 6 7 8 9]);
if A(5)sum(index)>=5
    b = 1;
else
    b = A(5);
end
end

抱歉,我将 b = 0 更改为 b= A(5)

于 2014-01-27T18:02:15.717 回答