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

조회 수: 2 (최근 30일)
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.

채택된 답변

Jan
Jan 2021년 4월 8일
편집: Jan 2021년 4월 8일
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
Jan
Jan 2021년 4월 8일
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;
Oliver Horrobin
Oliver Horrobin 2021년 4월 9일
Hi Jan,
It must be a grayscale image. It works perfectly now.
Thankyou so much,
Ollie

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by