Calculate the mean value of border pixels in image and minus that from the whole image

1 view (last 30 days)
Hello,
I am looking for what I am hoping is quite a simple solution.
I have an image that at the moment is 200 by 200 but has the ability to change size (lengh and width but at an equal rate).
What I need: To look at only the outside 5 pixels or so of the whole image ( so a 5 pixel wide band around the image) and calculate the mean pixel value.
I then need to subtract that value from each pixel in the image.
Any help is greatly appreciated,
Ollie.

Accepted Answer

Jan
Jan on 8 Apr 2021
Edited: Jan on 8 Apr 2021
img = rand(30, 60, 3); % Assuming RGB images;
border = 5;
siz = size(img);
mask = false(siz(1), siz(2));
mask(1:border, :) = true;
mask(:, 1:border) = true;
mask(siz(1)-border+1:siz(1), :) = true;
mask(:, siz(2)-border+1:siz(2)) = true;
tmp = reshape(img, [], 3);
meanBorder = mean(tmp(mask, :), 1);
img = img - reshape(meanBorder, 1, 1, 3);
% Cross-check: do the border pixels have a zero mean value now:
tmp = reshape(img, [], 3);
meanBorder = mean(tmp(mask, :), 1)
meanBorder = 1×3
1.0e+-15 * 0.0130 0.1765 -0.0405
Fine. But now some pixels have negative values.
  3 Comments
Jan
Jan on 8 Apr 2021
Maybe your input is not an RGB image, which are [M x N x 3] arrays.
If it is a grayscale image, which are [M x N] matrices, use:
siz = size(img);
mask = false(siz(1), siz(2));
mask(1:border, :) = true;
mask(:, 1:border) = true;
mask(siz(1)-border+1:siz(1), :) = true;
mask(:, siz(2)-border+1:siz(2)) = true;
meanBorder = mean(img(mask));
img = img - meanBorder;

Sign in to comment.

More Answers (0)

Categories

Find more on Images in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!