
How to convert nearest pixel as same number of pixels value from gray image? like bwlabel?
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
How to convert nearest pixel as same number of pixels value from gray image? like bwlabel?
0 Kommentare
Antworten (1)
Charu
am 5 Mai 2025
Bearbeitet: Charu
am 8 Mai 2025
Hello Voxey,
According to my understanding of the question you want to label connected components in a grayscale image.
The function “bwlabel” works only for binary images, for grayscale images, you can use “bwlabeln” with logical conditions You can also use “bwconncomp” and “labelmatrix” functions in a loop for each unique value.
You can refer to the steps mentioned below to get label connected components in a grayscale image:
- Let I be the grayscale image.
I = [
1 1 2 2;
1 0 0 2;
3 3 0 2
];
- Find the unique values (excluding background e.g.:0)
vals = unique(I);
vals(vals == 0) = [];
% Remove background if needed
- Initialse label matrix
L = zeros(size(I));
label_count = 0;
- Loop through each value and label connected components.
L = zeros(size(I), 'double');
% Make sure L is double
label_count = 0;
for k = 1:length(vals)
mask = I == vals(k);
CC = bwconncomp(mask, 8);
% 8-connectivity for 2D images
temp_labels = double(labelmatrix(CC)); % Convert to double
temp_labels(temp_labels > 0) = temp_labels(temp_labels > 0) + label_count;
L(mask) = temp_labels(mask);
label_count = max(L(:));
end
L is the labelled image and each connected region of the same value has a unique label.
Here is the image generated on sample data, with unique label for grayscale:

For more information on the functions, kindly refer to the link of MathWorks documentation mentioned below:
-bwlabeln:
-bwconncomp:
Hope this helps!
0 Kommentare
Siehe auch
Kategorien
Mehr zu Modify Image Colors finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!