
How to convert nearest pixel as same number of pixels value from gray image? like bwlabel?
조회 수: 1 (최근 30일)
이전 댓글 표시
How to convert nearest pixel as same number of pixels value from gray image? like bwlabel?
댓글 수: 0
답변 (1개)
Charu
2025년 5월 5일
편집: Charu
2025년 5월 8일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Modify Image Colors에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!