MATLAB Answers

how to detect background color of image ?

46 views (last 30 days)
ElizabethR
ElizabethR on 22 Apr 2016
Commented: ElizabethR on 24 Apr 2016
i want to make function, so if the background color if black like image 1, it will change to white.
But, if the background color image is white like in image 2, so it doesn't change.
How to make it ?? thanks

  1 Comment

MJ Thangaraj
MJ Thangaraj on 23 Apr 2016
The image is Binary so it's obviously going to have only White and BLACK values.Check whether the background in white and then Complement the image .

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 23 Apr 2016
If you can make the assumption that the majority of the pixels in the image are the background color, then
[rows, columns] = size(binaryImage);
numWhitePixels = sum(binaryImage);
numBlackPixels = rows * columns - numWhitePixels;
if numWhitePixels > numBlackPixels
% Background is white.
% Do nothing at all.
else
% Background is black.
% Make image all white, everywhere at every pixel.
binaryImage(:) = true;
end

  5 Comments

Show 2 older comments
ElizabethR
ElizabethR on 24 Apr 2016
thanks for answare, yes you are right, thanks for you explanation. Sorry, because my english is not good enough. I mean that i have image like image one, then the background will change into black and the foreground will change into white. And if the image is like image 2, then the backgroun and the foreground will not change. hanks you ^^
Image Analyst
Image Analyst on 24 Apr 2016
OK, then this should do it
bw = ~bw; % Change black into white and white into black.
ElizabethR
ElizabethR on 24 Apr 2016
okay .. Thank You so Much Image Analyst. God Bless ^^

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 23 Apr 2016
Foreground and background are matters of intent. For example, often binary images are white for the parts that contain the information of interest, but binary images might be representing text and text is often represented in black (corresponding to books, which use dark ink on a white page.) Chess diagrams often use both black and white for the pieces. It is therefore not possible to detect which color is the "foreground" and which color is the "background" by computer program alone.

  1 Comment

ElizabethR
ElizabethR on 24 Apr 2016
thanks for answare my question Walter ^^

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!