Labeling image region properties

조회 수: 10 (최근 30일)
Chad Greene
Chad Greene 2024년 2월 29일
댓글: Chad Greene 2024년 2월 29일
I have a binary image, and I'd like to create a corresponding mask that contains a value in each pixel for the area of each region. I can do this with bwlabel and regionprops, as shown below, but the loop is extremely slow for a very large binary image. It's just a matter of indexing, so surely there's a way to vectorize my loop?
This code creates the region_area mask that I'm aiming for--Notice the periods have low values, while the bigger letters like m have much larger areas. I'm just seeking ideas for how to speed this up.
% Load a binary image:
BW = imread('text.png');
% Label regions:
[L,Ln] = bwlabel(BW);
% Get the area of each labeled region:
stats = regionprops(L,'Area');
% Create a mask:
region_area = zeros(size(L));
for k = 1:Ln
region_area(L==k) = stats(k).Area;
end
% Display the results:
imagesc(region_area)
axis image
cb = colorbar;
ylabel(cb,'Region area (# of pixels)')

채택된 답변

Gayatri
Gayatri 2024년 2월 29일
Hi Chad,
To speed up the creation of a mask that contains the area value for each pixel in a region, you can replace the for loop with a vectorized operation. The key is to create an array of areas corresponding to the labeled regions and then use this array to directly index into the mask with the labeled image matrix. Here's how you can achieve this:
% Non-vectorized version with loop:
tic; % Start timer for loop
region_area_loop = zeros(size(L));
for k = 1:Ln
region_area_loop(L==k) = stats(k).Area;
end
loop_time = toc; % Stop timer for loop
% Vectorized version:
tic; % Start timer for vectorized
areas = [0, [stats.Area]];
region_area_vectorized = areas(L + 1);
vectorized_time = toc; % Stop timer for vectorized
% Display the timing results:
fprintf('Loop time: %f seconds\n', loop_time);
fprintf('Vectorized time: %f seconds\n', vectorized_time);
To confirm the speed-up, you can time both the original loop-based code and the vectorized code using tic and toc.
I hope this helps!
  댓글 수: 1
Chad Greene
Chad Greene 2024년 2월 29일
Yes, this is brilliant! Thanks @Gayatri!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by