Repository navigation
Expand file tree
/
Copy pathlabelacencode.m
More file actions
205 lines (197 loc) · 6.99 KB
/
Copy pathlabelacencode.m
File metadata and controls
205 lines (197 loc) · 6.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
function output = labelacencode(input, es, nx, ny)
%
% output = labelacencode(labels)
% or
% output = labelacencode(bytes, es, nx, ny)
%
% Compress a label array (a segmentation, parcellation or mask) with labelac (experimental): each
% element is predicted from its left, up and front neighbours along the three fastest-varying
% dimensions of the row-major (JData) array, and coded with adaptive counts and interleaved rANS.
% Lossless and bit-exact; about half the size of xz on segmentations. The format is jdai's
% (https://github.com/NeuroJSON/jdai, src/labelac.cpp), byte for byte. ZMat (with labelac) does
% the work when it is installed; else this file's vectorized code (a loop over wavefront planes
% and groups of rANS lanes, not over elements) gives the same bytes.
%
% input:
% labels: an integer, logical or char array, coded in its JData (row-major) order
% bytes: the elements' little-endian bytes in row-major order (uint8), with
% es: the element size in bytes (1, 2, 4 or 8)
% nx, ny: the fastest and second-fastest dimensions (as _ArraySize_(end), _ArraySize_(end-1))
%
% output:
% output: the labelac stream (uint8 row)
%
% examples:
% seg = uint8(randi(3, 64, 64, 64));
% z = labelacencode(seg);
% isequal(typecast(labelacdecode(z), 'uint8'), reshape(permute(seg, [3 2 1]), 1, []))
%
% license:
% BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONLab toolbox (http://neurojson.org/jsonlab)
%
if (nargin == 1)
% a label array: its row-major bytes, element size and two last dimensions
a = input;
if (islogical(a) || ischar(a))
a = uint8(a);
end
if (~isinteger(a) && ~isfloat(a))
error('labelac: a label array must be numeric');
end
dims = size(a);
nx = dims(end);
ny = dims(end - 1);
a = permute(a, ndims(a):-1:1);
input = typecast(a(:).', 'uint8');
es = numel(typecast(cast(0, class(a)), 'uint8'));
end
% ZMat's compiled coder, when it has labelac: the same bytes, much faster
persistent nozmat
if (isempty(nozmat) && exist('zmat', 'file'))
try
output = zmat(reshape(uint8(input), 1, []), 1, 'labelac', 'typesize', es, 'dims', [nx ny]);
if (~isempty(output) || isempty(input))
return
end
catch
end
nozmat = true;
end
M = 65536; % the scale of every quantized table
LOW = 65536; % rANS states live in [LOW, 2^32)
INC = 128; % added to a coded symbol's count
VOTE = 128; % a new context's start for each neighbour's label
LIMIT = 65535; % a context is halved while its total is above this
if (~any(es == [1 2 4 8]))
error('labelac: elements must be 1, 2, 4 or 8 bytes');
end
bytes = reshape(uint8(input), 1, []);
if (mod(numel(bytes), es))
error('labelac: the data is not a whole number of elements');
end
cls = {'uint8', 'uint16', '', 'uint32', '', '', '', 'uint64'};
a = typecast(bytes, cls{es});
count = numel(a);
nx = max(double(nx), 1);
ny = max(double(ny), 1);
if (count && mod(count, nx * ny))
nx = count; % a shape that does not fit: one row
ny = 1;
end
[values, ~, sym] = unique(a(:));
K = numel(values);
if (K > 65536)
error('labelac: more than 65536 distinct values (not a label array)');
end
output = [uint8(1), varint_(es), varint_(nx), varint_(ny), varint_(count), varint_(K), typecast(reshape(values, 1, []), 'uint8')];
if (K <= 1 || count == 0)
return
end
sym = double(sym(:)) - 1;
% the geometry: coordinates, the coding order (wavefront planes x + y + z, increasing index in
% each) and each element's context key (L * K + U) * K + F
i = (0:count - 1)';
x = mod(i, nx);
y = mod(floor(i / nx), ny);
z = floor(i / (nx * ny));
t = x + y + z;
[~, order] = sort(t); % (stable)
bounds = [0; cumsum(accumarray(t + 1, 1))];
L = zeros(count, 1);
U = L;
F = L;
k = find(x > 0);
L(k) = sym(k - 1);
k = find(y > 0);
U(k) = sym(k - nx);
k = find(z > 0);
F(k) = sym(k - nx * ny);
key = (L * K + U) * K + F;
clear L U F x y z t i k;
% every position's frequency and start, plane by plane (the counts from before the plane)
Fq = zeros(count, 1);
Cq = zeros(count, 1);
mkeys = zeros(0, 1); % known context keys, ascending
mrows = zeros(0, 1); % their rows in counts
counts = zeros(1024, K);
nrow = 0;
for p = 1:numel(bounds) - 1
pos = bounds(p) + 1:bounds(p + 1);
if (isempty(pos))
continue
end
j = order(pos);
s = sym(j);
% the plane's contexts: rows of the known ones, new rows for the others
[uk, ~, inv] = unique(key(j));
[tf, loc] = ismember(uk, mkeys);
rows = zeros(numel(uk), 1);
rows(tf) = mrows(loc(tf));
new = uk(~tf);
if (~isempty(new))
newrows = nrow + (1:numel(new))';
if (newrows(end) > size(counts, 1))
counts(max(2 * size(counts, 1), newrows(end)), K) = 0;
end
counts(newrows, :) = 1;
for nb = [floor(new / (K * K)), mod(floor(new / K), K), mod(new, K)]
ix = newrows + nb * size(counts, 1);
counts(ix) = counts(ix) + VOTE;
end
rows(~tf) = newrows;
nrow = newrows(end);
[mkeys, o] = sort([mkeys; new]);
mrows = [mrows; newrows];
mrows = mrows(o);
end
% their quantized tables
cu = counts(rows, :);
f = 1 + floor(cu * (M - K) ./ repmat(sum(cu, 2), 1, K));
[~, im] = max(cu, [], 2);
ix = (1:numel(rows))' + (im - 1) * numel(rows);
f(ix) = f(ix) + M - sum(f, 2);
c = cumsum(f, 2) - f;
ix = inv(:) + s * numel(rows);
Fq(pos) = f(ix);
Cq(pos) = c(ix);
% the plane counted; the contexts it touched halved while their totals are too big
counts(rows, :) = counts(rows, :) + accumarray([inv(:), s + 1], INC, [numel(rows), K]);
touched = rows;
while (~isempty(touched))
big = touched(sum(counts(touched, :), 2) > LIMIT);
if (isempty(big))
break
end
counts(big, :) = floor((counts(big, :) + 1) / 2);
touched = big;
end
end
clear key sym counts;
% interleaved rANS, from the last position to the first: position j in lane mod(j, N)
N = max(1, min(256, floor(count / 8192)));
state = LOW * ones(N, 1);
words = zeros(count, 1);
wpos = count;
for r = ceil(count / N) - 1:-1:0
n = min(N, count - r * N);
f = Fq(r * N + (1:n));
xs = state(1:n);
emit = find(xs >= f * 65536);
w = mod(xs(emit), 65536);
words(wpos - numel(w) + 1:wpos) = w;
wpos = wpos - numel(w);
xs(emit) = floor(xs(emit) / 65536);
state(1:n) = floor(xs ./ f) * M + mod(xs, f) + Cq(r * N + (1:n));
end
output = [output, varint_(N), typecast(uint32(state(:)'), 'uint8'), typecast(uint16(words(wpos + 1:end)'), 'uint8')];
%% -------------------------------------------------------------------------
function b = varint_(v)
b = zeros(1, 0, 'uint8');
v = double(v);
while (v >= 128)
b(end + 1) = uint8(mod(v, 128) + 128);
v = floor(v / 128);
end
b(end + 1) = uint8(v);