Labeling image region properties

12 Ansichten (letzte 30 Tage)
Chad Greene
Chad Greene am 29 Feb. 2024
Kommentiert: Chad Greene am 29 Feb. 2024
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)')

Akzeptierte Antwort

Gayatri
Gayatri am 29 Feb. 2024
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!

Weitere Antworten (0)

Produkte


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by