-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcubehelix_view.m
More file actions
415 lines (415 loc) · 13.8 KB
/
cubehelix_view.m
File metadata and controls
415 lines (415 loc) · 13.8 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
function [map,lo,hi,prm] = cubehelix_view(N,start,rots,satn,gamma,irange,domain)
% Creates an interactive figure for viewing CubeHelix colormaps. With demo!
%
% Create and view colormaps generated by Dave Green's CubeHelix algorithm:
%
% * Two colorbars show the colormap in color and grayscale.
% * A button toggles between 3D-cube and 2D-lineplot of the RGB values.
% * A button toggles an endless demo of randomly generated colormaps.
% * Nine sliders allow real-time adjustment of the CubeHelix parameters.
% * Warning text if any RGB values are clipped.
% * Warning text if the grayscale is not monotonic increasing/decreasing.
%
%%% Syntax %%%
%
% cubehelix_view
% cubehelix_view(N)
% cubehelix_view(N,start,rots,satn,gamma)
% cubehelix_view(N,start,rots,satn,gamma,irange)
% cubehelix_view(N,start,rots,satn,gamma,irange,domain)
% cubehelix_view(N,[start,rots,satn,gamma],...)
% cubehelix_view([],...)
% cubehelix_view(axes/figure handle array,...) % see "Adjust Colormaps"
% [map,lo,hi] = cubehelix_view(...)
%
% Calling the function with an output argument blocks MATLAB execution until
% the figure is deleted: the final colormap and parameters are then returned.
%
% CubeHelix is defined here: http://astron-soc.in/bulletin/11June/289392011.pdf
% For more information and examples: http://www.mrao.cam.ac.uk/~dag/CUBEHELIX/
%
% Note: The original specification (the links above) misnamed the saturation
% option as "hue". In this function the saturation option is named "satn".
%
%% Adjust Colormaps of Figures or Axes %%
%
% For R2014b or later: provide axes or figure handles as the first input
% and their COLORMAP will be updated in real-time by CUBEHELIX_VIEW:
%
% >> S = load('spine');
% >> image(S.X)
% >> cubehelix_view(gca)
%
%% Input Arguments (**=default) %%
%
% N = NumericScalar, an integer to define the colormap length.
% = []**, colormap length of two hundred and fifty-six (256).
% = Array of axes or figure handles. R2014b or later only.
% start = NumericScalar, the helix's start color (modulus 3), where R=1, G=2, B=3.
% rots = NumericScalar, the number of R->G->B rotations over the full domain.
% satn = NumericScalar, saturation controls how saturated the colors are.
% gamma = NumericScalar, gamma can be used to emphasize low or high intensity values.
% irange = NumericVector, range of brightness levels of the colormap's endnodes. Size 1x2.
% domain = NumericVector, domain of the cubehelix calculation (endnode positions). Size 1x2.
%
%% Output Arguments (block code execution until figure is closed) %%
%
% map = NumericMatrix, the colormap defined when the figure is closed.
% lo = LogicalMatrix, true where <map> values<0 were clipped to 0. Size Nx3
% hi = LogicalMatrix, true where <map> values>1 were clipped to 1. Size Nx3
%
%% Dependencies %%
%
% * MATLAB R2009b or later.
% * cubehelix.m <www.mathworks.com/matlabcentral/fileexchange/43700>
%
% See also CUBEHELIX BREWERMAP PRESET_COLORMAP MAXDISTCOLOR
% RGBPLOT COLORMAP COLORMAPEDITOR COLORBAR UICONTROL ADDLISTENER
persistent ax2D ln2D ax3D pt3D txtH is2D cbAx cbIm pTxt pSld prw
%
new = isempty(ax2D)||~ishghandle(ax2D);
dfn = 256;
upd = false;
upb = false;
hgv = [];
nmr = dfn;
%
if false
% >R2019a only!
fnh = @colororder; %#ok<UNRCH>
else % default
fnh = @colormap;
end
%
err = 'First input <N> must be a real positive scalar numeric or [].';
%
%% Input Wrangling %%
%
if nargin==0 || isnumeric(N)&&isequal(N,[])
N = dfn;
elseif isnumeric(N)
assert(isscalar(N),...
'SC:brewermap_view:N:NotScalarNumeric',err)
assert(isreal(N)&&isfinite(N)&&fix(N)==N&&N>0,...
'SC:brewermap_view:N:NotRealPositiveInteger',err)
N = double(N);
elseif all(ishghandle(N(:))) % R2014b or later
assert(all(isgraphics(N(:),'axes')|isgraphics(N(:),'figure')),...
'SC:cubehelix_view:N:NotAxesNorFigureHandles',...
'First input <N> may be an array of figure or axes handles.')
hgv = N(:);
nmr = arrayfun(@(h)size(fnh(h),1),hgv);
N = nmr(1);
else
error('SC:cubehelix_view:N:UnsupportedInput',err)
end
%
idp = 'SC:cubehelix_view:start:NotParameterVector';
idi = 'SC:cubehelix_view:irange:NotNodeRangeVector';
idd = 'SC:cubehelix_view:domain:NotNodeDomainVector';
txp = '%s input can be a vector of the four CubeHelix parameters: [start,rots,satn,gamma].';
txi = '%s input can be a vector of the endnode lightness levels <irange>.';
txd = '%s input can be a vector of the endnode relative positions <domain>.';
%
% Default pseudo-random parameters:
if nargin==0 || new
clk = sum(clock*100); %#ok<CLOCK>
foo = @(n)min(3,max(0,sqrt(-log(rem(clk/pow2(n),1))*2)));
bar = @(n)min(3,max(0,rem(clk/pow2(n),1)^36));
prw = [rem(clk,3);... % start
min(3,max(-3,log10(rem(clk,1)/(1-rem(clk,1)))));... % rotations
foo(5); foo(4);... % saturation and gamma
bar(3); 1-bar(2); bar(1); 1-bar(0)]; % irange and domain
% Original default parameters:
% prw = [0.5; -1.5; 1; 1; 0; 1; 0; 1];
% [sta; rots; sat; gam; irng; domn]
end
% Parse input parameters:
switch nargin
case 2
prw(1:4) = chvChk(4,start,idp,txp,'Second');
case 3
prw(1:4) = chvChk(4,start,idp,txp,'Second');
prw(5:6) = chvChk(2,rots, idi,txi,'Third');
case 4
prw(1:4) = chvChk(4,start,idp,txp,'Second');
prw(5:6) = chvChk(2,rots, idi,txi,'Third');
prw(7:8) = chvChk(2,satn, idd,txd,'Fourth');
case 5
prw(1:4) = prmChk(start,rots,satn,gamma);
case 6
prw(1:4) = prmChk(start,rots,satn,gamma);
prw(5:6) = chvChk(2,irange,idi,txi,'Sixth');
case 7
prw(1:4) = prmChk(start,rots,satn,gamma);
prw(5:6) = chvChk(2,irange,idi,txi,'Sixth');
prw(7:8) = chvChk(2,domain,idd,txd,'Seventh');
end
%
%% Ensure Figure Exists %%
%
% LHS and RHS slider bounds/limits, and slider step sizes:
lbd = [ 1; 0;-3; 0; 0; 0; 0; 0; 0]; % left limit
rbd = [dfn; 3; 3; 3; 3; 1; 1; 1; 1]; % right limit
mnr = [100; 5; 5; 5; 5; 1; 1; 1; 1]; % minor step
mjr = [100; 5; 5; 5; 5; 1; 1; 1; 1]; % major step
% [ N;st;ro;sa;ga;i1;i2;d1;d2]
stp = [mnr/100,mjr/10]; % [minor,major] step
%
% Define the 3D cube axis order:
xyz = 'RGB'; % specify the order here.
[~,xyz] = ismember(xyz,'RGB');
%
% Parameter names for each slider:
spn = {'N';'start hue';'rotations';'saturation';'gamma';'irange(1)';'irange(2)';'domain(1)';'domain(2)'};
%
if new % Create a new figure.
%
% Figure parameters:
M = numel(spn); % number of sliders
gap = 0.01; % gaps
bth = 0.04; % demo button height
btw = 0.10; % demo button width
uih = 0.40; % UI group height
cbw = 0.23; % colorbar width (both together)
cbh = 1-3*gap-bth; % colorbar height
axh = 1-uih-2*gap; % axes height
axw = 1-cbw-2*gap; % axes width
slh = uih/M - gap; % slider height
%
figH = figure('NumberTitle','off', 'IntegerHandle','off',...
'Units','normalized', 'HandleVisibility','callback',...
'Name','CubeHelix Interactive Parameter Selector',...
'MenuBar','figure', 'Toolbar','none', 'Tag',mfilename);
%
% Add 2D lineplot:
ax2D = axes('Parent',figH, 'Position',[gap,uih+gap,axw,axh], 'Box','on',...
'ColorOrder',[1,0,0; 0,1,0; 0,0,1; 0.6,0.6,0.6], 'HitTest','off',...
'Visible','off', 'XLim',[0,1], 'YLim',[0,1], 'XTick',[], 'YTick',[]);
ln2D = line([0,0,0,0;1,1,1,1],[0,0,0,0;1,1,1,1], 'Parent',ax2D,...
'Visible','off', 'Linestyle','-', 'Marker','.');
%
% Add 3D scatterplot:
ax3D = axes('Parent',figH, 'OuterPosition',[0,uih,axw+2*gap,1-uih],...
'Visible','on', 'XLim',[0,1], 'YLim',[0,1], 'ZLim',[0,1], 'HitTest','on');
pt3D = patch('Parent',ax3D, 'XData',[0;1], 'YData',[0;1], 'ZData',[0;1],...
'Visible','on', 'LineStyle','none', 'FaceColor','none', 'MarkerEdgeColor','none',...
'Marker','o', 'MarkerFaceColor','flat', 'MarkerSize',10, 'FaceVertexCData',[1,1,0;1,0,1]);
view(ax3D,3);
grid(ax3D,'on')
lbl = {'Red','Green','Blue'};
xlabel(ax3D,lbl{xyz(1)})
ylabel(ax3D,lbl{xyz(2)})
zlabel(ax3D,lbl{xyz(3)})
%
% Add warning text:
txtH = text('Parent',ax2D, 'Units','normalized', 'Position',[0,1],...
'HorizontalAlignment','left', 'VerticalAlignment','top', 'Color','r');
%
% Add demo button:
demo = uicontrol(figH, 'Style','togglebutton', 'Units','normalized',...
'Position',[1-cbw/2,1-bth-gap,cbw/2-gap,bth], 'String','Demo',...
'Max',1, 'Min',0, 'Callback',@chvDemo); %#ok<NASGU>
% Add 2D/3D button:
is2D = uicontrol(figH, 'Style','togglebutton', 'Units','normalized',...
'Position',[1-cbw/1,1-bth-gap,cbw/2-gap,bth], 'String','2D / 3D',...
'Max',1, 'Min',0, 'Callback',@chv2D3D);
%
% Add colorbars:
C(1,1,:) = [1,1,1];
cbAx(2) = axes('Parent',figH, 'Visible','off', 'Units','normalized',...
'Position',[1-cbw/2,gap,cbw/2-gap,cbh], 'YLim',[0.5,1.5],...
'YDir','reverse', 'HitTest','off');
cbAx(1) = axes('Parent',figH, 'Visible','off', 'Units','normalized',...
'Position',[1-cbw/1,gap,cbw/2-gap,cbh], 'YLim',[0.5,1.5],...
'YDir','reverse', 'HitTest','off');
cbIm(2) = image('Parent',cbAx(2), 'CData',C);
cbIm(1) = image('Parent',cbAx(1), 'CData',C);
%
% Add parameter sliders, listeners, and corresponding text:
sv = mean([lbd,rbd],2);
for m = M:-1:1
Y = gap+(M-m)*(slh+gap);
pLab(m) = uicontrol(figH,'Style','text', 'Units','normalized',...
'Position',[gap,Y,btw,slh], 'String',spn{m});
pTxt(m) = uicontrol(figH,'Style','text', 'Units','normalized',...
'Position',[gap+btw,Y,btw,slh], 'String','X');
pSld(m) = uicontrol(figH,'Style','slider', 'Units','normalized',...
'Position',[2*btw+gap,Y,axw-2*btw,slh], 'Min',lbd(m), 'Max',rbd(m),...
'SliderStep',stp(m,:)/(rbd(m)-lbd(m)), 'Value',sv(m));
addlistener(pSld(m), 'Value', 'PostSet',@(~,~)chvSldr(m));
end
%
end
%
%% Nested Functions %%
%
function chvUpDt()
% Update all graphics objects in the figure.
%
% Get CubeHelix colormap and grayscale equivalent:
[map,lo,hi] = cubehelix(N, prw(1:4),prw(5:6),prw(7:8));
mag = map*[0.298936;0.587043;0.114021];
%
% Update colorbar values:
set(cbAx, 'YLim',[0,abs(N)+(N==0)]+0.5);
set(cbIm(1), 'CData',reshape(map,[],1,3))
set(cbIm(2), 'CData', repmat(mag,[1,1,3]))
%
% Update 2D line / 3D patch values:
if get(is2D, 'Value')
set(ln2D, 'XData',linspace(0,1,abs(N)));
set(ln2D,{'YData'},num2cell([map,mag],1).');
else % 3D
set(pt3D,...
'XData',map(:,xyz(1)),...
'YData',map(:,xyz(2)),...
'ZData',map(:,xyz(3)),...
'FaceVertexCData',map)
end
%
% Update warning text:
wrn = {' Not Monotonic';' Clipped'};
mad = diff(mag);
idw = [any(mad<=0)&&any(0<=mad);any(lo(:))||any(hi(:))];
set(txtH,'String',wrn(idw));
%
% Update parameter value text:
set(pTxt(1), 'String',sprintf('%.0f',N));
set(pTxt(2:end), {'String'},sprintfc('%.2f',prw));
%
% Update external axes/figure colormaps:
nmr(1) = N;
for k = 1:numel(hgv)
fnh(hgv(k),cubehelix(nmr(k), prw(1:4),prw(5:6),prw(7:8)));
end
%
drawnow()
end
%
function chv2D3D(h,~)
% Switch between 2D-line and 3D-cube representation.
%
if get(h,'Value') % 2D
set(ax3D, 'HitTest','off', 'Visible','off')
set(ax2D, 'HitTest','on', 'Visible','on')
set(pt3D, 'Visible','off')
set(ln2D, 'Visible','on')
else % 3D
set(ax2D, 'HitTest','off', 'Visible','off')
set(ax3D, 'HitTest','on', 'Visible','on')
set(ln2D, 'Visible','off')
set(pt3D, 'Visible','on')
end
%
chvUpDt();
end
%
function chvSldr(m)
% Get new slider value.
%
if ~upd
return
end
%
val = get(pSld(m),'Value');
if m==1
N = round(val);
else
prw(m-1) = val;
end
%
chvUpDt()
end
%
function chvDemo(h,~)
% Display random CubeHelix colormaps.
%
% Parameter value step length:
pvs = 0.03;
% Functions to randomly specify new parameter values:
randfn = cell(1,8);
randfn(7:8) = {@()rand(1,1).^42,@()1-rand(1,1).^42};
randfn(3:4) = {@()sqrt(-log(rand(1,1))*2)};
randfn(1:2) = {@()3*rand(1,1),@()randn(1,1)};
randfn(5:6) = randfn(7:8);
%
% Define initial target values:
tgt = prw;
%
while ishghandle(h) && get(h,'Value')
%
% new random targets:
idr = abs(tgt-prw)<1e-4;
tgt(idr) = round(100*cellfun(@(fn)fn(),randfn(idr)))/100;
% move ontop of close targets:
idt = abs(tgt-prw)<=pvs;
prw(idt) = tgt(idt);
% move towards far away targets:
idm = ~(idr|idt);
prw(idm) = prw(idm) + pvs*sign(tgt(idm)-prw(idm));
%
upb = (upb || N<=1) && N<dfn;
N = N - 1 + 2*upb;
%
% Update slider position:
upd = false;
try %#ok<TRYNC>
set(pSld, {'Value'},num2cell(max(lbd,min(rbd,[N;prw]))));
chvUpDt();
end
upd = true;
%
% Faster/slower:
pause(0.07);
end
%
end
%
%% Initialize the Figure %%
%
set(pSld, {'Value'},num2cell(max(lbd,min(rbd,[N;prw]))));
upd = true;
chvUpDt()
%
if nargout
waitfor(ax2D);
prm = prw;
else
clear map
end
%
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%cubehelix_view
function V = prmChk(varargin)
% Check that separate parameter values are real scalar numerics.
for k = 1:nargin
t = inputname(k);
v = varargin{k};
assert(isnumeric(v)&&isscalar(v)&&isfinite(v)&&isreal(v),...
sprintf('SC:cubehelix_view:%s:NotRealScalarNumeric',t),...
'Input parameter <%s> must be real, finite, numeric scalar.',t)
end
V = cellfun(@double,varargin(:));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%prmChk
function x = chvChk(n,x,eid,msg,ord)
% Check that the input variable <x> is real numeric vector with <n> elements.
assert(isnumeric(x)&&isreal(x)&&all(isfinite(x))&&isvector(x)&&numel(x)==n,eid,msg,ord)
x = double(x(:));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%chvChk
%
% Copyright (c) 2013-2026 Stephen Cobeldick
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and limitations under the License.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%license