Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you don't have access to the <a href="http://www.mathworks.com/products/image/" rel="nofollow">Image Processing Toolbox</a>, another way to accomplish this is by constructing four matrices representing the top, right, bottom and left first differences for each point and then searching for corresponding elements in all four matrices that are non-negative (i.e. the element exceeds all of its neighbours).</p> <p>Here's the idea broken down...</p> <p>Generate some test data:</p> <pre> >> sizeA = 3; A = randi(255, sizeA) A = 254 131 94 135 10 124 105 191 84 </pre> <p>Pad the borders with zero-elements:</p> <pre> >> A2 = zeros(sizeA+2) * -Inf; A2(2:end-1,2:end-1) = A A2 = 0 0 0 0 0 0 254 131 94 0 0 135 10 124 0 0 105 191 84 0 0 0 0 0 0 </pre> <p>Construct the four first-difference matrices:</p> <pre> >> leftDiff = A2(2:end-1,2:end-1) - A2(2:end-1,1:end-2) leftDiff = 254 -123 -37 135 -125 114 105 86 -107 >> topDiff = A2(2:end-1,2:end-1) - A2(1:end-2,2:end-1) topDiff = 254 131 94 -119 -121 30 -30 181 -40 >> rightDiff = A2(2:end-1,2:end-1) - A2(2:end-1,3:end) rightDiff = 123 37 94 125 -114 124 -86 107 84 >> bottomDiff = A2(2:end-1,2:end-1) - A2(3:end,2:end-1) bottomDiff = 119 121 -30 30 -181 40 105 191 84 </pre> <p>Find the elements that exceed all of the neighbours:</p> <pre> indexKeep = find(leftDiff >= 0 & topDiff >= 0 & rightDiff >= 0 & bottomDiff >= 0) </pre> <p>Create the resulting matrix:</p> <pre> >> B = zeros(sizeA); B(indexKeep) = A(indexKeep) B = 254 0 0 0 0 124 0 191 0 </pre> <p>After wrapping this all into a function and testing it on 1000 random 100x100 matrices, the algorithm appears to be quite fast:</p> <pre> >> tic; for ii = 1:1000 A = randi(255, 100); B = test(A); end; toc Elapsed time is 0.861121 seconds. </pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload