Question

How can I calculate the percent of pixels, where value = 1, in a 10x10 moving analysis window? My ultimate goal is to have an image where area is calculated on a per 10x10 window. I suspect the answer is close to the following (although this does not seem to work):

win = ones(10, 10);      % Create a 10x10 window

count0 = sum(sum(buffer == 0));  % Count pixels with "0" value
count1 = sum(sum(buffer));       % Count pixels with "1" value
percent = count1/(count0 + count1);     % Calculate percent

movingwindow = imfilter(percent, win)

I am trying to use the above to calculate the area of the "trees" in a 10x10 moving window on the following dataset:

% Generate a grid of 0's to begin with.
m = zeros(400, 400, 'uint8');

% Generate 100 random "trees".
numRandom = 100;
linearIndices = randi(numel(m), 1, numRandom);

% Assign a radius value of 1-12 to each tree
m(linearIndices) = randi(12, [numel(linearIndices) 1]);

% Buffer the trees by their radius
buffer = false(size(m));
for radius =1:12 % update to actual range
    im_r  = m==radius;
    se    = strel('disk',radius);
    im_rb = imfilter(im_r, double(se.getnhood()));

    buffer = buffer | im_rb;
end

im2bw(buffer)
Was it helpful?

Solution

With the Image Processing Toolbox, you can use the nfilter function.

Test=triu(ones(100));
f = @(x) numel(x(x==1))/numel(x);
I2 = nlfilter(Test,[10 10],f);

Result:

enter image description here

And then do what's necessary to deal with border artifacts. I suspect there are more efficient ways of doing this (using column-wise processing), but it's a start.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top