0

I have a double image and my aim is to convert it to logical. I want to create 5x5 window and put it on each pixel in the image. Then, I calculate the average of these 25 pixels. If the center pixel value is greater then the average value, it will be 1. Otherwise 0.

How can I do that?

P.S. I don't want to do that this way:

IM[i - 2, j - 2]
IM[i - 1, j - 2]
IM[i, j - 2]
IM[i + 1, j - 2]
IM[i + 2, j - 2]
      .
      .
ffttyy
  • 853
  • 2
  • 19
  • 49

2 Answers2

1

Several approaches (running time is probably in decreasing order):

  1. With nlfilter:

    result = nlfilter(im, [5 5], @(x) x(3,3)>mean(x(:)));
    
  2. With blockproc:

    result = blockproc(im, [1 1], @(x) x.data(3,3)>mean(x.data(:)), ...
        'Bordersize', [2 2], 'Trimborder', 0);
    

    Note that with blockproc we need to specify blocks of size 1x1 (so that the block "moves" from pixel to pixel in each direction), border of size 2 in eacch direction around wach pixel (to get 5x5 blocks), and prevent the function result from being trimned, because the result is just 1 value.

  3. With conv2:

    result = im > conv2(im, ones(5,5)/25, 'same');
    
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Finally using it! Nice. – Divakar Dec 06 '14 at 17:08
  • Yep! My second answer with `nlfilter` :-D – Luis Mendo Dec 06 '14 at 17:09
  • Which one's the first? – Divakar Dec 06 '14 at 17:10
  • It's [this one](http://stackoverflow.com/a/27325226/2586922). Admittedly a not very natural use of `nlfilter` – Luis Mendo Dec 06 '14 at 17:15
  • All of them work quite good but I have a question. I don't understand the 3rd method. You create a 5*5 matrix full of ones but I can't understand how this matrix can be our window? – ffttyy Dec 06 '14 at 17:33
  • hehe, nice to see other `nfilter`users :-) http://stackoverflow.com/a/22818561/2777181 – Cape Code Dec 06 '14 at 17:40
  • @sigara The 3rd method uses 2D-[convolution](http://en.wikipedia.org/wiki/Convolution). It applies a mask (the 5x5 constant matrix) around each pixel and sums the product of pixel values times mask. The mask values are chosen such that the convolution result is the mean – Luis Mendo Dec 06 '14 at 18:54
0

If I am right, it seems like a outlier method. The code below may be what you wanted:

mask   = 0.04 * ones(5); mask(3, 3) = 0; % // mask is for average the double image
avgIm  = filter2(mask, imd); % // imd is your double image.
output = imd > avgIm;
mehmet
  • 1,631
  • 16
  • 21
  • In this code I am calculating average value of all neighbour (24 pixel except current pixel). You can comment out the part "mask(3, 3) = 0;" – mehmet Dec 06 '14 at 17:13