Skip to content

Commit de95e5c

Browse files
committed
add regionElementCounts.m
1 parent a1d8cb3 commit de95e5c

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed

src/@Image/regionElementCounts.m

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
function [counts, labels] = regionElementCounts(obj, varargin)
2+
% Count the number of pixels/voxels within each region of a label image.
3+
%
4+
% output = regionElementCounts(input)
5+
%
6+
% Example
7+
% regionElementCounts
8+
%
9+
% See also
10+
%
11+
12+
% ------
13+
% Author: David Legland
14+
% e-mail: david.legland@inrae.fr
15+
% INRAE - BIA Research Unit - BIBS Platform (Nantes)
16+
% Created: 2020-12-02, using Matlab 9.8.0.1323502 (R2020a)
17+
% Copyright 2020 INRAE.
18+
19+
% check input type
20+
if ~isLabelImage(obj)
21+
error('Requires a label image as input');
22+
end
23+
24+
% determine labels
25+
if isempty(varargin)
26+
labels = unique(obj.Data(:));
27+
labels(labels==0) = [];
28+
else
29+
labels = varargin{1};
30+
end
31+
32+
% allocate memory
33+
nLabels = length(labels);
34+
counts = zeros(nLabels, 1);
35+
36+
% iterate over labels and count elements
37+
for i = 1:nLabels
38+
counts(i) = sum(obj.Data(:) == labels(i));
39+
end
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
function tests = test_regionElementCounts
2+
% Test suite for the file regionElementCounts.
3+
%
4+
% Test suite for the file regionElementCounts
5+
%
6+
% Example
7+
% test_regionElementCounts
8+
%
9+
% See also
10+
% regionElementCounts
11+
12+
% ------
13+
% Author: David Legland
14+
% e-mail: david.legland@inrae.fr
15+
% Created: 2020-12-02, using Matlab 9.8.0.1323502 (R2020a)
16+
% Copyright 2020 INRAE - BIA-BIBS.
17+
18+
tests = functiontests(localfunctions);
19+
20+
function test_2d(testCase) %#ok<*DEFNU>
21+
% Count the elements in a label image with 4 regions.
22+
23+
data = zeros(10, 10);
24+
data(2, 2) = 1;
25+
data(2, 4:8) = 3;
26+
data(4:8, 2) = 4;
27+
data(4:8, 4:8) = 9;
28+
img = Image('Data', data, 'Type', 'label');
29+
30+
counts = regionElementCounts(img);
31+
32+
assertEqual(testCase, length(counts), 4);
33+
assertEqual(testCase, counts, [1 5 5 25]');
34+
35+
36+
function test_3d(testCase) %#ok<*DEFNU>
37+
% Count the elements in a label image with 4 regions.
38+
39+
data = zeros(10, 10, 10);
40+
data(2, 2, 2) = 1;
41+
data(4:8, 2, 2) = 3;
42+
data(2, 4:8, 2) = 4;
43+
data(2, 2, 4:8) = 5;
44+
data(4:8, 4:8, 2) = 10;
45+
data(4:8, 2, 4:8) = 12;
46+
data(2, 4:8, 4:8) = 15;
47+
data(4:8, 4:8, 4:8) = 19;
48+
img = Image('Data', data, 'Type', 'label');
49+
50+
counts = regionElementCounts(img);
51+
52+
assertEqual(testCase, length(counts), 8);
53+
assertEqual(testCase, counts, [1 5 5 5 25 25 25 125]');
54+

0 commit comments

Comments
 (0)