Only mask elements of some value with conv2

5 views (last 30 days)
I want to use convolution, or something like convolution, to perform sum over neighboring elements. So normally I could use
x=zeros(20,20);
r=randi(1000,size(x));
mask=[ 0 0 1 1 1 0 0
0 1 1 1 1 1 0
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
0 1 1 1 1 1 0
0 0 1 1 1 0 0];
myconv=conv2(r,mask);
However, I only want the mask to add elements with the same value as the reference element (center of the mask). How can this be done? Thanks!
Note: this would be easy if there were only a few possible values, but I want it to work for many possible values in the matrix r.

Accepted Answer

Matt J
Matt J on 6 Oct 2014
Edited: Matt J on 6 Oct 2014
How about this?
[N,N]=size(mask);
vals=im2col(r,[N,N],'sliding');
ref=vals((N^2+1)/2, :); %assumes odd-dimensions of mask
result=mask(:).' * (vals.*bsxfun(@eq,vals, ref ));
result=reshape(result,size(r)-N+1);
It's a modification of conv2(...'valid'). If you wanted conv2(...,'full'), you would simply have to pre-pad r with zeros.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!