How to find high contrast objects in image?

4 views (last 30 days)
Jakub
Jakub on 27 Mar 2025
Commented: Walter Roberson on 27 Mar 2025
I have matrix 50x200 and i want script that will go through the matrix and compare values with its surrounding values which gives contrast ratio, very higher results will mean object with higher contrast. Usage is detecting objects in image from luminance analyser detected while driving in car.
  1 Comment
Jakub
Jakub on 27 Mar 2025
Each value in matrix is luminance value of each image`s pixel.

Sign in to comment.

Answers (1)

TED MOSBY
TED MOSBY on 27 Mar 2025
Edited: TED MOSBY on 27 Mar 2025
Hi Jakub,
The contrast ratio is the absolute difference between the center pixel and the mean of its 8 neighbors divided by the neighbor mean. You can simply loop through the pixels and extract a 3*3 block around each of it, then calculate the contrast.
I have written an example script for your reference:
imageMatrix = rand(50,200); % This is just an example matrix
[m, n] = size(imageMatrix);
contrastMatrix = zeros(m, n);
% Loop through the matrix excluding the boundary pixels
for i = 2:m-1
for j = 2:n-1
% Extract the 3x3 neighborhood centered at (i,j)
neighborhood = imageMatrix(i-1:i+1, j-1:j+1);
% Calculate the sum of the 3x3 block and subtract the center pixel
centerPixel = imageMatrix(i,j);
localMean = (sum(neighborhood(:)) - centerPixel) / 8;
% Compute the contrast ratio
if localMean ~= 0
contrastMatrix(i,j) = abs(centerPixel - localMean) / localMean;
else
contrastMatrix(i,j) = 0;
end
end
end
% Visualize the contrast matrix
figure;
imagesc(contrastMatrix);
colorbar;
title('Contrast Ratio Map');
xlabel('Pixel Column');
ylabel('Pixel Row');
The output appears as below:
Hope this helps!
  1 Comment
Walter Roberson
Walter Roberson on 27 Mar 2025
This sounds like a job for
abs(conv2(double(imageMatrix), [1 1 1; 1 -1 1; 1 1 1]/8, 'same'))

Sign in to comment.

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!