Only mask elements of some value with conv2

2 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Matt J
Matt J il 6 Ott 2014
Modificato: Matt J il 6 Ott 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.

Più risposte (0)

Categorie

Scopri di più su Migrate GUIDE Apps in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by