Hi there,
I have a 3D array (mask) with the numbers 0 background, 1, 2, 3 and 4. The numbers 1,2,3 and 4 correspond to particular regions.
I want to count how many regions in my 3D mask have the number 1,2,3, or 4.
Does anyone know how to do this?

 採用された回答

Rik
Rik 2020 年 2 月 6 日
編集済み: Rik 2020 年 2 月 7 日

0 投票

You can use bwlabeln to label all your non-zero regions. then you can loop through each of the labeled regions to determine which number they have. With that, you essentially have the result you need.
If you don't have the image processing toolbox, let me know, because I have an alternative that doesn't require any toolbox.
Edit: added the example below.
%generate example data where max(L(:)) returns about 30
IM=randi(300000,100,100,100);
IM(IM>10)=0;
[L,n_regions]=bwlabeln(IM>0);
counts=zeros(1,max(IM(:)));
for n=1:n_regions
ind=find(L==n,1);
field_val=IM(ind);
counts(field_val)=counts(field_val)+1;
end

4 件のコメント

Gina Carts
Gina Carts 2020 年 2 月 7 日
Hi Rik,
Thanks for your reply. I tried the bwlabeln function like this:
[L,n] = bwlabeln(mask);
When I printed n, I got the number 32. This is actually the correct number of regions I have (non-zero) but it doesn't give me how many regions of these 32 have number 1, how many number 2, how many number 3 etc.
How can I do that?
Rik
Rik 2020 年 2 月 7 日
I added an example to my answer. Let me know if there is anything unclear.
Gina Carts
Gina Carts 2020 年 2 月 7 日
I think I see how it works. When I print the counts I got the following:
counts =
4 5 4 2 2 4 1 5 1 5
That means I have 4 regions with number 1, 5 regions with number 2 etc. Am I correct?
Rik
Rik 2020 年 2 月 8 日
Yes, that is the idea. There might be more efficient ways to get to this vector, but this is what I could come up with.

サインインしてコメントする。

その他の回答 (0 件)

質問済み:

2020 年 2 月 6 日

コメント済み:

Rik
2020 年 2 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by