2
votes

I need to create a 32x32 sliding window on an image Z. I then need to check the mean intensity of each window on the image.

Can I use: n=[32,32] h = fspecial('average', n); filter2(h, img)

N = 32;
info = repmat(struct, ceil(size(Z, 1) / N), ceil(size(Z, 2) / N)); 
for row = 1:N:size(Z, 1)%loop through each pixel in the image matrix
   for col = 1:N:size(Z, 2)
     r = (row - 1) / N + 1;
     c = (col - 1) / N + 1;
     imgWindow = Z(row:min(end,row+N-1), col:min(end,col+N-1));
    average = mean(imgWindow(:)) %calculate the mean intensity of pixels within each window
   end
end

However this only creates 12x30. Can anyone spot where I have gone wrong?

2
What's that magic word struct doing alongside repmat? It may not sort out the issue at hand, but got curious about it. - Divakar
If you type size(Z), what do you get? - tashuhka
In the event that you have the image processing toolbox, you might want to use the ready made sliding filter functions it has. - Cape Code
You can also get inspiration from some of my implementations, nfilter here: stackoverflow.com/a/22987604/2777181, filter2 here: stackoverflow.com/a/22914519/2777181 - Cape Code
If it's the mean you want, look at this: stackoverflow.com/a/1738103/2777181 - Cape Code

2 Answers

2
votes

Your image is 364x350, and the window size is 32x32. What happens is this:

enter image description here

Notice in the last column the windows are 32x30, in the last row the windows are 12x32, and the last window (bottom-right) is 12x30. That's the last to be calculated, and why you're getting that value when the code stops running.

I see three options here:

  1. Fill the last column with two columns of pixels and the last row with 20 rows of pixels (fill with zeros, perhaps?)
  2. Discard the last column and the last row.
  3. Change the window size to MxN, where M is a divisor of 364 and N is a divisor of 350.
1
votes

Initialize before the for loop

e=1;

and then start counter in for loop and put this code

imgWindow (:,:,e)= Z(row:min(end,row+N-1), col:min(end,col+N-1));

instead of

imgWindow = Z(row:min(end,row+N-1), col:min(end,col+N-1));

Hope it will help you. Regards