Find Max Delta of Sliding 3x3 Window Over Matrix
显示 更早的评论
I have the code below to find the max delta between a point and its 8 neighbors in a sliding 3x3 window. I do this for the whole matrix input, A. This works fine and correct, but I am wondering if this can be accomplished with several uses of conv2 instead of the imerode/imdilation calls. The computation I'm doing is depicted in the attached image.

% This method works fine...
A = magic(3); % Test case
% This finds the max diff
% between a pixel and its 8 neighbors.
drMin = min(A(:)); drMax = max(A(:)); % Phantom (padding) pts outside of domain are assumed the avg.
padPt = mean([drMin drMax]); % Value to use for padding.
tmp1 = padarray(A,1,padPt,'both'); tmp2 = padarray(tmp1',1,padPt,'both'); Apad = tmp2'; % Pad matrix.
maxApad = imdilate(Apad,ones(3)) - Apad; % Local max minus the map. Delta from each pt to max neighbor.
minApad = imerode(Apad,ones(3)) - Apad; % Local min minus the map. Delta from each pt to min neighbor.
tmp(:,:,1) = abs(maxApad); tmp(:,:,2) = abs(minApad);
Ctmp = max(tmp,[],3); % Largest of the two gives the max delta from each point to its neighbors!
C = Ctmp(2:end-1,2:end-1); % Remove padding...
The expected result for the magic(3) input is:
7 7 5
6 4 6
5 7 7
I have tried with the following code, but it's clearly off.
A = magic(3);
arrayTot = zeros(3,3,8);
kernel = zeros([9 1]); kernel(5) = 1;
for k = 1:9
if k ~=5
kernel(k) = -1;
k1 = kernel;
k1 = reshape(k1,[3 3]);
tmp = conv2(A,k1,'same');
arrayTot(:,:,k) = abs(tmp);
kernel = zeros([9 1]); kernel(5) = 1;
end
end
tst = max(arrayTot,[],3)
Any advice would be appreciated. Thanks.
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Image Processing Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!