Only mask elements of some value with conv2

1 次查看(过去 30 天)
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.

采纳的回答

Matt J
Matt J 2014-10-6
编辑:Matt J 2014-10-6
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by