Is there an efficient and fast way to process pixel neighborhoods without loops?

4 ビュー (過去 30 日間)
Ahmed Elazab
Ahmed Elazab 2016 年 1 月 26 日
回答済み: Tony Richardson 2020 年 7 月 13 日
Hi all, I am looking for an efficient and fast way to process local window without loops. I want to apply a nonlinear operation on the local neighborhood with an exponential function. The output of this operation is not a scalar rather than being a weight for ever pixel in the neighborhoods. Later, I use these weights to calculate the final value of the central pixel. Here is a code snippet of what I did:
for i=1:r
for j=1:c
x=i:i+wsize-1; y=j:j+wsize-1 % wsize=3 (the window size)
if(max(x)>r || (max(y)>c))
break
end
Win=im1(x,y); Win=Win(:);
C=im2(x,y); C=C(:); % current window of size wsize
avgC=mean(C);
Gij=exp(-(C-(avgC(i,j)))./C);
Wij=(G_ij)./sum(G_ij);
im3(i,j)=sum(Win.*Wij);
end
end
Note: im1 and im2 are different while the desired output will be in im3.

回答 (2 件)

Image Analyst
Image Analyst 2016 年 1 月 26 日
There is a function called nlfilter() that can apply your custom function to a moving neighborhood. I attach a demo.
  2 件のコメント
Ahmed Elazab
Ahmed Elazab 2016 年 1 月 26 日
Dear Image Analyst, Thanks so much for reply. I tried to use nlfilter function before but it is much slower than using the code above.
Image Analyst
Image Analyst 2016 年 1 月 26 日
Just get rid of the loops and vectorize it. Use conv2() or imfilter().

サインインしてコメントする。


Tony Richardson
Tony Richardson 2020 年 7 月 13 日
I've written up a brief description (see the url below) of a fairly straight-forward method that I've found to be much faster that nlfilter. It does not use loops (vectorized) and still easily allows for non-linear processing of neighborhoods (for example - median processing). (nlfilter allows non-linear processing, but conv2 and imfilter do not.)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by