MATLAB: How to replace the center pixel of a 3X3 window with the min difference among its surronding pixels in matlab

digital image processingfilter designImage Processing Toolbox

I want to replace the center pixel of a 3×3 window filter with the minimum difference among its surrounding pixels. I want to run this process for all pixels of the image.
Then I want to calculate the mean square of the minimum differences of all pixels in the entire image.
Would you please give me some suggestion or code snippet to solve my problem. I am new in matlab.
Please response..

Best Answer

I think you're going to have to do it manually by using conv2() 8 times with a [-1 1] kernel that rotates around the 8 neighbors, and then take the min of the 8 images. Then square, sum, and sqrt.
image1 = conv2(grayImage, [-1, 0, 0; 0, 1, 0; 0, 0, 0], 'same');
image2 = conv2(grayImage, [0, -1, 0; 0, 1, 0; 0, 0, 0], 'same');
image3 = conv2(grayImage, [0, 0, -1; 0, 1, 0; 0, 0, 0], 'same');
image4 = conv2(grayImage, [0, 0, 0; -1, 1, 0; 0, 0, 0], 'same');
image5 = conv2(grayImage, [0, 0, 0; 0, 1, -1; 0, 0, 0], 'same');
image6 = conv2(grayImage, [0, 0, 0; 0, 1, 0; -1, 0, 0], 'same');
image7 = conv2(grayImage, [0, 0, 0; 0, 1, 0; 0, -1, 0], 'same');
image8 = conv2(grayImage, [0, 0, 0; 0, 1, 0; 0, 0, -1], 'same');
allImages = cat(3, image1, image2, image3, image4, image5, ...
image6, image7, image8);
minDiffImage = min(allImages, [], 3);
minDiffImage = minDiffImage .^2; % Square it.
mse = mean(minDiffImage (:));
Try that untested code and see how it works.