Matlab快速邻域操作 [英] Matlab fast neighborhood operation

查看:865
本文介绍了Matlab快速邻域操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题。我有一个Matrix A ,整数值在0到5之间。
例如:

pre $ $ $ c> x = randi(5,10,10)

现在我想调用一个过滤器,size 3x3,这给了我最常见的价值

我试过2个解决方案:

  fun = @(z)mode(z(:)); 
y1 = nlfilter(x,[3 3],fun);

需要很长时间...

  y2 = colfilt(x,[3 3],'sliding',@ mode); 

这也需要很长时间。
我有一些非常大的矩阵,这两个解决方案都需要很长时间。
有没有更快的方法?

解决方案

+1给@弗洛里斯的极好的建议使用 hist 。速度非常快尽管如此,你可以做得更好一些。 hist 基于 histc ,这可以用来代替。 histc 是一个已编译的函数,也就是说,不是用Matlab编写的,这就是为什么解决方案要快得多。这里有一个小函数,试图概括@Floris所做的(也是该解决方案返回的是一个向量而不是所需的矩阵),并通过 nlfilter colfilt 。它不要求输入具有特定的尺寸,并使用 im2col 来有效地重新排列数据。事实上,前三行以及对 im2col 的调用与你的情况下的 colfit 不一样。

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
aa(ma + nhood(1)-1,na + nhood(2)-1)= 0; (1楼 - (1)-1)/ 2)+(1:ma),floor((nhood(2)-1)/ 2)+(1:na))= a;
[〜,a(:)] = max(histc(im2col(aa,nhood,'sliding'),min(a(:)) - 1:max(a(:))));
a = a-1;

用法:

  x = randi(5,10,10); 
y3 = intmodefilt(x,[3 3]);

对于大型数组,这比 colfilt 在我的机器上。用 histc 替换 hist 负责两倍加速。当然没有输入检查,所以函数假定 a 都是整数等等。



最后,那 randi(IMAX,N,N) 返回值范围 1:IMAX ,而不是 0:IMAX 状态。


I have a Problem. I have a Matrix A with integer values between 0 and 5. for example like:

x=randi(5,10,10)

Now I want to call a filter, size 3x3, which gives me the the most common value

I have tried 2 solutions:

fun = @(z) mode(z(:));
y1 = nlfilter(x,[3 3],fun);

which takes very long...

and

y2 = colfilt(x,[3 3],'sliding',@mode);

which also takes long. I have some really big matrices and both solutions take a long time. Is there any faster way?

解决方案

+1 to @Floris for the excellent suggestion to use hist. It's very fast. You can do a bit better though. hist is based on histc, which can be used instead. histc is a compiled function, i.e., not written in Matlab, which is why the solution is much faster.

Here's a small function that attempts to generalize what @Floris did (also that solution returns a vector rather than the desired matrix) and achieve what you're doing with nlfilter and colfilt. It doesn't require that the input have particular dimensions and uses im2col to efficiently rearrange the data. In fact, the the first three lines and the call to im2col are virtually identical to what colfit does in your case.

function a=intmodefilt(a,nhood)
[ma,na] = size(a);
aa(ma+nhood(1)-1,na+nhood(2)-1) = 0;
aa(floor((nhood(1)-1)/2)+(1:ma),floor((nhood(2)-1)/2)+(1:na)) = a;
[~,a(:)] = max(histc(im2col(aa,nhood,'sliding'),min(a(:))-1:max(a(:))));
a = a-1;

Usage:

x = randi(5,10,10);
y3 = intmodefilt(x,[3 3]);

For large arrays, this is over 75 times faster than colfilt on my machine. Replacing hist with histc is responsible for a factor of two speedup. There is of course no input checking so the function assumes that a is all integers, etc.

Lastly, note that randi(IMAX,N,N) returns values in the range 1:IMAX, not 0:IMAX as you seem to state.

这篇关于Matlab快速邻域操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆