Finding the largest difference between any two pixels within a set of 5 contiguous pixels

I have a matrix of 22 x 22 cells each containing a number. For a given cell, I need to find the largest difference between any two cells within a set of five contiguous pixels (ie. that cell and the one above, below, left and right of it). I then need to step forward one cell from the original cell and again analyse the next set of five cells, and repeat this for every column in the matrix.

 Accepted Answer

Use imdilate() with [0 1 0; 1 1 1; 0 1 0] to get the largest value, and imerode() with the same structuring element to get the smallest value, and subtract.
imdilate() corresponds to maximum over the selected pixels, and imerode() corresponds to minimum over the selected pixels.

5 Comments

How do I refer to the initial specific cell to start looking at that subsection of 5 pixels?
You do not need to. The morphological processing will do all possibilities.
M = randi(10,22,22);
pixel_diff = imdilate(M,[0 1 0;1 1 1;0 1 0]) - imerode(M,[0 1 0;1 1 1;0 1 0]);
If you prefer something more explicit, and do not mind that this version does not handle the edges, then
M = randi(10,22,22);
R = 2:size(M,1)-1; C = 2:size(M,2)-1;
PT = M(R-1, C); %row above, same column
PL = M(R,C-1); %same row, previous column
PC = M(R, C); %here
PR = M(R, C+1); %same row, next column
PB = M(R+1, C); %next row, same column
stack = cat(3, PT, PL, PC, PR, PB);
Mmax = max(stack, [], 3);
Mmin = min(stack, [], 3);
pixel_diff2 = Mmax - Mmin;
isequal( pixel_diff(2:end-1, 2:end-1), pixel_diff2)
I have tried to run this code, and get the error 'undefined function or variable 'pixel_diff'.
The last line there, the reference to pixel_diff is a reference to the computation of the short version with imerode and imdilate, and the isequal() is just there to prove that the computations come out the same, to give evidence that the imerode / imdilate version can be trusted.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!