MATLAB: How to threshold the image automatically based on its energy content

histogramimage processingthresholding

Say my threshold is taking in those components that constitute about 75% of energy of image and making the remaining as zero.How do I do that?

Best Answer

D_coder, try this:
clc; % Clear the command window.
clearvars;
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
grayImage = imread('cameraman.tif');
subplot(2, 2, 1);
imshow(grayImage);
title('Original Image', 'FontSize', fontSize);
sortedGrayLevels = double(sort(grayImage(:), 'descend'));
% Sum up the energy from most energetic to least energy.
percentage = cumsum(sortedGrayLevels);
percentage = percentage / percentage(end);
subplot(2, 2, 2);
plot(percentage, 'b-', 'LineWidth', 2);
grid on;
title('Cumulative Distribution Function', 'FontSize', fontSize);
% Find the brighter 75%
% Find the gray level where 75 percent is

index75 = find(percentage >= 0.75, 1, 'first')
grayLevel75 = grayImage(index75)
% threshold the most energy 75%

binaryImage = grayImage > grayLevel75;
subplot(2, 2, 3);
imshow(binaryImage);
title('Brighter 75%', 'FontSize', fontSize);
% Find the darker 75%
% Find the gray level where 75 percent is
index75 = find(percentage >= 0.25, 1, 'first')
grayLevel25 = grayImage(index75)
% threshold the most energy 75%
binaryImage25 = grayImage < grayLevel25;
subplot(2, 2, 4);
imshow(binaryImage25);
title('Darker 75%', 'FontSize', fontSize);
Each binary image will contain 75% of the energy. It just depends if you wanted to start with the darker pixels and work brighter, or start with the brightest pixels and work darker.