Setting an adaptive threshold for image binarization

15 ビュー (過去 30 日間)
Mehran Varshosaz
Mehran Varshosaz 2022 年 7 月 18 日
回答済み: Suraj Kumar 2024 年 8 月 29 日
Hello everyone.
Does any of you have any idea on how to set an adaptive threshold on images similar to ones I have attached below in order to binarize the image so that the luminous LED become 1 and other pixels in the background become 0?
I have tried adaptive thresholding and Otsu thresholding techniques but non of them returned reliable results.
I do not expect to extactly extract all luminous LEDs from image but at least 80% of them must be found.
By the way, I also use watershed segmentation after binarizing the image, so if 2-3 LEDs are connected together after binarization, it's not a big deal :)
Any Method other than thesholding for finding the position of LEDs is also appreciated.

回答 (1 件)

Suraj Kumar
Suraj Kumar 2024 年 8 月 29 日
Hi Mehran,
To set an adaptive threshold, binarize images in a reliable way and represent the white pixels as 1 and background as 0, you can go through the following steps along with the attached code snippets:
1. Load the image and convert it into grayscale using ‘rgb2gray’ function since thresholding works only on intensity values.
I = imread('led.jpg');
if size(I, 3) == 3
I_gray = rgb2gray(I);
else
I_gray = I;
end
2. Apply adaptive thresholding using ‘adaptthresh’ function to handle varying lighting conditions across the image.
% Apply local adaptive thresholding
T = adaptthresh(I_gray, 0.5, 'ForegroundPolarity', 'bright', 'NeighborhoodSize', 25);
BW = imbinarize(I_gray, T);
3.Use morphological operations to remove noise and close small gaps in the binary image. Then filter out small objects that are unlikely to be LEDs using ‘bwareopen’ .
% Use morphological operations to clean up the image
BW_cleaned = imopen(BW, strel('disk', 2));
BW_cleaned = imclose(BW_cleaned, strel('disk', 3));
% Filter out small objects based on area
minArea = 50;
BW_filtered = bwareaopen(BW_cleaned, minArea);
4.Visualize the results to verify them.
% Display the original and processed images
figure;
subplot(1, 2, 1);
imshow(I);
title('Original Image');
subplot(1, 2, 2);
imshow(BW_filtered);
title('Filtered Binarized Image');
You may refer to the output for a clearer understanding:
To know more about the ‘rgb2gray’, bwareopen’ and adaptthresh’ functions in MATLAB you can go through the documentations linked below:
Hope this works for you!

Community Treasure Hunt

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

Start Hunting!

Translated by