2

The intention is to estimate in a [3 3] sliding window. 0.5*[(A(i)-A(5))^2] is computed where a(i) is the pixels around center pixel a(5).

The mean of each of these 8 half square differences is stored in the center pixel's location.

To tackle this conv2 and nlfilter were used on a training example matrix as follows.

clc;
close all;
clear all;
A = [1 2 3 4 5 6;5 4 6 3 2 1;2 3 2 1 4 5];
kernel = [-1 -1 -1; -1 8 -1; -1 -1 -1];
outputImage = conv2(A, kernel);
fun = @(x) mean(x(:));
B= nlfilter (outputImage,[3 3],fun);

The initial idea was to calculate the difference and store it in the location of the pixels instead of the center pixel. Then use a sliding window to take mean of those differences and replace the center pixel.

It was apparent that my logic was flawed.

Though i was able to calculate the difference(i first tried to see simple difference was possible for me) i had to deal with data being overwritten. moreover this method will create a matrix larger than the original which is also wrong.

Bharath S
  • 161
  • 1
  • 12

1 Answers1

2

the function mean and the kernel you are using are both linear and do not represent the non-linear operation you are trying to achieve.

One way of using conv and mean is by computing the 8 differences as different output channels

ker = cell(1,8);
for ii=1:8
    ker{ii} = zeros(3);
    ker{ii}(2,2) = 1; %// for a(5)
    if ii < 5
       ker{ii}(ii) = -1; 
    else
       ker{ii}(ii+1) = -1; 
    end
 end
 interim = zeros( [size(A,1) size(A,2), numel(ker)] ); % allocate room for intermidiate results
 for ii=1:numel(ker)
     interim(:,:,ii) = conv2(A, ker{ii}, 'same' ); %//'same' takes care of output size for you
 end

Now interim holds each of the different a(5)-a(i) we are ready for the non-linear operation

 interim = interim.^2;
 B = 0.5 * interim;
Shai
  • 111,146
  • 38
  • 238
  • 371
  • Thank you! I did not consider using an interim variable to hold data in separate planes. I do have a follow up question if i may though the non linearity was addressed the mean of the half square differences should replace the center pixels. Since the kernels compute single differences in each plane doesn't indexing to replace center pixels with the mean become much more complicated? – Bharath S Mar 30 '15 at 13:14
  • @BharathS if you only want to replace `a(5)` with the sum over all `i`: `0.5*( a(5)- a(i) )^2` then `B = sum(interim,3);` and that's it ! – Shai Mar 30 '15 at 13:56
  • 1
    Thank you! Wish i could up vote but new to the website. – Bharath S Mar 30 '15 at 14:14
  • @BharathS glad I could help. keep participating and soon you'll be able to upvote! – Shai Mar 30 '15 at 14:20