MATLAB Answers

How can I speed up (or avoid) a comparison in for loop?

4 views (last 30 days)
Max Mierzwa
Max Mierzwa on 17 Sep 2021 at 9:34
Commented: Matt J on 17 Sep 2021 at 19:03
Hi Everyone,
I'm analysing porosity in volumetric image data from CT scans. The input data is logical. 0 indicates background or pores while 1 indicates material.
The code shows a simplified example with two pores. The smaller pore needs to be removed because it's smaller than the threshold. bwlabeln (from the Image Processing Toolbox) changes the zeros of the pores to an ID (look in L-array). After the labelling I can quickly identify the undersized pores (step #1 f-vector).
My problem is the performance of the for-loop (step #2). For large data sets as in my case (A is typically 1000x300x1000 with over 20,000 pores that need to be removed) this takes forever. How can I improve the performance of the for-loop? Or do you have another idea how to delete (change 0 to 1) the small pores from the data set?
Kind regards,
%% create synthetic specimen
A=ones(10,10,10); % background = 0, material = 1
threshold = 10; % min. amount of elements for pore
A(3:5,3:5,3:5)=0; % pore elements = 27 > threshold -> must be kept
A(7:8,7:8,7:8)=0; % pore elements = 8 < threshold -> must be removed
%% preprocessing
r = 1; % rim size
s = size(A); % size of A
a = zeros(s+(r*2));
a(r+1:r+s(1),r+1:r+s(2),r+1:r+s(3)) = A;
A = imbinarize(a); % make logical
AA = imcomplement(A); % inverse image
[L,n] = bwlabeln(AA,6); % label pores
N = histcounts(L); % number of elements with certain value
%% #1. vector with too small pores (Voxel < threshold)
f = find(N<threshold); % find pores with too little elements
f = f-1;
%% #2. set critical values = 1
for i = 1:length(f)
A(L==f(i)) = 1; % A=0 background or pore, A=1 material
% disp(i) % shows that the loop takes forever if length(f) is large

Accepted Answer

Jan on 17 Sep 2021 at 9:45
Edited: Jan on 17 Sep 2021 at 9:54
What about omitting the loop:
A(ismember(L, f)) = true;
LUT = [false, N < threshold];
A(LUT(L + 1)) = true;
Matt J
Matt J on 17 Sep 2021 at 19:03
In my data from the CT-scans (lenght(f) > 10000) the other issues of the code had a negligible impact on processing time.
Maybe negligible compared to the original for-loop, but the use of bwlabeln and histcounts is unnecessary and quite inefficient. I've modified my example above with length(f)=40000 and you can still see that it is much slower than bwlareaopenn.

Sign in to comment.

More Answers (1)

Community Treasure Hunt

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

Start Hunting!