MATLAB Answers

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

조회 수: 4(최근 30일)
Max Mierzwa
Max Mierzwa 2021년 9월 17일
댓글: Matt J 2021년 9월 17일
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

채택된 답변

Jan 2021년 9월 17일
편집: Jan 2021년 9월 17일
What about omitting the loop:
A(ismember(L, f)) = true;
LUT = [false, N < threshold];
A(LUT(L + 1)) = true;
  댓글 수: 6
Matt J
Matt J 2021년 9월 17일
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.

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

추가 답변(1개)

Matt J
Matt J 2021년 9월 17일
편집: Matt J 2021년 9월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by