plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
ylucet/CCA-master
|
plq_coSplit_test.m
|
.m
|
CCA-master/tests/plq_coSplit_test.m
| 6,280 |
utf_8
|
1c012fd8273507e6b5c09482c30fec29
|
function tests = plq_coSplit_test()
tests = functiontests(localfunctions);
end
% Author: Mike Trienis, Bryan Gardiner
% For: Dr. Yves Lucet
% Whatsit: A test file for plq convex hull function plq_coSplit.
% I = Indicator, E = Exponential, C = Conjugate, L = Linear, Q = Quadratic
function [b] = testPointIndicator(testCase)
b = false;
plqf = [5,0,0,10];
result = plq_coSplit(plqf);
b = all(plqf == result);
assert(all(all(b)));
end
function [b] = testConcaveQ(testCase)
b = false;
plqf = [-1,0,0,inf; 2,-1,0,1; inf,0,0,inf];
result = plq_coSplit(plqf);
expected = [-1,0,0,inf; 2,0,-1,-1; inf,0,0,inf];
b = all(result == expected);
assert(all(all(b)));
end
%---------------------------%
function [b] = testL2Lch_1(testCase)
b = false;
plqf = [-1,0,0,inf; 1,0,1,-1; 4,0,0,0; inf,0,0,inf];
result = plq_coSplit(plqf);
desired = [-1,0,0,inf; 4,0,0.4,-1.6; inf,0,0,inf];
b = all(result == desired | abs(result - desired) < 1E-5);
assert(all(all(b)));
end
function [b] = testL2L2L2Lch_2(testCase)
b = false;
plqf = [0,0,0,inf; 1,0,-1,1; 2,0,1,-1; 3,0,-1,3; 4,0,1,-3; inf,0,0,inf];
result = plq_coSplit(plqf);
desired = [0,0,0,inf; 1,0,-1,1; 3,0,0,0; 4,0,1,-3; inf,0,0,inf];
b = (result == desired | abs(result - desired) < 1E-5);
assert(all(all(b)));
end
function [b] = testQ2L2Qch_3(testCase)
b = false;
plqf = [-1,1/2,0,1; 1,0,-2,-0.5; inf,1,-2,-1.5];
result = plq_coSplit(plqf);
desired = plq_co(plqf);
b = (result == desired | abs(result - desired) < 1E-5);
assert(all(all(b)));
end
function [b] = testQ2Qch_6(testCase)
b = false;
plqf = [0,2,4,0;inf,2,-4,0];
result = plq_coSplit(plqf); result(end,1)=0;
desired=[-1,2,4,0;1,0,0,- 2;inf,2,-4,0]; desired(end,1)=0;
b = all(norm(result-desired) < 1E-5);
assert(all(all(b)));
end
%---------------------------%
function [b] = testL2L2Qch_7(testCase)
b = false;
plqf = [0,0,1,0;2,0,0,0;inf,1,-4,4];
result = plq_coSplit(plqf); result(end,1)=0;
desired = [2.5,0,1,-2.25;inf,1,-4,4]; desired(end,1)=0;
b = all(norm(result-desired) < 1E-5);
assert(all(all(b)));
end
function [b] = testQ2Q2Qch_8(testCase)
b = false;
plqf =[-2,1,8,16;2,-1,0,8;inf,1,-8,16];
result = plq_coSplit(plqf); result(end,1)=0;
desired = [-4,1,8,16;4,0,0,0;inf,1,-8, 16]; desired(end,1)=0;
b = all(norm(result-desired) < 1E-5);
assert(all(all(b)));
end
%---------------------------%
function [b] = testQ2Q2Qch_9(testCase)
b = false;
plqf =[-2,1,8,16;2,-1,0,8;inf,1,-8,16];
result = plq_coSplit(plqf); result(end,1)=0;
desired=[-4,1,8,16;4,0,0,0;inf,1,-8,16]; desired(end,1)=0;
b = all(norm(result-desired) < 1E-5);
assert(all(all(b)));
end
function [b] = testQ2L2L2Qch_10(testCase)
b = false;
plqf =[-3,1,8,16;0,0,1,4;3,0,-1,4;inf,1,-8,16];
result = plq_coSplit(plqf); result(end,1)=0;
desired = [-4,1,8,16;4,0,0,0;inf,1,-8,16]; desired(end,1)=0;
b = all(norm(result-desired) < 1E-5);
assert(all(all(b)));
end
function [b] = testQ2L2L2Qch_11(testCase)
b = false;
plqf =[-3,1,8,16;0,0,-1,-2;3,0,1,-2;inf,1,-8,16];
result = plq_coSplit(plqf); result(end,1)=0;
desired = [-4.2426407,1,8,16;0,0,-0.4852814,-2;4.2426407,0,0.4852814,-2;inf,1,-8,16]; desired(end,1)=0;
b = all(norm(result-desired) < 1E-5);
assert(all(all(b)));
end
%---------------------------%
function [b] = testL2Q2Lch_12(testCase)
b = false;
plqf =[-2,0,-1,10;2,1,0,8;inf,0,1,10];
result = plq_coSplit(plqf); result(end,1)=0;
desired=[-0.5,0,-1,7.75;0.5,1,0,8;inf,0,1,7.75]; desired(end,1)=0;
b = all(norm(result-desired) < 1E-5);
assert(all(all(b)));
end
function [b] = testL2Q2Lch_13(testCase)
b = false;
plqf =[-2,0,-1,2;1,-1,0,8;inf,0,1,6];
result = plq_coSplit(plqf); result(end,1)=0;
desired=[- 2,0,-1,2;inf,0,1,6]; desired(end,1)=0;
b = all(norm(result-desired) < 1E-5);
assert(all(all(b)));
end
%---------------------------%
function [b] = testPosInfHull_0(testCase)
b = false;
plqf = [inf,0,0,inf];
result = plq_coSplit(plqf);
desired = [inf,0,0,inf];
b = (result == desired);
assert(all(all(b)));
end
function [b] = testNegInfHull_0(testCase)
b = false;
plqf = [inf,0,0,-inf];
result = plq_coSplit(plqf);
desired = [inf,0,0,-inf];
b = (result == desired);
assert(all(all(b)));
end
function [b] = testNegInfHull_1(testCase)
b = false;
plqf = [0,-1,-2,1;1,0,0,1;inf,1,1,0];
result = plq_coSplit(plqf);
desired = [inf,0,0,-inf];
b = (result == desired);
assert(all(all(b)));
end
function [b] = testNegInfHull_2(testCase)
b = false;
plqf = [-1,1,4,3;1,0,2.5,2.5;3,1,-2,6;inf,-2,12,-9];
result = plq_coSplit(plqf);
desired = [inf,0,0,-inf];
b = (result == desired);
assert(all(all(b)));
end
function [b] = testNegInfHull_3(testCase)
b = false;
plqf = [0,0,-1,0;1,1,0,0;inf,0,-2,3];
result = plq_coSplit(plqf);
desired = [inf,0,0,-inf];
b = (result == desired);
assert(all(all(b)));
end
%---------------------------%
function [b] = runTestFile(testCase)
b = true;
b = checkForFail(testWrapper(testPointIndicator, 'testPointIndicator'), b);
b = checkForFail(testWrapper(testConcaveQ, 'testConcaveQ'), b);
b = checkForFail(testWrapper(testL2Lch_1, 'testL2Lch_1'), b);
b = checkForFail(testWrapper(testL2L2L2Lch_2, 'testL2L2L2Lch_2'), b);
b = checkForFail(testWrapper(testQ2L2Qch_3, 'testQ2L2Qch_3'), b);
b = checkForFail(testWrapper(testQ2Qch_6, 'testQ2Qch_6'), b);
b = checkForFail(testWrapper(testL2L2Qch_7, 'testL2L2Qch_7'), b);
b = checkForFail(testWrapper(testQ2Q2Qch_8, 'testQ2Q2Qch_8'), b);
b = checkForFail(testWrapper(testQ2Q2Qch_9, 'testQ2Q2Qch_9'), b);
b = checkForFail(testWrapper(testQ2L2L2Qch_10, 'testQ2L2L2Qch_10'), b);
b = checkForFail(testWrapper(testQ2L2L2Qch_11, 'testQ2L2L2Qch_11'), b);
b = checkForFail(testWrapper(testL2Q2Lch_12, 'testL2Q2Lch_12'), b);
b = checkForFail(testWrapper(testL2Q2Lch_13, 'testL2Q2Lch_13'), b);
b = checkForFail(testWrapper(testPosInfHull_0, 'testPosInfHull_0'), b);
b = checkForFail(testWrapper(testNegInfHull_0, 'testNegInfHull_0'), b);
b = checkForFail(testWrapper(testNegInfHull_1, 'testNegInfHull_1'), b);
b = checkForFail(testWrapper(testNegInfHull_2, 'testNegInfHull_2'), b);
b = checkForFail(testWrapper(testNegInfHull_3, 'testNegInfHull_3'), b);
assert(all(all(b)));
end
|
github
|
ylucet/CCA-master
|
plq_add_Test.m
|
.m
|
CCA-master/tests/plq_add_Test.m
| 2,283 |
utf_8
|
72223477778971e187982a08e027ab67
|
%% Author: Mike Trienis
%% For: Dr. Yves Lucet
%% Whatsit: A test file for plq_add, adds two piecewise linear quadratic functions.
%%mode(-1);
%%L: Linear, Q: Quadratic, I: Indicator, PW: Piecewise
%%__test_set = 'PLQ: plq_add';
function tests = plq_add_Test
tests = functiontests(localfunctions);
end
function [b] = testQLQNonsmPlusQLQNonsm(testCase)
b = 0;
plqf = [-1,1,0,0;1,0,0,1;inf,1,0,0];
plqg = [0,1,0,0;2,0,1,0;inf,1,0,-2];
result=plq_add(plqf,plqg);
desired = [-1,2,0,0;0,1,0,1;1,0,1,1;2,1,1,0;inf,2,0,-2];
b = all(result==desired);
end
function [b] = testQQSmoothPlusQQSmooth(testCase)
b = 0;
plqf = [-1,1,1,1; inf,1,1,1];
plqg = [-2,1,1,0; inf,1,1,0];
result = plq_add(plqf,plqg);
desired = [inf,2,2,1];
b = all(result==desired);
end
%%Note this function tests when there is a common point between the two PLQ functions
function [b] = testQLSmoothPlusQLQNonsm(testCase)
b = 0;
plqf=[1,1,0,0;3, 0, 2, -1;inf,3,-16,26];
plqg=[0,1,0,0;1, 0, 1, 0;inf,3, -4, 2];
result = plq_add(plqf,plqg);
desired = [0,2,0,0;1,1,1,0;3,3,-2,1;inf,6,-20,28];
b = all(result==desired);
end
function [b] = testIPlusQ(testCase)
b = 0;
plqf=[4,0,0,5];
plqg=[inf,1/2,0,0];
result = plq_add(plqf,plqg);
desired = [4,0,0,13];
b = all(result==desired);
end
function [b] = testIPlusQPW(testCase)
b = 0;
plqf=[4,0,0,5];
plqg=[0,0,-1,0;inf,0,1,0];
result = plq_add(plqf,plqg);
desired = [4,0,0,9];
b = all(result==desired);
end
function [b] = testIPlusQPW2(testCase)
b = 0;
plqg=[4,0,0,5];
plqf=[0,0,-1,0;inf,0,1,0];
result = plq_add(plqf,plqg);
desired = [4,0,0,9];
b = all(result==desired);
end
function [b] = testIPlusPL(testCase)
b = 0;
Ii=[-0.5,0,0,inf;0.5,0,0,0;inf,0,0,inf];
plq=[-1,0,-1,-1;0,0,1,1;1,0,-1,1;inf,0,1,-1];
result = plq_add(Ii,plq);
desired = [-0.5,0,0,inf;0,0,1,1;0.5,0,-1,1;inf,0,0,inf];
b = all(result==desired);
end
function [b] = testIPlusI(testCase)
b = 0;
f1 = [1,0,0,3];
f2 = [1,0,0,10];
result = plq_add(f1, f2);
desired = [1,0,0,13];
b = isequal(desired, result);
end
function [b] = testIPlusI2(testCase)
b = 0;
f1 = [1,0,0,3];
f2 = [2,0,0,10];
result = plq_add(f1, f2);
desired = [inf,0,0,inf];
b = isequal(desired, result);
end
|
github
|
ylucet/CCA-master
|
plq_split_test.m
|
.m
|
CCA-master/tests/plq_split_test.m
| 1,441 |
utf_8
|
4e61a0e2842691344452cc25b35fd779
|
function tests = plq_split_test()
tests = functiontests(localfunctions);
end
%perform all tests by comparing with plq functions
function b = prim(p)
P=gph_plq(p);
q=plq_scalar(p,3);Q=gph_plq(q);
QQ=gph_scalar(P,3);
b = gph_isEqual(Q,QQ);
q=plq_scalar(p,0);Q=gph_plq(q);
QQ=gph_scalar(P,0);
b = b & gph_isEqual(Q,QQ);
end
function [b] = testAbs(testCase)
p =[0 0 -1 0; inf 0 1 0];%abs function
b = prim(p);
assert(b)
end
function [b] = testInd(testCase)
p=[-1 0 0 inf;1 0 0 0 ;inf 0 0 inf];
b = prim(p);
assert(b)
end
function [b] = testPL(testCase)
% A piecewise linear function:
% x<0: y=-x
% 0<x<1: y=0
% 1<x: y=x-1
G = [-1, 0, 0, 1, 1, 2; ...
-1, -1, 0, 0, 1, 1; ...
1, 0, 0, 0, 0, 1];
p=plq_gph(G);
b = prim(p);
assert(b)
end
function [b] = testPLQ1(testCase)
b = false;
% A PLQ function:
% x<-1: y=(x+1)^2
% -1<x<1: y=0
% 1<x: y=(x-1)^2
p=[-1 1 2 1;1 0 0 0;inf 1 -2 1];
b = prim(p);
assert(b)
end
function [b] = testPLQ2(testCase)
b = false;
% A PLQ function:
% x in [-1,1]: 0
% otherwise: x^2 - 1
p=[-1 1 0 -1;1 0 0 0;inf 1 0 -1];
b = prim(p);
assert(b)
end
function [b] = testQuadratic(testCase)
p=[inf,1,0,0];
b = prim(p);
assert(b)
end
function [b] = testLinear(testCase)
p=[inf,0,1,0];
b = prim(p);
assert(b)
end
function [b] = testIndicatorSingleton(testCase)
p=[1,0,0,2];
b = prim(p);
assert(b)
end
|
github
|
ylucet/CCA-master
|
plq_min_test.m
|
.m
|
CCA-master/tests/plq_min_test.m
| 2,474 |
utf_8
|
f304c3a87b23864e5c6b724a481332d4
|
function tests = plq_min_test()
tests = functiontests(localfunctions);
end
% Author: Mike Trienis
% For: Dr. Yves Lucet
% Whatsit: A test file for plq_max, adds two piecewise linear quadratic functions.
%L: Linear, Q: Quadratic, I: Indicator, PW: Piecewise
function [b] = testLLMin(testCase)
b = false;
plqf = [inf,0,1,0];
plqg = [inf,0,-1,0];
[result,maxf] = plq_min(plqf,plqg);
% x=linspace(-5,5,25)';
% ymax = plq_eval(result,x);
% plot2d(x,ymax);
desired = [0,0,1,0;inf,0,-1,0];
b = isequal(result, desired);
b = b & isequal(maxf, [1,-inf,0;2,0,inf]);
assert(all(all(b)));
end
function [b] = testQLMax(testCase)
b = false;
plqf = [inf,1,0,0];
plqg = [inf,0,0,1];
result = plq_min(plqf,plqg);
% x=linspace(-5,5,25)';
% ymax = plq_eval(result,x);
% plot2d(x,ymax);
desired = [-1,0,0,1;1,1,0,0;inf,0,0,1];
b = isequal(result,desired);
assert(all(all(b)));
end
function [b] = testQLQMax(testCase)
b = false;
plqf = [-1,1,0,0;1,0,0,1;inf,1,0,0];
plqg = [0,1,0,0;2,0,1,0;inf,1,0,-2];
result = plq_min(plqf,plqg);
result_clean = plq_clean(result);
% x=linspace(-5,5,100)';
% yf = plq_eval(plqf,x);
% yg = plq_eval(plqg,x);
% plot2d(x,[yf,yg],rect=[-2,-1,2,5]);
desired = [0,1,0,0;2,0,1,0;inf,1,0,-2];
b = isequal(result_clean,desired);
assert(all(all(b)));
end
function [b] = testQQMax(testCase)
b = false;
plqf1 = [inf,1,0,0];
plqf2 = [inf,1/10,0,1];
result = plq_min(plqf1,plqf2);
% x=linspace(-5,5,100)';
% f0=plq_eval(result,x);
% f1=plq_eval(plqf1,x);
% f2=plq_eval(plqf2,x);
% plot2d(x,[f0,f1,f2]);
% a=gca(); % Handle on axes entity
% a.thickness=3;
% poly1= a.children.children(3); %store polyline handle into poly1
% poly1.foreground = 2; % another way to change the style
% poly1.thickness = 3;
desired = [- 1.0540926,0.1,0,1;1.0540926,1,0,0;inf,0.1,0,1];
b = isequal(result(:,2:end),desired(:,2:end));
assert(all(all(b)));
end
function [b] = testQQMaxdl(testCase)
b = false;
plqf1 = [inf,1,0,0];
plqf2 = [inf,1,2,-1];
result = plq_min(plqf1,plqf2);
% x=linspace(-5,5,100)';
% f0=plq_eval(result,x);
% f1=plq_eval(plqf1,x);
% f2=plq_eval(plqf2,x);
% plot2d(x,[f0,f1,f2]);
% a=gca(); % Handle on axes entity
% a.thickness=3;
% poly1= a.children.children(3); %store polyline handle into poly1
% poly1.foreground = 2; % another way to change the style
% poly1.thickness = 3;
desired = [0.5,1,2,-1;inf,1,0,0];
b = isequal(result,desired);
assert(all(all(b)));
end
|
github
|
ylucet/CCA-master
|
gph_check_test.m
|
.m
|
CCA-master/tests/gph_check_test.m
| 1,873 |
utf_8
|
2dda0168ec6cbbf03c72e215ef8774bb
|
function tests = gph_check_test()
tests = functiontests(localfunctions);
end
function [b] = testBoundedDomain(testCase)
f=[-1 -1 1 1;-1 0 0 1;inf 0 0 inf];
b=gph_check(f);
assert(b)
end
function [b] = testXNondecreasing(testCase)
f=[-1 -2 1 1;-1 0 0 1;0 0 0 0];
b= ~gph_check(f);
assert(b)
end
function [b] = testSNondecreasing(testCase)
f=[-1 0 1 1;-1 0 0 -1;0 0 0 0];
b= ~gph_check(f);
assert(b)
end
function [b] = testN(testCase)
f=[1;0;0];
b=~gph_check(f);%n==1
f=[-1 -2 1 1;-1 0 0 1];
b=b & ~gph_check(f);%2xn
assert(b)
end
function [b] = testFullDomain(testCase)
p=[inf,1,0,0];f=gph_plq(p);
b=gph_check(f);
assert(b)
end
function [b] = testIndicatorSingleton(testCase)
p=[1,0,0,2];f=gph_plq(p);
b=gph_check(f);
assert(b)
end
function [b] = testCont(testCase)
b = false;
f = [ -1 -1 0 0 1 1; ...
-2 -1 -1 0 2 3; ...
inf 1 0 0 1 inf];
b = gph_check(f);
assert(b)
end
function [b] = testDiscont1(testCase)
b = false;
f = [ -1 -1 0 0 1 1; ...
-2 -1 -1 0 2 3; ...
inf 1 1 1 2 inf];
b = ~gph_check(f);
assert(b)
end
function [b] = testDiscont2(testCase)
b = false;
f = [ -1 -1 0 0 1 1; ...
-2 -1 -1 0 2 3; ...
inf 1 0 1 1 inf];
b = ~gph_check(f);
assert(b)
end
function [b] = testDiscont3(testCase)
b = false;
f = [ -1 -1 0 0 1 1; ...
-2 -1 -1 0 2 3; ...
inf 1 1 0 1 inf];
b = ~gph_check(f);
assert(b)
end
function [b] = testDiscontL(testCase)
% Test discontinuity in the first region.
b = false;
f = [-1 0 0 1; ...
-1 -1 1 1; ...
2 0 0 1];
b = ~gph_check(f);
assert(b)
end
function [b] = testDiscontR(testCase)
% Test discontinuity in the first region.
b = false;
f = [-1 0 0 1; ...
-1 -1 1 1; ...
1 0 0 2];
b = ~gph_check(f);
assert(b)
end
|
github
|
ylucet/CCA-master
|
gph_pa_test.m
|
.m
|
CCA-master/tests/gph_pa_test.m
| 2,336 |
utf_8
|
80b0ff973df76cc4d3246354181f3010
|
function tests = gph_pa_helper()
tests = functiontests(localfunctions);
end
% I = Indicator, E = Exponential, C = Conjugate, L = Linear, Q = Quadratic
function b=helper(f1, f2, lambda)
rplq = plq_pa(f1,f2,lambda);
G1=gph_plq(f1);
G2=gph_plq(f2);
G = gph_pa(G1,G2,lambda);
rgph = plq_gph(G);
b = plq_isEqual(rplq, rgph);
end
function [b] = testL2Lpa(testCase)
f1 = [inf, 0, 1, 0];
f2 = [inf, 0, -1, 5];
b = helper(f1,f2,0.5);
assert(all(all(b)));
end
function [b] = testI2Ipa(testCase)
f1 = [6,0,0,4];
f2 = [5,0,0,1];
b = helper(f1,f2,0.5);
assert(all(all(b)));
end
function b = testQ2Q(testCase)
p0 = [inf,0.5,0,0];
p1 = [inf,1,-2,1];
b = helper(p0,p1,0.2);
assert(all(all(b)));
end
function [b] = testAbs2zero1a(testCase)
f1 = [0,0,0,0];
f2 = [0,0,-1,0;inf,0,1,0];
b = helper(f2,f1,0.5);
assert(all(all(b)));
end
function [b] = testAbs2zero1b(testCase)
f1 = [0,0,0,0];
f2 = [0,0,-1,0;inf,0,1,0];
b = helper(f1,f2,0.5);
assert(all(all(b)));
end
function b = testPLQ2PLQ(testCase)
x=linspace(-2,2,4)';
function y=f0(x),y=x.^4;end
function y=df0(x),y=4*x.^3;end
p0 = plq_build(x,@f0,@df0,false,false,'soqs','bounded');
p1 = [inf,1,-2,1];
b = helper(p1,p0,0.5);
b = helper(p0,p1,0.5);
assert(all(all(b)));
end
function [b] = testAbs2zero2a(testCase)
f0 = [inf,0,0,0];
f1 = [0,0,-1,0;inf,0,1,0];
b = helper(f1,f0,0.5);
assert(all(all(b)));
end
function [b] = testAbs2zero2b(testCase)
f0 = [inf,0,0,0];
f1 = [0,0,-1,0;inf,0,1,0];
b = helper(f0,f1,0.5);
assert(all(all(b)));
end
function b = test1(testCase)
function y=f0(x), y=x.^4;end
function y=df0(x), y=4*x.^3;end
domf0=[-inf,inf];
function y=f1(x), y=exp(x);end
function y=df1(x), y=exp(x);end
domf1=[-inf,inf];
x=linspace(-10,10,5);
p0 = plq_build(x,@f0,@df0,false,false,'soqs','bounded');
p1 = plq_build(x,@f1,@df1,false,false,'soqs','bounded');
b = helper(p0,p1,0.5);
assert(all(all(b)));
end
function b= test2(testCase)
f1=[-2,0,0,inf;-1,0,0,0;inf,0,0,inf];
f2=[1,0,0,inf;2,0,0,0;inf,0,0,inf];
b = helper(f1,f2,0.5);
assert(all(all(b)));
end
function test_expected(testCase)
f1 = [6,0,0,4];
f2 = [5,0,0,1];
G1=gph_plq(f1);G2=gph_plq(f2);
G = gph_pa(G1,G2,0.5);
expected = [5.5 5.5; -1.5 1.5; 2.625 2.625];
b = isequal(expected, G);
assert(all(all(b)));
end
|
github
|
ylucet/CCA-master
|
plq_conv_test.m
|
.m
|
CCA-master/tests/plq_conv_test.m
| 4,951 |
utf_8
|
70767f3da63fe338cf326098a0f4657f
|
function tests = plq_conv_test()
tests = functiontests(localfunctions);
end
% Author: Mike Trienis
% For: Dr. Yves Lucet
% Whatsit: A test file for plq
%L: Linear, Q: Quadratic, I: Indicator
function b = testInfconvLft(testCase)
b = false;
plqf = [inf,1/4,0,0];
plqg = [inf,1,0,0];
result = plq_infconv_lft(plqf,plqg);
desired = [inf,1/5,0,0];
b = all(result==desired);
assert(b);
end
function b = testDeconvLft(testCase)
b = false;
plqf = [inf,1/4,0,0];
plqg = [inf,1,0,0];
result = plq_deconv_lft(plqf,plqg);
desired = [inf,1/3,0,0];
b = all(result==desired);
assert(b);
end
function b = testInfconvBruteDL1(testCase)
b = false;
f = [-1,0,0,inf;1,0,-1,0;inf,0,0,inf];
g = [-1,0,0,inf;1,0,1,0;inf,0,0,inf];
desired = plq_infconv_lft(f, g);
[result1, lb1] = plq_infconv_brute_d(f(2,:), g(2,:), [-1;-1], [1;1]);
[result2, lb2] = plq_infconv_brute_d(g(2,:), f(2,:), [-1;-1], [1;1]);
result1 = [lb1,0,0,inf;result1;inf,0,0,inf];
result2 = [lb2,0,0,inf;result2;inf,0,0,inf];
b = isequal(desired, result1, result2);
assert(b);
end
function b = testInfconvBruteDL2(testCase)
b = false;
f = [-0.5,0,0,inf;1.5,0,-1,0.5;inf,0,0,inf];
g = [-1,0,0,inf;1,0,1,0;inf,0,0,inf];
desired = plq_infconv_lft(f, g);
[result1, lb1] = plq_infconv_brute_d(f(2,:), g(2,:), [-0.5;-1], [1.5;1]);
[result2, lb2] = plq_infconv_brute_d(g(2,:), f(2,:), [-1;-0.5], [1;1.5]);
result1 = [lb1,0,0,inf;result1;inf,0,0,inf];
result2 = [lb2,0,0,inf;result2;inf,0,0,inf];
b = isequal(desired, result1, result2);
assert(b);
end
function b = testInfconvBruteDL3(testCase)
b = false;
f = [-1,0,0,inf;1,0,-1,0;inf,0,0,inf];
g = [2,0,0,inf;4,0,1,-3;inf,0,0,inf];
desired = plq_infconv_lft(f, g);
[result1, lb1] = plq_infconv_brute_d(f(2,:), g(2,:), [-1;2], [1;4]);
[result2, lb2] = plq_infconv_brute_d(g(2,:), f(2,:), [2;-1], [4;1]);
result1 = [lb1,0,0,inf;result1;inf,0,0,inf];
result2 = [lb2,0,0,inf;result2;inf,0,0,inf];
b = isequal(desired, result1, result2);
assert(b);
end
function b = testInfconvBruteL0(testCase)
% nf==1, ng==1, f up, g up.
b = false;
f = [-1,0,0,inf;1,0,1,0;inf,0,0,inf];
g = [0,0,0,inf;2,0,2,-1/2;inf,0,0,inf];
desired = plq_infconv_lft(f, g);
[result1, am1] = plq_infconv_brute(f, g);
[result2, am2] = plq_infconv_brute(g, f);
b = isequal(desired, result1, result2);
%b = b & isEqual(am1, am2),
assert(b);
end
function b = testInfconvBruteL1(testCase)
% nf==2, ng==1, f v, g up.
b = false;
f = [-1,0,0,inf;1,0,-1,0;3,0,1,-2;inf,0,0,inf];
g = [-1,0,0,inf;1,0,1,0;inf,0,0,inf];
desired = plq_infconv_lft(f, g);
[result1, am1] = plq_infconv_brute(f, g);
[result2, am2] = plq_infconv_brute(g, f);
b = isequal(desired, result1, result2);
%b = b & isEqual(am1, am2),
assert(b);
end
function b = testInfconvBruteL2(testCase)
% nf==2, ng==2, f v, g v.
b = false;
f = [-1,0,0,inf;1,0,-1,0;3,0,1,-2;inf,0,0,inf];
g = [-3,0,0,inf;-1,0,-1,-1;1,0,1,1;inf,0,0,inf];
desired = plq_infconv_lft(f, g);
[result1, am1] = plq_infconv_brute(f, g);
[result2, am2] = plq_infconv_brute(g, f);
b = isequal(desired, result1, result2);
%b = b & isEqual(am1, am2),
assert(b);
end
function b = testInfconvBruteL3(testCase)
% nf==3, ng==3, f u, g down, disjoint domains.
b = false;
f = [-4,0,0,inf;-3,0,-1,-2;-2,0,0,1;-1,0,1,3;inf,0,0,inf];
g = [0,0,0,inf;1,0,-5,8;2,0,-2,5;3,0,-1/2,2;inf,0,0,inf];
desired = plq_infconv_lft(f, g);
[result1,am1] = plq_infconv_brute(f, g);
[result2,am2] = plq_infconv_brute(g, f);
b = isequal(desired, result1, result2);
%b = b & isEqual(am1, am2);
assert(b);
end
function plqf = plq_pl_from(x0, y0, dx, ms)
if (size(ms, 1) > size(ms, 2))
ms = ms';
end;
plqf = zeros(length(ms) + 2, 4);
x = x0;
y = y0;
plqf(1,:) = [x0, 0, 0, inf];
i = 2;
for m = ms
plqf(i,:) = [x + dx, 0, m, y - m*x];
x = x + dx;
y = plqf(i,3)*x + plqf(i,4);
i = i + 1;
end;
plqf(end,:) = [inf, 0, 0, inf];
end
function b = testInfconvBruteL4(testCase)
b = false;
%f = [0,0,0,inf;2,0,0,1;3,0,0,0;6,0,0,1;inf,0,0,inf];
f = [0.5,0,0,inf;1.5,0,-1,1.5;2.5,0,0,0;5,0,0.4,-1;inf,0,0,inf];
g = [0,0,0,inf;1,0,-1,2;3,0,1,0;inf,0,0,inf];
desired = plq_infconv_lft(f, g);
[result1, am1] = plq_infconv_brute(f, g);
[result2, am2] = plq_infconv_brute(g, f);
b = (desired == result1 | abs(desired - result1) < 1E-6);
b = b & (desired == result2 | abs(desired - result2) < 1E-6);
assert(all(all(b)));
%b = b & isEqual(am1, am2);
end
function b = testInfconvBruteLCommut1(testCase)
b = false;
f = plq_pl_from(0, 0, 1, 1:4);
g = plq_pl_from(0.1, -2, 0.3, 1:8);
desired = plq_infconv_lft(f, g);
[result1, am1] = plq_infconv_brute(f, g);
[result2, am2] = plq_infconv_brute(g, f);
b = (desired == result1 | abs(desired - result1) < 1E-6);
b = b & (desired == result2 | abs(desired - result2) < 1E-6);
assert(all(all(b)));
%b = b & isEqual(am1, am2);
end
|
github
|
ylucet/CCA-master
|
gph_plq_test.m
|
.m
|
CCA-master/tests/gph_plq_test.m
| 2,844 |
utf_8
|
5730c9c9fb170d8323974d470698c991
|
function tests = gph_plq_test()
tests = functiontests(localfunctions);
end
% Unit test file for gph_plq
function b = testAbs(testCase)
%abs function
p = [0,0,-1,0;inf,0,1,0];
G = gph_plq(p);
E = [-1, 0, 0, 1; -1, -1, 1, 1; 1, 0, 0, 1];
b = all(G==E);
assert(all(all(b))) ;
end
function b = testQuartic(testCase)
function y=f(x), y=x.^4;end
function dy=df(x), dy=4*x.^3;end
x=linspace(-2,2,4)';
p=plq_build(x,@f,@df,true,false,'soqs','bounded');
P=gph_plq(p);
pg=plq_gph(P);
b=plq_isEqual(p,pg);
assert(all(all(b)))
end
function [b] = testInd(testCase)
b = false;
% The function I_[-1,1].
plq = [-1,0,0,inf; 1,0,0,0; inf,0,0,inf];
gph = gph_plq(plq);
expected = [-1, -1, 1, 1; ...
-1, 0, 0, 1; ...
inf, 0, 0, inf];
b = all(gph == expected);
assert(all(all(b)))
end
function [b] = testPL(testCase)
b = false;
plq = [0,0,-1,0; 1,0,0,0; inf,0,1,-1];
gph = gph_plq(plq);
expected = [-1, 0, 0, 1, 1, 2; ...
-1, -1, 0, 0, 1, 1; ...
1, 0, 0, 0, 0, 1];
b = all(gph == expected);
assert(all(all(b)))
end
function [b] = testPLQ1(testCase)
b = false;
% A PLQ function:
% x<-1: y=(x+1)^2
% -1<x<1: y=0
% 1<x: y=(x-1)^2
plq = [-1,1,2,1; 1,0,0,0; inf,1,-2,1];
gph = gph_plq(plq);
expected = [-2, -1, 1, 2; ...
-2, 0, 0, 2; ...
1, 0, 0, 1];
b = all(gph == expected);
assert(all(all(b)))
end
function b = testPLQ2(testCase)
b = false;
% A PLQ function:
% x in [-1,1]: 0
% otherwise: x^2 - 1
plq = [-1,1,0,-1; 1,0,0,0; inf,1,0,-1];
gph = gph_plq(plq);
expected = [-2, -1, -1, 1, 1, 2; ...
-4, -2, 0, 0, 2, 4; ...
3, 0, 0, 0, 0, 3];
b = all(gph == expected);
assert(all(all(b)))
end
function b = testFullDomain(testCase)
p = [inf,1,0,0];
gph = gph_plq(p);
ge = [-1 1;-2 2;1 1];
b = gph_isEqual(gph,ge);
assert(all(all(b)))
end
function b = testIndicator(testCase)
p = [2,0,0,1];
gph = gph_plq(p);
ge = [2 2;-1 1;1 1];
b = gph_isEqual(gph,ge);
assert(all(all(b)))
end
function [b] = runTestFile(testCase)
b = true;
b = checkForFail(testWrapper(testAbs,'testAbs'), b);
b = checkForFail(testWrapper(testQuartic,'testQuartic'), b);
b = checkForFail(testWrapper(testInd,'testInd'), b);
b = checkForFail(testWrapper(testPL,'testPL'), b);
b = checkForFail(testWrapper(testPLQ1,'testPLQ1'), b);
b = checkForFail(testWrapper(testPLQ2,'testPLQ2'), b);
b = checkForFail(testWrapper(testFullDomain,'testFullDomain'), b);
b = checkForFail(testWrapper(testIndicator,'testIndicator'), b);
assert(all(all(b)))
end
|
github
|
ylucet/CCA-master
|
removeTriplicate_test.m
|
.m
|
CCA-master/tests/removeTriplicate_test.m
| 604 |
utf_8
|
19efe538d0b1d7571029d87534dd2e8d
|
function tests = removeTriplicate_test()
tests = functiontests(localfunctions);
end
function [b] = test1(testCase)
M=[1 2 2 3 3 3 4 4 4 4];
[N,k]=removeTriplicate(M,1E-6);
b=all(N==[1 2 2 3 3 4 4]) & all(k==[1 2 3 4 6 7 10]);
assert(b)
end
function [b] = test2(testCase)
M=[1 2 2 3 3 3 4 4 4 4 1 1];
[N,k]=removeTriplicate(M,1E-6);
b=all(N==[1 2 2 3 3 4 4 1 1]) & all(k==[1 2 3 4 6 7 10 11 12]);
assert(b)
end
function [b] = runTestFile(testCase)
b = true;
b = checkForFail(testWrapper(test1,'test1'), b);
b = checkForFail(testWrapper(test2,'test2'), b);
assert(b)
end
|
github
|
ylucet/CCA-master
|
plq_isEqual_test.m
|
.m
|
CCA-master/tests/plq_isEqual_test.m
| 1,280 |
utf_8
|
1eaeeac91c15c077770bee61fa7d0714
|
function tests = plq_isEqual_test()
tests = functiontests(localfunctions);
end
function b = test1(testCase)
%domain is split
p1=[inf 1 0 0];
p2=[0 1 0 0;inf 1 0 0];
b=plq_isEqual(p1,p2);
%small values
eps=1e-12;
p2=[inf 1+eps eps -eps];
b=b & plq_isEqual(p1,p2);
%small values + split partitions
p2=[-eps 1 0 eps;eps 1-eps -eps/10 0;inf 1 -eps eps/1000];
b=b & plq_isEqual(p1,p2);
p1=[1 0 0 1];
b=plq_isEqual(p1,p1);
p2=[1 0 0 1+eps];
b=plq_isEqual(p1,p2);
assert(b) ;
end
function b= test2(testCase)
p = [-1 0 0 inf;1 0 0 0 ;inf 0 0 inf];
b = plq_isEqual(p,p);
assert(b) ;
end
function b= test3(testCase)
p = [-1 0 0 -inf;1 0 0 0 ;inf 0 0 -inf];
b = plq_isEqual(p,p);
assert(b) ;
end
function b= test4(testCase)
p = [1 0 0 -4];q=[inf 0 0 -4];
b = ~plq_isEqual(p,q);
assert(b) ;
end
function b=test5(testCase)
x=linspace(-2,2,4)';
function y=f0(x),y=x.^4;end
function y=df0(x),y=4*x.^3;end
p0 = plq_build(x,@f0,@df0,false,false,'soqs','bounded');
p1 = [inf,1,-2,1];
f1=p0;
f2=p1;
lambda=0.5;
rplq = plq_pa(f1,f2,lambda);
G1=gph_plq(f1);
G2=gph_plq(f2);
G = gph_pa(G1,G2,lambda);
rgph = plq_gph(G);
rplq=plq_clean(rplq);
rgph=plq_clean(rgph);
b = plq_isEqual(rplq, rgph);
assert(b) ;
end
|
github
|
ylucet/CCA-master
|
gph_add_test.m
|
.m
|
CCA-master/tests/gph_add_test.m
| 5,664 |
utf_8
|
65879a46c95294e9112bc35b1f1d23ce
|
function tests = gph_add_test()
tests = functiontests(localfunctions);
end
% Unit test file for gph_add
% The codes for the gph model are as follows:
% - I represents a point indicator
% - L represents a linear plq region (flat line in the gph)
% - Q represents a quadratic plq region (non-flat line in the gph)
% - B represents bounded on a specific side
function b = testI_I_same(testCase)
% Add two point indicators with different x values.
b = false;
gph1 = [2 2; -1 1; 3 3]; % f(2) = 3
gph2 = [2 2; -1 1; 5 5]; % f(2) = 5
X = [1; 2; 3; 5; 8; 10];
expected = [inf; 8; inf; inf; inf; inf];
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(expected == actual);
assert(all(all(b)))
end
function b = testI_I_diff(testCase)
% Add two point indicators with different x values.
b = false;
gph1 = [2 2; -1 1; 3 3]; % f(2) = 3
gph2 = [5 5; -1 1; 8 8]; % f(5) = 8
X = [1; 2; 3; 5; 8; 10];
expected = X + inf;
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(expected == actual);
assert(all(all(b)))
end
function b = testI_LL(testCase)
% Add a point indicator to a linear function, and assert that
% the result is another point indicator.
b = false;
gph1 = [-1 -1; -1 1; 2 2];
gph2 = [-1 0 0 1; -1 -1 1 1; 1 0 0 1];
gph = gph_add(gph1, gph2);
b = gph(1,1)==-1 & gph(1,2)==-1 & gph(3,1)==3 & gph(3,2)==3;
assert(all(all(b)))
end
function b = testL_L_sameX(testCase)
% Add two single-region linear functions, defined with different X
% values.
eps = 1e-10;
b = false;
gph1 = [-5 -4; 0 0; 2 2]; % f(x) = 2
gph2 = [-5 -4; 2 2; -7 -5]; % f(x) = 2*x + 3
X = (-1.5:0.5:1.5)';
expected = 2*X + 5;
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(abs(expected - actual) < eps); assert(all(all(b)))
end
function b = testL_L_diffX(testCase)
% Add two single-region linear functions, defined with identical x
% values.
eps = 1e-10;
b = false;
gph1 = [-1 1; 0 0; 2 2]; % f(x) = -5*X - 10
gph2 = [0 1; 2 2; 3 5]; % f(x) = 2*X + 3
X = (-1.5:0.5:1.5)';
expected = 2*X + 5;
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(abs(expected - actual) < eps);
assert(all(all(b)))
end
function b = testQ_LQ_oneSameX(testCase)
% Add a single-region quadratic function to a two-region function,
% where an x value in the first lines up with an x value in the second.
eps = 1e-10;
b = false;
gph1 = [0 1; 0 2; 0 1]; % f(x) = x^2
gph2 = gph_plq([0,0,-1,0; inf,1/2,0,0]);
X = (-2:0.5:2)';
expected = [6; 3.75; 2; 0.75; 0; 0.375; 1.5; 3.375; 6];
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(abs(expected - actual) < eps);
assert(all(all(b)))
end
function b = testQ_LQ_allDiffX(testCase)
% Add a single-region quadratic function to a two-region function,
% where NO x value in the first lines up with an x value in the second.
eps = 1e-10;
b = false;
gph1 = [0 1; 0 2; 0 1]; % f(x) = x^2
gph2 = gph_plq([5,0,-1,5; inf,1/2,-5,25/2]);
X = (-2:0.5:7)';
expected = [11; 8.75; 7; 5.75; 5; 4.75; 5; 5.75; 7; 8.75; 11; ...
13.75; 17; 20.75; 25; 30.375; 36.5; 43.375; 51];
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(abs(expected - actual) < eps);
assert(all(all(b)))
end
function b = testQ_BL(testCase)
% Add a single-region quadratic function to a lower-bounded
% single-linear-region function.
eps = 1e-10;
b = false;
gph1 = [1 2; 2 4; 1 4]; % f(x) = x^2
gph2 = gph_plq([0,0,0,inf; inf,0,1,0]); % f(x) = x, x > 0
X = (-1:0.5:2)';
expected = [inf; inf; 0; 0.75; 2; 3.75; 6];
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(expected == actual | abs(expected - actual) < eps);
assert(all(all(b)))
end
function b = testBLB_BLB(testCase)
% Add two bounded linear functions with different, overlapping,
% domains.
eps = 1e-10;
b = false;
% f(x) = 2*x, for -1 <= x <= 1.
gph1 = [-1 -1 1 1; 1 2 2 3; inf -2 2 inf];
% g(x) = 3, for 0 <= x <= 2.
gph2 = [0 0 2 2; -1 0 0 1; inf 3 3 inf];
X = (-1.5:0.5:2.5)';
expected = [inf inf inf 3 4 5 inf inf inf]';
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(expected == actual | abs(expected - actual) < eps);
assert(all(all(b)))
end
function b = testLL_LL(testCase)
% Add two unbounded linear functions with same domain breaks.
eps = 1e-10;
b = false;
gph1 = gph_plq([0,0,0,0; inf,0,2,0]);
gph2 = gph_plq([0,0,-1,0; inf,0,1,0]);
X = (-1.5:0.5:1.5)';
expected = [1.5 1 0.5 0 1.5 3 4.5]';
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(expected == actual | abs(expected - actual) < eps);
assert(all(all(b)))
end
function b = testLL_LL_2(testCase)
% Add two unbounded linear functions with different domain breaks.
eps = 1e-10;
b = false;
gph1 = gph_plq([0,0,0,0; inf,0,2,0]);
gph2 = gph_plq([2,0,-1,2; inf,0,1,-2]);
X = (-1.5:0.5:3.5)';
expected = [3.5, 3, 2.5, 2, 2.5, 3, 3.5, 4, 5.5, 7, 8.5]';
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(expected == actual | abs(expected - actual) < eps);
assert(all(all(b)))
end
function b = testQLQ_BLB(testCase)
% Add an unbounded quadratic-linear-quadratic function to a bounded
% linear function defined only over two of the first function's regions.
eps = 1e-10;
b = false;
gph1 = gph_plq([-1,1,2,1; 1,0,0,0; inf,1,-2,1]);
gph2 = gph_plq([0,0,0,inf; 2,0,1,0; inf,0,0,inf]);
X = (-2:0.5:3)';
expected = [inf; inf; inf; inf; 0; 0.5; 1; 1.75; 3; inf; inf];
gph = gph_add(gph1, gph2);
actual = gph_eval(gph, X);
b = all(expected == actual | abs(expected - actual) < eps);
assert(all(all(b)))
end
|
github
|
ylucet/CCA-master
|
gph_scalar_test.m
|
.m
|
CCA-master/tests/gph_scalar_test.m
| 1,429 |
utf_8
|
86d9179e6949dd73a0b94cf9da0ad91f
|
function tests = gph_scalar_test()
tests = functiontests(localfunctions);
end
%perform all tests by comparing with plq functions
function b = helper(p)
P=gph_plq(p);
q=plq_scalar(p,3);
Q=gph_plq(q);
QQ=gph_scalar(P,3);
b = gph_isEqual(Q,QQ);
q=plq_scalar(p,0);
Q=gph_plq(q);
QQ=gph_scalar(P,0);
end
function [b] = testAbs(testCase)
p =[0 0 -1 0; inf 0 1 0];%abs function
b=helper(p);
assert(b)
end
function [b] = testInd(testCase)
p=[-1 0 0 inf;1 0 0 0 ;inf 0 0 inf]; b=helper(p);
assert(b)
end
function [b] = testPL(testCase)
% A piecewise linear function:
% x<0: y=-x
% 0<x<1: y=0
% 1<x: y=x-1
G = [-1, 0, 0, 1, 1, 2; ...
-1, -1, 0, 0, 1, 1; ...
1, 0, 0, 0, 0, 1];
p=plq_gph(G);
b=helper(p);
assert(b)
end
function [b] = testPLQ1(testCase)
b = false;
% A PLQ function:
% x<-1: y=(x+1)^2
% -1<x<1: y=0
% 1<x: y=(x-1)^2
p=[-1 1 2 1;1 0 0 0;inf 1 -2 1];
b=helper(p);
assert(b)
end
function [b] = testPLQ2(testCase)
b = false;
% A PLQ function:
% x in [-1,1]: 0
% otherwise: x^2 - 1
p=[-1 1 0 -1;1 0 0 0;inf 1 0 -1];
b=helper(p);
assert(b)
end
function [b] = testQuadratic(testCase)
p=[inf,1,0,0];
b=helper(p);
assert(b)
end
function [b] = testLinear(testCase)
p=[inf,0,1,0];
b=helper(p);
assert(b)
end
function [b] = testIndicatorSingleton(testCase)
p=[1,0,0,2];
b=helper(p);
assert(b)
end
|
github
|
ylucet/CCA-master
|
gph_isEqual_test.m
|
.m
|
CCA-master/tests/gph_isEqual_test.m
| 886 |
utf_8
|
34fd01765157409680c99adb0b725d05
|
function tests = gph_isEqual_test()
tests = functiontests(localfunctions);
end
function b = test1(testCase)
%domain is split
p1=[inf 1 0 0];g1=gph_plq(p1);
p2=[0 1 0 0;inf 1 0 0];g2=gph_plq(p2);
b=gph_isEqual(g1,g2);
%small values
eps=1e-9;
p2=[inf 1+eps eps -eps];g2=gph_plq(p2);
b=b & gph_isEqual(g1,g2);
%small values + split partitions
p2=[-eps 1 0 eps;eps 1-eps -eps/10 0;inf 1 -eps eps/1000];
g2=gph_plq(p2);
b=b & gph_isEqual(g1,g2);
assert(b)
end
function b = testIndicator(testCase)
p = [2,0,0,1];
g = gph_plq(p);
ge = [2 2;-1 1;1 1];
b = gph_isEqual(g,ge);
assert(b)
end
function b = testFullDomain(testCase)
p = [2,0,0,1];
g = gph_plq(p);
ge = [2 2;-1 1;1 1];
b = gph_isEqual(g,ge);
assert(b)
end
function b= test2(testCase)
p = [-1 -1 1 1; -1 0 0 1;inf 0 0 inf];
g = gph_plq(p);
b = gph_isEqual(g,g);
assert(b)
end
|
github
|
ylucet/CCA-master
|
plq_conv_buildl.m
|
.m
|
CCA-master/macros/plq/plq_conv_buildl.m
| 3,414 |
utf_8
|
089e1a7e917222922d8c21336aad477b
|
%build a linear function, f1i, is the function index, and x1i is the x-value we wanted to evaluate the function on.
%similarly f2i is the function index of the second function, and x2i corresponds to the value we evaluate the function on.
%In other words constructs a linear function from (x1i,f[f1i](x(x1i))), to (x(x2i),f[f2i](x(x2i))).
%function [plq_fctn] = _plq_conv_build2(x,a,b,c)
function [l_fctn]=plq_conv_buildl(x,a,b,c,f1i,x1i,f2i,x2i),
%printf(" x(x1i)=
%The case used most often is the PLQ convex hull on a bounded interval [x(1),x(5)].
if x(x1i) > -inf & x(x2i) < inf
%LOWER BOUNDRY IS FINITE, UPPER BOUNDRY IS FINITE
y1 = a(f1i)*x(x1i).^2 + b(f1i)*x(x1i) + c(f1i);
y2 = a(f2i)*x(x2i).^2 + b(f2i)*x(x2i) + c(f2i);
m = (y2-y1)/(x(x2i)-x(x1i)); %slope
i = -x(x1i)*m + y1; l_fctn = [x(x2i),0,m,i];
elseif x(1) == -inf & x(5) == inf
%LOWER BOUNDRY IS UNBOUNDED, UPPER BOUNDRY IS UNBOUNDED
if a(1) ~= 0 & a(2) ~= 0
cerror('_plq_conv_buildl: CASE D.N.E. (1)'); %D.N.E, as x(2), & x(4) exist
elseif a(1) ~= 0 & a(2) == 0
%special
x(2)=-1/2*(b(1)-2*a(2)*x(3)-b(2))/a(1);
y1 = a(1)*x(2).^2+b(1)*x(2)+c(1);
m=2*a(2)*x(3)+b(2);
i=-x(2)*m+y1;
l_fctn=[x(2),a(1),b(1),c(1);x(5),0,m,i];
elseif a(1) == 0 & a(2) ~= 0
%special
x(4) = 1/2*(-b(2)+2*a(1)*x(3)+b(1))/a(2);
y2 = a(2)*x(4).^2 + b(2)*x(4) + c(2);
m=2*a(1)*x(3) + b(1);
i=-x(4)*m + y2;
l_fctn=[x(4),0,m,i;x(5),a(2),b(2),c(2)];
elseif a(1) == 0 & a(2) == 0
%D.N.E, as plqco=[inf,0,0,-inf]
else cerror('_plq_conv_buildl: Case does not exist');
end;
elseif x(1) == -inf & x(5) < inf
%LOWER BOUNDRY IS UNBOUNDED, UPPER BOUNDRY IS FINITE
if a(1) ~= 0 & a(2) ~= 0
cerror('_plq_conv_buildl: CASE D.N.E (2)'); %D.N.E, as x(2), & x(4) exist
elseif a(1) ~= 0 & a(2) == 0
cerror('_plq_conv_buildl: CASE D.N.E (3)'); %D.N.E, as x(2) exists
elseif a(1) == 0 & a(2) ~= 0
%special
x(4) = 1/2*(-b(2)+2*a(1)*x(3)+b(1))/a(2);
y2 = a(2)*x(4).^2 + b(2)*x(4) + c(2);
m=2*a(1)*x(3) + b(1);
i=-x(4)*m + y2;
l_fctn =[x(4),0,m,i;x(5),a(2),b(2),c(2)];
elseif a(1) == 0 & a(2) == 0
l_fctn = [x(5),0,b(1),-x(5)*b(1)+(b(2)*x(5)+c(2))]; %special
else cerror('_plq_conv_buildl: Case does not exist');
end;
elseif x(1) > -inf & x(5) == inf
%LOWER BOUNDRY IS FINITE, UPPER BOUNDRY IS UNBOUNDED
if a(1) ~= 0 & a(2) ~= 0
cerror('_plq_conv_buildl: CASE D.N.E. (4)'); %D.N.E, as x(2), & x(4) exist
elseif a(1) ~= 0 & a(2) == 0
%special
x(2) = (b(2)-b(1))/2*a(1);
y2 = a(1)*x(2).^2 + b(1)*x(2) + c(1);
m=b(2);
i=-x(2)*m + y2;
l_fctn =[x(2),a(1),b(1),c(1);x(5),0,m,i];
elseif a(1) == 0 & a(2) ~= 0
cerror('_plq_conv_buildl: CASE D.N.E. (5)'); %D.N.E, as x(4) exists
elseif a(1) == 0 & a(2) == 0
%special
l_fctn=[inf,0,b(2),-x(1)*b(2)+(b(1)*x(1)+c(1))];
else cerror('_plq_conv_buildl: CASE D.N.E. (6)');
end;
else cerror('_plq_conv_buildl: CASE D.N.E. (7)');
end
end
|
github
|
ylucet/CCA-master
|
plq_conv_qlq.m
|
.m
|
CCA-master/macros/plq/plq_conv_qlq.m
| 1,138 |
utf_8
|
354736313b4d338c3590428c16b49aea
|
% This function processes a function containing a QLQ segment, where the
% linear piece is converging to the convex hull of the quadratics. Given
% the index i of the linear piece, it removes it, interpolating the
% quadratics to their intersection point. It returns the new function,
% and the index of the left quadratic piece.
function [plqf, i] = plq_conv_qlq(plqf, i)
j = i + 1;
i = i - 1;
A = plqf(i,2) - plqf(j,2);
B = plqf(i,3) - plqf(j,3);
C = plqf(i,4) - plqf(j,4);
x1 = -plqf(i,4) / plqf(i,3);
x5 = -plqf(j,4) / plqf(j,3);
% Calculate the intersection point.
if A == 0
x = -C/B;
else
D = B*B - 4*A*C;
if D < 0
cerror('_plq_conv_qlq: Unable to intersect parabolas. Impossible case?');
end;
pr = (-B + sqrt(D)) / (2*A);
nr = (-B - sqrt(D)) / (2*A);
if x1 <= pr <= x5
x = pr;
elseif x1 <= nr <= x5
x = nr;
else
cerror('_plq_conv_qlq: Intersection not parabola vertices. Impossible case?');
end;
end;
plqf(i,1) = x;
plqf(i+1,:) = [];
end
|
github
|
ylucet/CCA-master
|
pl_gph.m
|
.m
|
CCA-master/macros/plq/pl_gph.m
| 642 |
utf_8
|
867a7663eb9624b241e590a508509e02
|
%convert the subdifferential of a gph function into a piecewise-linear function
%error out if the graph of the subdifferential is not a function (it is always
%piecewise-linear but may have vertical pieces).
function q = pl_gph(G)
eps=1e-8;
x0 = G(1,1:end-1);x1 = G(1,2:end);
if any(find(abs(x1-x0)<eps))
q=[]; cerror('Unable to convert graph of subdifferential to piecewise-linear function: graph is not a function!');
end;
x = [G(1,2:end-1)';inf];
a = zeros(size(x));
b = (G(2,2:end)-G(2,1:end-1))./ (G(1,2:end)-G(1,1:end-1));%can't divide by zero here because of test above
c = G(2,1:end-1)-b .* x0;
q=[x a b' c'];
end
|
github
|
ylucet/CCA-master
|
plq_eval.m
|
.m
|
CCA-master/macros/plq/plq_eval.m
| 1,332 |
utf_8
|
bc3d1ccabb95e50ed5f888cf94436e04
|
%%%%%%%%%%%%%%EVALUATES A PLQ FUNCTION ON A GRID%%%%%%%%%%%%%%
function [y, k] = plq_eval(plqf,X)
%evaluate a plq function on a grid y=plqf(x),
%x(k(1,l-1))<=X(k(2,l))<=X(k(3,l))<=x(k(1,l)) i.e. k(:,l)=[i;jl;jr]
x=plqf(:,1);a=plqf(:,2);b=plqf(:,3);c=plqf(:,4);
n1=length(x);n=length(X);
if size(X,1)<size(X,2)
X=X';
end;
y=[];k=[];
if (n1 == 1 & x(1) < inf)
j=find(x==X);
y=ones(size(X))*inf;y(j)=c;
return;
end;
if x(n1) ~= inf
s=sprintf('Error in plq_eval: right bound of plqf should be infinity instead of false',x(n1));cerror(s);return;
end;
i=1; jl=1;%left index on X
jr=1;%rigth index on X
while (jl <= n)
while (x(i) < X(jl)), i=i+1;
end;%x(n)=$inf so always get out
jr = jl + 1;
while ((jr <= n) & X(jr) <=x(i)), jr = jr + 1;
end;
if jr > n
jr = n; else jr = jr - 1;
end;
xx = X(jl:jr);
k(:,end+1)=[i;jl;jr];
y = [y; a(i)*xx.^2+b(i)*xx+c(i)];
jl = jr + 1;
i = i + 1;
end;
if k(1,1)==0 & k(2,1)==0 & k(3,1)==0
k(:,1) = [];
end
% k(:,1)=[];%remove 1st colum which is [0;0;0]
if length(y)~=n
s=sprintf('Error in plq_eval: length(X)=i ~= length(y)=i',n,length(y));cerror(s);return;
end;
end
|
github
|
ylucet/CCA-master
|
plq_lft.m
|
.m
|
CCA-master/macros/plq/plq_lft.m
| 2,970 |
utf_8
|
80c07702f7d844e6aac7a4feecb75260
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%PLQ CONJUGATE%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plqfstar = plq_lft(plqf,isConvex)
if nargin<=1
isConvex=false;
end;%default to non-convex functions
if ~isConvex
plqf=plq_co(plqf);
end;
x=plqf(:,1);a=plqf(:,2);b=plqf(:,3);c=plqf(:,4);
n = size(x,1); %number of rows
i=1;%primal index: x(i); scan plqf
j=1; %dual index: s(j); build plqfstar
%special case: Indicator of a point or linear function
if n == 1
if x(i) == inf & a == 0
%LINE - TO - POINT
plqfstar=[b,0,0,-c];return;
elseif x(i) < inf
%POINT - TO - LINE
plqfstar=[inf,0,x,-c];return;
end
end
if c(1) == inf
%domain is left-bounded: add a linear part
s(1) = 2*a(2)*x(1) + b(2);
sa(1) = 0;
sb(1) = x(1);
sc(1) = -a(2)*x(1).^2-b(2)*x(1)-c(2);
j = j + 1;i = i + 1;
elseif a(1)==0
%first part is linear: add infinity + linear part
s(1) = b(1);
sa(1) = 0;
sb(1) = 0;
sc(1) = inf;
s(2) = 2*a(2)*x(1) + b(2);
sa(2) = 0;
sb(2) = x(1);
sc(2)=-b(1)*x(1) - c(1);
%since -b(1)*x(1) - c(1)=-a(2)*x(1).^2-b(2)*x(1)-c(2) the formula is the same as for left-bounded above
j = j + 2;i = i + 1;
end
%Now each line in plqf(i:n-1,:) gives a quadratic part + a linear part
%and each value of i between istart and n-1 gives 2 values for j
jend=2*(n-i)+j-1;%n-i=(n-1)-(i-1)=number of primal values to read; j-1=dual values already added
if jend > j
%when there is a middle part
jq=j:2:jend-1;
jl=j+1:2:jend;
ai=a(i:n-1);xi=x(i:n-1);bi=b(i:n-1);ci=c(i:n-1);t=4*ai;%tmp vars to reduce calculations
sq=2*ai.*xi+bi;saq=t.^(-1);sbq=-2*bi./ t;scq=(bi.^2)./ t-ci;%quadratic part (careful 1./t<>t.^(-1))
sl=2*a(i+1:n).*xi+b(i+1:n);sal=zeros(size(xi));sbl=xi;scl=-ai.*xi.^2-bi.*xi-ci;%linear part
z=zeros(jend-j+1,1);
s(j:jend)=z;sa(j:jend)=z;
sb(j:jend)=z;sc(j:jend)=z;
s(jq)=sq;sa(jq)=saq;sb(jq)=sbq;sc(jq)=scq;
s(jl)=sl;sa(jl)=sal;sb(jl)=sbl;sc(jl)=scl;
j=jend+1;
end;
if c(n) == inf
%domain is right-bounded: add a linear part
s(j) = inf;
sa(j) = 0;
sb(j) = x(n-1);
sc(j) = -a(n-1)*x(n-1).^2-b(n-1)*x(n-1)-c(n-1);
elseif a(n)==0
%last part is linear: add infinity
s(j) = inf;
sa(j) = 0;
sb(j) = 0;
sc(j) = inf;
else %last part is quadratic: add a quadratic
s(j) = 2*a(n)*x(n) + b(n);
sa(j) = 1/(4*a(n));
sb(j) = -b(n)/(2*a(n));
sc(j) = b(n).^2/(4*a(n)) - c(n);%always finite value since a(n)>0
end
j = j + 1;i = i + 1;
plqfstar = plq_clean([ s' , sa' , sb' , sc' ]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%PLQ CONJUGATE%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
ylucet/CCA-master
|
dl_maxoninterval.m
|
.m
|
CCA-master/macros/plq/dl_maxoninterval.m
| 787 |
utf_8
|
59decfa80407d18793aca4e2c2a0c2b9
|
%computes the maximum of two functions under the assumption that difference of q1 - q2 is linear function!!!!!
function [plq,maxq] = dl_maxoninterval(q1,q2,lb,ub,a,b,c)
if b == 0
%horizontal line, i.e. no intersection with the x-axis
plq = maxoninterval(q1,q2,lb,ub,a,b,c);
if (c > 0)
maxq = [1,lb,ub]; else maxq = [2,lb,ub];
end;
else
x = -c/b; %y=bx+c --> find x-intercept 0=bx+c --> x = -c/b
if x <= lb | x >= ub
[plq,i] = maxoninterval(q1,q2,lb,ub,a,b,c);
maxq = [i,lb,ub];
else
[plq_i1,i1] = maxoninterval(q1,q2,lb,x,a,b,c);
[plq_i2,i2] = maxoninterval(q1,q2,x,ub,a,b,c);
plq = [plq_i1;plq_i2];
maxq = [i1,lb,x;i2,x,ub];
end
end;
end
|
github
|
ylucet/CCA-master
|
plq_diff.m
|
.m
|
CCA-master/macros/plq/plq_diff.m
| 156 |
utf_8
|
b6183f2b53373ceab1df8bdf97be2542
|
%compute the piecewise linear derivative of p
%errors out (in pl_gph) if dp is not a function
function dp = plq_diff(p)
G=gph_plq(p);
dp=pl_gph(G);
end%
|
github
|
ylucet/CCA-master
|
plq_pa.m
|
.m
|
CCA-master/macros/plq/plq_pa.m
| 1,125 |
utf_8
|
52476e3ee72032dc09e0feb1c4ec5515
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%PROXIMAL AVERAGE%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pa = plq_pa(f1,f2,lambda_pa,isConvex)
if nargin<=3
isConvex=true;
end;%default to convex functions
pa=[];%default value in case of error
%f[lambda] = (lambda(f1 + (1/2)normsquared)* + (1 - lambda)(f2 + (1/2)normsquared)*)* - (1/2)normsquared
normsquared = [inf, 1/2, 0, 0];
negnormsquared = plq_scalar(normsquared,-1);
f1normsquared = plq_add(f1,normsquared);
f2normsquared = plq_add(f2,normsquared);
f1normsquaredstar = plq_lft(f1normsquared,isConvex);
f2normsquaredstar = plq_lft(f2normsquared,isConvex);
f1normsquaredstarlambda = plq_scalar(f1normsquaredstar,1-lambda_pa);%1-lambda first function
f2normsquaredstarlambda = plq_scalar(f2normsquaredstar,lambda_pa);
f1normsquaredstarlambda=plq_clean(f1normsquaredstarlambda);%remove floating point errors
proxadd = plq_add(f1normsquaredstarlambda,f2normsquaredstarlambda);
proxaddstar = plq_lft(proxadd);
proxaddstar = plq_clean(proxaddstar);
pa = plq_add(proxaddstar,negnormsquared);
end
|
github
|
ylucet/CCA-master
|
plq_gpa.m
|
.m
|
CCA-master/macros/plq/plq_gpa.m
| 372 |
utf_8
|
4ce033348ff00b5b6c66e54118a84053
|
%generalized proximal average from
%W. Hare. A Proximal Average for Nonconvex Functions:
%A Proximal Stability Perspective. SIOPT
function pa = plq_gpa(p0,p1,lambda,r)
pa1 = plq_scalar(plq_me(p0,1/r,false), -(1-lambda));
pa2 = plq_scalar(plq_me(p1,1/r,false), -lambda);
pa=plq_add(pa1,pa2);
pa=plq_me(pa,1/(r+lambda*(1-lambda)),false);
pa=plq_scalar(pa,-1);
end
|
github
|
ylucet/CCA-master
|
plq_maxoninterval.m
|
.m
|
CCA-master/macros/plq/plq_maxoninterval.m
| 1,293 |
utf_8
|
c0803fd5c071801dbaf2a21496257b6e
|
%l1,l2,q1,q2 are all represented by the formar [a,b,c] which represents ax^2 + bx + c
%Each corresponding function will find the maximum function between two functions
%either quadratic-linear, quadratic-quadratic, linear-linear which is valid only
%within the interval [lb,ub] the lower and upper bound.
%main function
%computes the maximum of two functions under the assumption that q1 - q2 is linear or quadratic.
%DOES NOT HANDLE SINGLETON INDICATOR FUNCTIONS.
function [plq,maxq] = plq_maxoninterval(q1,q2,lb,ub)
%printf(" q1=[i,i,i],q2=[i,i,i] lb=i,ub=i",q1(1,1),q1(1,2),q1(1,3),q2(1,1),q2(1,2),q2(1,3),lb,ub);
if all(q1==q2)
plq=[ub,q1]; %printf(" plq_max: [i,i,i,i]",plq(1,1),plq(1,2),plq(1,3),plq(1,4));
maxq=[];
return;
end;
%to find where q1 > q2 find where (q1 - q2) > 0
dlq = (q1 - q2); %WARNING: the difference of two quadratics is linear! or quadratic!
a=dlq(1,1);b=dlq(1,2);c=dlq(1,3);
if a == 0
%dlq is linear
[plq,maxq] = dl_maxoninterval(q1,q2,lb,ub,a,b,c); %printf(" plq_max: [i,i,i,i]",plq(1,1),plq(1,2),plq(1,3),plq(1,4));
else
%dlq is quadratic
[plq,maxq] = dq_maxoninterval(q1,q2,lb,ub,a,b,c); %printf(" plq_max: [i,i,i,i] Q",plq(1,1),plq(1,2),plq(1,3),plq(1,4));
end
end
|
github
|
ylucet/CCA-master
|
dq_maxoninterval.m
|
.m
|
CCA-master/macros/plq/dq_maxoninterval.m
| 2,316 |
utf_8
|
b48229058294bd7a7a72ba75df6ebe1f
|
%computes the maximum of two functions under the assumption that the difference of q1 - q2 is quadratic!!!!!
function [plq,maxq] = dq_maxoninterval(q1,q2,lb,ub,a,b,c)
delta = b.^2 - 4*a*c; %calculating the discriminant of the quadratic
%printf(" a:
if delta > 0
%there are two real roots
%finding the zeros of qd
x(1) = (-b - sqrt(delta))/(2*a);
x(2) = (-b + sqrt(delta))/(2*a);
x = sort([x]);
if (x(1) < lb & x(2) > ub) | (x(1) > ub & x(2) > ub) | (x(1) < lb & x(2) < lb)
%both zeros are outside our interval
%plq = maxoninterval(q1,q2,dq,lb,ub);
[plq,i] = maxoninterval(q1,q2,lb,ub,a,b,c);
maxq = [i,lb,ub];
elseif x(1) >= lb & x(2) <= ub
%both zeros are inside our interval (NOTE: x(1),x(2) are sorted)
[plq_i1,i1] = maxoninterval(q1,q2,lb,x(1),a,b,c);
[plq_i2,i2] = maxoninterval(q1,q2,x(1),x(2),a,b,c);
[plq_i3,i3] = maxoninterval(q1,q2,x(2),ub,a,b,c);
plq = [plq_i1;plq_i2;plq_i3];
maxq = [i1,lb,x(1);i2,x(1),x(2);i3,x(2),ub];
elseif x(1) >= lb & x(1) <= ub
%only left root inside interval
[plq_i1,i1] = maxoninterval(q1,q2,lb,x(1),a,b,c);
[plq_i2,i2] = maxoninterval(q1,q2,x(1),ub,a,b,c);
plq = [plq_i1;plq_i2];
maxq = [i1,lb,x(1);i2,x(1),ub];
else %only right root inside interval
[plq_i1,i1] = maxoninterval(q1,q2,lb,x(2),a,b,c);
[plq_i2,i2] = maxoninterval(q1,q2,x(2),ub,a,b,c);
plq = [plq_i1;plq_i2];
maxq = [i1,lb,x(2);i2,x(2),ub];
end
elseif delta < 0
%there are 2 complex roots (No real roots)
[plq,i] = maxoninterval(q1,q2,lb,ub,a,b,c);
maxq = [i,lb,ub];
else %delta = 0 then there is 1 real root
x(1) = (-b + sqrt(delta))/(2*a);
if x(1) <= lb | x(1) >= ub
%the root is outside our lower and upper bound
[plq,i] = maxoninterval(q1,q2,lb,ub,a,b,c);
maxq = [i,lb,ub];
else %zero is inside the interval
[plq,i] = maxoninterval(q1,q2,lb,x(1),a,b,c);
plq(1,1) = ub; %since the quadratic is tangent to the x-axis, we know that it does not cut the axis
maxq = [i,lb,ub];
end
end
end
|
github
|
ylucet/CCA-master
|
plq_isEqual.m
|
.m
|
CCA-master/macros/plq/plq_isEqual.m
| 912 |
utf_8
|
ec1209d3ad6cdaaae0b413ff85b65343
|
%test whether 2 plq functions are equal
%use the clean function to round small values
%and contrary to the isEqual function compacts small intervals
function b = plq_isEqual(p1,p2)
%remove common inf values to prevent inf-inf=NaN
isP1inf=(p1(end,1)==inf);
isP2inf=(p2(end,1)==inf);
large=realmax;
i1=find(p1==inf);
i2=find(p2==inf);
p1(i1)=large;
p2(i2)=large;
i1=find(p1==-inf);
i2=find(p2==-inf);
p1(i1)=-large;
p2(i2)=-large;
%restore plq format without screwing indicator of a point special case
if isP1inf
p1(end,1)=inf;
end;
if isP2inf
p2(end,1)=inf;end
%compute difference of both functions and test it is the zero function
q = plq_clean(plq_add(p1,plq_scalar(p2,-1)));
if all([size(p1,1)==1,size(p2,1)==1,~isinf(p1(1,1)),~isinf(p2(1,1))])
%SPECIAL CASE: 2 indicators of singleton
b = norm(p1-p2) < 1E-6;
else
b = all(q==[inf 0 0 0]);
end
end
|
github
|
ylucet/CCA-master
|
plq_prox.m
|
.m
|
CCA-master/macros/plq/plq_prox.m
| 624 |
utf_8
|
952b3b805996a1c6b734ec8965dc749b
|
%compute the proximal mapping of a PLQ function
%from the graph of the subdifferential
%only works for convex functions
function q=plq_prox(p,alpha)
eps=1e-8;
if alpha<0
cerror('alpha must be nonnegative');
end;
G = gph_plq(p);
P = [1 alpha;1 0] * G(1:2,:);
P(3,:)=zeros(size(1,size(P,2)));
q = pl_gph(P);
% %TO DO
% if n==2 & abs(g(1,1)-g(1,2))<eps then%singleton indicator
% h=g(1:2,:);
% h(3,:)=alpha*g(3,:);
% else
% i=find(g==inf);
%
% h = [1 alpha;1 0] * g(1:2,:);
% %multiply 3rd row (values of f) alone to avoid 0*inf giving % h(3,:)=alpha*g(3,:);
% h(i)=inf;
% end
end
|
github
|
ylucet/CCA-master
|
mikeplq_lft.m
|
.m
|
CCA-master/macros/plq/mikeplq_lft.m
| 2,485 |
utf_8
|
4a8a376c96a6cdc8dbca409bb0666fd2
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%PLQ CONJUGATE%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plqfstar = mikeplq_lft(plqf)
x=plqf(:,1);a=plqf(:,2);b=plqf(:,3);c=plqf(:,4);
n = size(x,1); %number of rows
i=1;j=1;
while i <= n,
plqType = getType(n,x,a,b,c,i);
switch plqType,
case 6
%BOUNDED RHS
s(i) = inf;
sa(i) = 0;
sb(i) = x(i-1);
sc(i) = (-1)*a(i-1)*x(i-1).^2-b(i-1)*x(i-1)-c(i-1);
j = j + 1;
case 5
%BOUNDED LHS
s(i) = 2*a(i+1)*x(i) + b(i+1);
sa(i) = 0;
sb(i) = x(i);
sc(i) = (-1)*a(i+1)*x(i).^2-b(i+1)*x(i)-c(i+1);
j = j + 1;
case 3
%LINE - TO - POINT
s(i) = b(i);sa(i) = 0;sb(i) = 0;sc(i) = -c(i);
case 4
%POINT - TO - LINE
s(i) = inf;sa(i) = 0;sb(i) = x(i);sc(i) = -c(i);
case 1
%linear - TO - quadratic or linear
%first row of conjugate matrix
if i < n
s(j) = b(i);
else
s(j) = inf;
end
sa(j) = 0;sb(j) = 0;sc(j) = inf;
%second row of conjugate matrix
if i < n
if s(j) < 2*a(i+1)*x(i) + b(i+1)
s(j+1) = 2*a(i+1)*x(i) + b(i+1);
sa(j+1) = 0;
sb(j+1) = x(i);
sc(j+1) = (-1)*b(i)*x(i) - c(i);
j = j + 2;
else j = j + 1;
end
end
case 2
%quadratic - TO - quadratic or linear
%first row of conjugate matrix
if i < n
s(j) = 2*a(i)*x(i) + b(i);
else
s(j) = inf;
end
sa(j) = 1/(4*a(i));
sb(j) = (-1/2)*(b(i)/a(i));
sc(j) = (1/4)*(b(i)*b(i))/a(i) - c(i); %potential for infinity value
%second row of conjugate matrix
if (i < n)
if s(j) < 2*a(i+1)*x(i) + b(i+1)
s(j+1) = 2*a(i+1)*x(i) + b(i+1);
sa(j+1) = 0;
sb(j+1) = x(i);
sc(j+1) = -a(i)*x(i)*x(i) - b(i)*x(i) - c(i);
j = j + 2;
else j = j + 1;
end
end
end
i = i + 1;
end
plqfstarDirty = [ s' , sa' , sb' , sc' ];
plqfstar = plq_clean(plqfstarDirty);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%PLQ CONJUGATE%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
ylucet/CCA-master
|
plq_clean.m
|
.m
|
CCA-master/macros/plq/plq_clean.m
| 2,258 |
utf_8
|
dc8dc83b379d4c42cedca04b558f4848
|
%%%%%%%%%PLQ CONJUGATE HELPER FUNCTION%%%%%%%%%%%%%
function [plqClean] = plq_clean(plqDirty)
eps=1E-6;%1E-6;precision below which numbers are rounded to zero
% a Temporary Vector or matrix to check presence of infinite
dplq=plqDirty(2:end-1,:)-plqDirty(1:end-2,:);
%clear duplicate point values e.g [0,1,0,1;0,2,0,0] -> [0,1,0,1]
j1=find(abs(dplq(:,1))<eps);%delete j1+1
if length(j1)>0
plqDirty(j1+1,:)=[];
end;
dplq=plqDirty(2:end,:)-plqDirty(1:end-1,:);
%clear duplicate rows e.g. [0,1,0,0;0,1,0,0]->[0,1,0,0]
if size(dplq,1)==1
tempnum = dplq(1,2:end); %Since norm doesn't take infinite argument, replace it with a large number
knan = isnan(tempnum);
kinf = isinf(tempnum);
tempnum(knan) = 1E10;
tempnum(kinf) = 1E10;
if norm(tempnum)<eps
plqDirty(1,:)=[];
end;
else
m=abs(dplq(:,2:end))*ones(size(dplq(:,2:end), 2), 1);
n=abs(plqDirty(1:end-1,2:end))*ones(size(plqDirty(1:end-1,2:end), 2), 1);
i=find(n==inf | n==0);n(i)=1;%no division by inf
m=m./ n;%use relative error
j2=find(m<eps);
plqDirty(j2,:)=[];
end
%round small numbers to zero
%this should be done by the clean function
%but clean is buggy when the matrix contains inf
%P1=plqDirty(:,2:$)
P1=plqDirty;
P=reshape(P1,[numel(P1), 1]);
ni=find(abs(P)<eps);
P(ni)=0;
P1=reshape(P,size(P1));
%plqDirty(:,2:$)=P1;
plqDirty=P1;
%Mike
%Addition of infinity values results in functions like
% [x x x x]
% [x x x inf]
% [x x x xinf]
% [inf x x inf]
%However it is properly represented as
% [x x x x]
% [inf x x inf]
%The following lines of code remove the redundant infinity rows.
plqInf = plq_rowalwaysinf(plqDirty);
[rs,cs] = find(all([plqInf(1:end-1,:), plqInf(2:end,:)], 2));
if (size(rs,1) ~= 0)
plqDirty(rs+1,2:end-1) = 0; % If rs==[], then rs+1==[1],
plqDirty(rs,:) = []; % we want rs+1==[], hence the if.
end
%bounded domains are represented as x0,0,0,inf so force the zeros in
if (plqDirty(1,4)==inf)
plqDirty(1,2:3)=0;
end;
%(same for xn,0,0,inf)
if (plqDirty(end,4)==inf)
plqDirty(end,2:3)=0;
end;
plqClean = plqDirty;
end
%%%%%%%%%PLQ CONJUGATE HELPER FUNCTION%%%%%%%%%%%%%
|
github
|
ylucet/CCA-master
|
conv_interval_func.m
|
.m
|
CCA-master/macros/plq/conv_interval_func.m
| 2,426 |
utf_8
|
d8db504dd85cad8da52b3d2ab26d23e4
|
%The following routine solves [PROBLEM 2.].
function [plqco] = conv_interval_func(x,a,b,c,x1,x3,x5),
EPS=1E-10; x(1)=x1;x(3)=x3;x(5)=x5;
%solving the quadratic for x(2)
if a(1) ~= 0 & x(5) < inf
A1 = -a(1);
B1 = 2*a(1)*x5;
C1 = c(1) + b(1)*x5 - a(2)*x5.^2 - b(2)*x5 - c(2);
D1 = B1.^2 - 4*A1*C1;
if D1<0
printf('D1<0 in _conv_interval_func');
pause
cerror('_conv_interval_func: D1<0. Is your function continuous on ri dom?');
end
pr1 = (-B1 + sqrt(D1))/(2*A1); %solution is x2
nr1 = (-B1 - sqrt(D1))/(2*A1); %negative root required for the LINEAR-QUADRATIC CASE.
if x(1) <= pr1 & pr1 <= x(3)
x(2) = pr1; plqco=[x(2),a(1),b(1),c(1);
plq_conv_buildl(x,a,b,c,1,2,2,5)];
elseif x(3) <= pr1 & pr1 <= x(5)
x(4)=pr1; plqco=[plq_conv_buildl(x,a,b,c,1,1,2,4);x(5),a(2),b(2),c(2)]; %potentially useless
elseif x(1) <= nr1 & nr1 <= x(3)
x(2) =pr1; plqco=[x(2),a(1),b(1),c(1);plq_conv_buildl(x,a,b,c,1,2,2,5)];
elseif x(3) <= nr1 & nr1 <= x(5)
x(4)=pr1; plqco=[plq_conv_buildl(x,a,b,c,1,1,2,4);x(5),a(2),b(2),c(2)]; %potentially useless
else plqco=plq_conv_buildl(x,a,b,c,1,1,2,5);
end;
%solving the quadratic for x(4)
%elseif a(2) <> 0 & x(1) > -inf & x(5) < inf then
elseif a(2) ~= 0 & x(1) > -inf
A2 = a(2);
B2 = -2*a(2)*x(1);
C2 = -b(2)*x(1) + a(1)*x(1).^2 + b(1)*x(1) + c(1) - c(2);
D2 = B2.^2 - 4*A2*C2;
pr2 = (-B2 + sqrt(D2))/(2*A2);
nr2 = (-B2 - sqrt(D2))/(2*A2);
if x(3) <= pr2 & pr2 <= x(5)
x(4)=pr2; plqco=[plq_conv_buildl(x,a,b,c,1,1,2,4);x(5),a(2),b(2),c(2)];
elseif x(1) <= pr2 & pr2 <= x(3)
x(2)=pr2; plqco=[x(2),a(1),b(1),c(1);plq_conv_buildl(x,a,b,c,1,2,2,5)]; %potentially useless
elseif x(3) <= nr2 & nr2 <= x(5)
x(4)=nr2; plqco=[plq_conv_buildl(x,a,b,c,1,1,2,4);x(5),a(2),b(2),c(2)];
elseif x(1) <= nr2 & nr2 <= x(3)
x(2)=nr2; plqco=[x(2),a(1),b(1),c(1);plq_conv_buildl(x,a,b,c,1,2,2,5)]; %potentially useless
else plqco=plq_conv_buildl(x,a,b,c,1,1,2,5);
end;
else plqco=plq_conv_buildl(x,a,b,c,1,1,2,5);
end;
end
|
github
|
ylucet/CCA-master
|
maxoninterval.m
|
.m
|
CCA-master/macros/plq/maxoninterval.m
| 628 |
utf_8
|
ef4a1cb5891e30edc2832b2b459545fd
|
%calculates the max between two functions that do not intersect within the given interval.
function [plq,i] = maxoninterval(q1,q2,lb,ub,a,b,c)
if all(isinf([lb,ub]))
m=0;%pick any point
else%at most one bound is infinite
lb1=lb;ub1=ub;
if lb==-inf
lb1=ub-1;
end;
if ub==inf
ub1=lb+1;
end;
m=(lb1+ub1)/2;%midpoint
end;
%printf(" Maxoninterval: q1=[
if a*m.^2+b*m+c > 0
plq = [ub,q1]; i = 1; %assumes (q1 - q2) = qld
else
plq = [ub,q2];
i = 2;
end;
end
%%%%%%%%%%%%FINDS THE MAXIMUM OF TWO PLQ FUCNTIONS%%
|
github
|
ylucet/CCA-master
|
getType.m
|
.m
|
CCA-master/macros/plq/getType.m
| 646 |
utf_8
|
b963a76342ad79eed66b859448a50f81
|
%%%%%%%%%PLQ CONJUGATE HELPER FUNCTION%%%%%%%%%%%%%
function plqType=getType(n,x,a,b,c,i)
if a(i) == 0
plqType = 1;%part is linear
else plqType = 2;%part is quadratic
end
if n == 1 & x(i) == inf & a(i) == 0
plqType = 3;%LINE - TO - POINT
elseif n == 1 & x(i) < inf
%POINT - TO - LINE
plqType = 4;
end
if a(i) == inf | b(i) == inf | c(i) == inf & i == 1
plqType = 5; %Bounded by the LHS
end
if a(i) == inf | b(i) == inf | c(i) == inf & i == size(x,1)
plqType = 6; %Bounded by the RHS
end
end
%%%%%%%%%PLQ CONJUGATE HELPER FUNCTION%%%%%%%%%%%%%
|
github
|
ylucet/CCA-master
|
plq_scalar.m
|
.m
|
CCA-master/macros/plq/plq_scalar.m
| 727 |
utf_8
|
560ba03ddd66d62e121fe08f9ee1358e
|
%%%%%%%%%%%%%%PLQ SCALAR MULTIPLCATION FUNCTION%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function q = plq_scalar(p,lambda)
%avoid 0 * inf
i=find(p==inf);j=find(p==-inf);
q = [p(:,1), lambda*p(:,2:4)];
%restore inf values;
if lambda >= 0
q(i)=inf;
else
q(i)=-inf;
%careful not to mess up indicator of singleton
if p(end,1)==inf
q(end,1)=inf;
end;
end;
if lambda >= 0
q(j)=-inf; else q(j)=inf;
end;
%need to clean AFTER restauring values otherwise the index i
%does not correspond to the cleaned matrix that may have less rows.
q = plq_clean(q);
end
%%%%%%%%%%%%%%PLQ SCALAR MULTIPLCATION%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
ylucet/CCA-master
|
plq_conv_on_interval.m
|
.m
|
CCA-master/macros/plq/plq_conv_on_interval.m
| 3,520 |
utf_8
|
136f014a8ae025791037254a1c77f4f4
|
%We assume x(1) < x(2) < x(3) < x(4) < x(5) are ordered and finite (no infinity values).
%In creating the PLQ hull we may need to create points x(2) and x(4).
%Note that x(1) is the LEFTBOUND, x(3) is the partition point, and x(5) is the RIGHTBOUND in our PLQ interval.
%_plq_conv_on_interval finds the convex hull on the interval [x1,x5].
function [plqco] = plq_conv_on_interval(f1,f2,x1,x3,x5) %Assume f1 is to the left of f2
x(1) = x1; a(1)=f1(1,2); a(2)=f2(1,2);
x(3) = x3; b(1)=f1(1,3); b(2)=f2(1,3);
x(5) = x5; c(1)=f1(1,4); c(2)=f2(1,4);
plqco=[];
if a(1) < 0
%concave down pieces are simply replaced by a linear function.
f1=plq_conv_buildl(x,a,b,c,1,1,1,3);
f2=[x(5),a(2),b(2),c(2)];
plqco=plq_conv_on_interval(f1,f2,x(1),x(3),x(5));
elseif a(2) < 0
f1=[x(3),a(1),b(1),c(1)];
f2=plq_conv_buildl(x,a,b,c,2,5,2,3);
plqco=plq_conv_on_interval(f1,f2,x(1),x(3),x(5));
elseif 2*a(1)*x(3)+b(1) <= 2*a(2)*x(3)+b(2)
%trivial case
plqco=[x(3),a(1),b(1),c(1);x(5),a(2),b(2),c(2)];
elseif a(1) == 0 & a(2) == 0
%(LINEAR-LINEAR) f1 is linear and f2 is linear.
[plqco]=plq_conv_buildl(x,a,b,c,1,1,2,5);
elseif a(1) == 0 & a(2) ~= 0
% (LINEAR-QUDARTIC) if f1 is linear and f2 is quadratic then x(4) is determined.
plqco=[conv_interval_func(x,a,b,c,x1,x3,x5)];
elseif a(1) ~= 0 & a(2) == 0
% (QUADRATIC-LINEAR) if f1 is quadratic and f2 is linear then x(2) is determined.
plqco=[conv_interval_func(x,a,b,c,x1,x3,x5)];
elseif a(1) ~= 0 & a(2) ~= 0
% (QUADRATIC-QUADRATIC) if f1 is quadratic and f2 is quadratic we need to find solutions to A*x(4)^2 + B*x(4) + C.
%The following code solves [PROBLEM 1.],
A=(1/4)*(-4*a(2).^2+4*a(2)*a(1))/a(1);
B=(1/4)*(-4*a(2)*b(2)+4*b(1)*a(2))/a(1);
C=(1/4)*(-b(2).^2-b(1).^2+4*c(1)*a(1)+2*b(1)*b(2)-4*c(2)*a(1))/a(1);
D = B.^2 - 4*A*C; %Discriminant.
%printf("QUADRATIC-QUADRATIC CASE: Solving
if A == 0
%Linear case, so we have Bx+C=0 with one zero.
x(4) = (-C/B);
x(2) = (-1/2)*(b(1)-2*a(2)*x(4)-b(2))/a(1);
if x(2) < x(1) | x(3) < x(2)
x(2)=inf;
end;
if x(4) < x(3) | x(4) > x(5)
x(4)=inf;
end;
%and thus we should just ignore them. Similarly if D < 0, just ignore x(2) and x(4) as they don't help with the hull.
else % A <> 0, Quadratic case, so we have Ax^2+Bx+C=0, with one or two zeros. Solving for x(4).
if D>0
nr = (-B - sqrt(D))/(2*A); %negative root
pr = (-B + sqrt(D))/(2*A); %positive root
if D==0
nr=pr;
end;
if x(3) < pr & pr < x(5)
x(4) = pr;
elseif x(3) < nr & nr < x(5)
x(4) = nr; %printf(" NEGATIVE ROOT ");
else x(4)=inf; end;
x(2) = (-1/2)*(b(1)-2*a(2)*x(4)-b(2))/a(1);
if x(1) > x(2) | x(2) > x(3)
x(2)=inf;
end;
else
x(2)=inf; x(4)=inf;
end
end
if x(2) < inf & x(4) < inf
plqco=[x(2),a(1),b(1),c(1);plq_conv_buildl(x,a,b,c,1,2,2,4);x(5),a(2),b(2),c(2)];
else %x(2) == inf | x(4) == inf,
%Here we solve the SECOND PROBLEM: as x(2) or x(4) is infeasible in [PROBLEM 1.]
plqco=[conv_interval_func(x,a,b,c,x1,x3,x5)];
end;
else cerror('Case does not exist.');
end
end
|
github
|
ylucet/CCA-master
|
plq_me.m
|
.m
|
CCA-master/macros/plq/plq_me.m
| 1,423 |
utf_8
|
14d93a30667f540fc25fed4ab4f9638b
|
%%%%%%%%%%%%%%PIECEWISE LINEAR QUADRATIC MOREAU ENVELOPE (WRAPPER) %%%%%%%%%%%%%%
function plqme = plq_me(plqf,lambda,isConvex)
if nargin<=2
isConvex=false;
end;%default to non-convex functions
a = plqf(:,2);
if (lambda < 0 | a(1) < 0 | a(end) < 0)
maxScale = plq_me_max_scale(plqf);
if (lambda < 0 | lambda > maxScale)
cerror(sprintf('plq_me(): Scale false should be in (0,false].', lambda, maxScale));
plq_me = [];
return;
end;
end;
% x=plqf(:,1);a=plqf(:,2);b=plqf(:,3);c=plqf(:,4);
% % if size(x,1) == 1 & x(1) ~= inf then %we have an indicator function of a point [x, 0, 0, c] where x is the horizontal pos, and c is the height.
% printf("plq_me of indicator:");
% disp(plqf);
% plqf = [x, 0, 0, a*x^2 + b*x + c];
% plqf = [x, lambda*a, lambda*b, lambda*c + (1/2)*x^2];
% else
% printf("plq_me of function:");
% disp(plqf);
% plqf = [x, lambda*a + (1/2), lambda*b, lambda*c];
% end
plqme = plq_scalar(plqf,lambda);
plqme = plq_add(plqme,[inf,1/2,0,0]);
plqme = plq_lft(plqme,isConvex);
sx=plqme(:,1);sa=plqme(:,2);sb=plqme(:,3);sc=plqme(:,4);
% plqme = [sx, (-1/lambda)*sa + (1/(2*lambda)), (-1/lambda)*sb, (-1/lambda)*sc];
plqme = plq_scalar(plqme,-1);
plqme = plq_clean(plqme);%make sure x is increasing
plqme = plq_add(plqme,[inf,1/2,0,0]);
plqme = plq_scalar(plqme,1/lambda);
end
|
github
|
ylucet/CCA-master
|
plq_rowalwaysinf.m
|
.m
|
CCA-master/macros/plq/plq_rowalwaysinf.m
| 324 |
utf_8
|
ed134c2e4377a82b7305df411e88ad48
|
% A polynomial is always infinite if a and b are not infinite
% and not NaN, and c is infinite.
function [alwaysinf, sgn] = plq_rowalwaysinf(plqf)
alwaysinf = ~(any(isinf(plqf(:,2:end-1)), 2) ......
| any(isnan(plqf(:,2:end-1)), 2)) ......
& isinf(plqf(:,end));
sgn = sign(plqf(:,end));
end
|
github
|
ylucet/CCA-master
|
plq_co.m
|
.m
|
CCA-master/macros/plq/plq_co.m
| 394 |
utf_8
|
84a6438464a1bd8dadfd7a74e702d207
|
%%%%%%%%%%PLQ CONVEX HULL%%%%%%%%%%%%%%%%%%%%%%%%
%TODO, (1) UPDATE PLQ_EVAL FOR NONCONVEX FUNCTIONS?.
% (2) UPDATE PLQ_BUILD FOR NONCONVEX FUNCTIONS.
function plqco = plq_co(plqf, method)
% Allowed values for method: direct, split.
if nargin < 2
method = 'direct';
end;
if method == 'direct'
plqco = plq_coDirect(plqf);
else
plqco = plq_coSplit(plqf);
end;
end
|
github
|
ylucet/CCA-master
|
soqs_build.m
|
.m
|
CCA-master/macros/soqs/soqs_build.m
| 5,023 |
utf_8
|
5d3ade6e9a1bf1f46c923cddfcac3598
|
% _soqs_build
%
% Builds a Shape-Preserving Osculatory Quadratic Spline (soqs) going
% through (x,f(x)) with derivative df(x) at (x,f(x)).
%
% The code is taken partially from Algorithm 574: Shape-Preserving
% Osculatory Quadratic Splines, Feb. 4, 1981 with permission from the
% Association for Computing Machinery (ACM).
%x, f, df are vectors such that f=f(x) and df=f'(x)
%extrapolate: take values: 'constant': extrapolate by a constant,
% 'bounded': bounded domain (extrapolate by inf)
function spline=soqs_build(x,f,df,extrapolate)
n=max(size(x));
spline(1,:)=[x(1),0,0,f(1)];%constant extrapolation
for i=1:n-1;
M1=df(i);
M2=df(i+1);
P1=x(i);
P2=f(i);
Q1=x(i+1);
Q2=f(i+1);
% Determine the case
Case=soqs_choose(P1,P2,M1,M2,Q1,Q2,2.20D-16);
% Calculate parameters
Z1=0;
ZTWO=0;
V1=0;
V2=0;
W1=0;
W2=0;
Z2=0;
if Case==1
Z1=(P2-Q2+M2*Q1-M1*P1)/(M2-M1);
ZTWO = P2 + M1*(Z1-P1);
V1 = (P1+Z1)/2;
V2 = (P2+ZTWO)/2;
W1 = (Z1+Q1)/2;
W2 = (ZTWO+Q2)/2;
Z2 = V2 + ((W2-V2)/(W1-V1))*(Z1-V1);
elseif Case==2
Z1 = (P1+Q1)/2;
V1 = (P1+Z1)/2;
V2 = P2 + M1*(V1-P1);
W1 = (Z1+Q1)/2;
W2 = Q2 + M2*(W1-Q1);
Z2 = (V2+W2)/2;
else
C1 = P1 + (Q2-P2)/M1;
D1 = Q1 + (P2-Q2)/M2;
H1 = 2*C1 - P1;
J1 = 2*D1 - Q1;
MBAR1 = (Q2-P2)/(H1-P1);
MBAR2 = (P2-Q2)/(J1-Q1);
if Case==3
K1 = (P2-Q2+Q1*MBAR2-P1*MBAR1)/(MBAR2-MBAR1);
if (abs(M1)>abs(M2))
Z1=(K1+P1)/2;
else
Z1=(K1+Q1)/2;
end;
V1 = (P1+Z1)/2;
V2 = P2 + M1*(V1-P1);
W1 = (Q1+Z1)/2;
W2 = Q2 + M2*(W1-Q1);
Z2 = V2 + ((W2-V2)/(W1-V1))*(Z1-V1);
else
Y1 = (P1+C1)/2;
V1 = (P1+Y1)/2;
V2 = M1*(V1-P1) + P2;
Z1 = (D1+Q1)/2;
W1 = (Q1+Z1)/2;
W2 = M2*(W1-Q1) + Q2;
MBAR3 = (W2-V2)/(W1-V1);
Y2 = MBAR3*(Y1-V1) + V2;
Z2 = MBAR3*(Z1-V1) + V2;
E1 = (Y1+Z1)/2;
E2 = MBAR3*(E1-V1) + V2;
end;
end;
% calculate Bernstein coefficients according to case
if Case==1 | Case==2 | Case==3
a=(P2+Z2-2*V2)/(Z1-P1).^2;
b=(-2*P2*Z1+2*V2*P1+2*V2*Z1-2*Z2*P1)/(Z1-P1).^2;
c=(P2*Z1.^2+Z2*P1.^2-2*V2*P1*Z1)/(Z1-P1).^2;
spline(end+1,:)=[Z1,a,b,c];
a=(-2*W2+Z2+Q2)/(Q1-Z1).^2';
b=(-2*Z2*Q1+2*W2*Z1+2*W2*Q1-2*Q2*Z1)/(Q1-Z1).^2;
c=(Z2*Q1.^2+Q2*Z1.^2-2*W2*Z1*Q1)/((Q1-Z1).^2);
spline(end+1,:)=[Q1,a,b,c];
else
a=(-2*V2+P2+Y2)/(Y1-P1).^2;
b=(-2*P2*Y1+2*V2*P1+2*V2*Y1-2*Y2*P1)/(Y1-P1).^2;
c=(P2*Y1.^2+Y2*P1.^2-2*V2*P1*Y1)/(Y1-P1).^2;
spline(end+1,:)=[Y1,a,b,c];
a=(-2*E2+Y2+Z2)/(Z1-Y1).^2';
b=(-2*Y2*Z1+2*E2*Y1+2*E2*Z1-2*Z2*Y1)/(Z1-Y1).^2;
c=(Y2*Z1.^2+Z2*Y1.^2-2*E2*Y1*Z1)/((Z1-Y1).^2);
spline(end+1,:)=[Z1,a,b,c];
a=(-2*W2+Z2+Q2)/(Q1-Z1).^2';
b=(-2*Z2*Q1+2*W2*Z1+2*W2*Q1-2*Q2*Z1)/(Q1-Z1).^2;
c=(Z2*Q1.^2+Q2*Z1.^2-2*W2*Z1*Q1)/((Q1-Z1).^2);
spline(end+1,:)=[Q1,a,b,c];
end;
end;
spline(end+1,:)=[inf,0,0,f(n)];%constant extrapolation
switch (extrapolate)
case 'constant'
%constant outside of domain (nothing to do)
case 'bounded'
%bounded domain: inf outside of domain
spline(1,4)=inf;
spline(end,4)=inf;
otherwise
cerror(sprintf('Unknown option end '))
end
end
|
github
|
ylucet/CCA-master
|
soqs_choose.m
|
.m
|
CCA-master/macros/soqs/soqs_choose.m
| 3,372 |
utf_8
|
5050d77efb4aae22c93013e66d0cb794
|
% _soqs_choose
%
% Auxillary function for _soqs_build to determine the type of spline
% regarding derivative slopes and distances between the spline end points.
%
% The code is taken partially from Algorithm 574: Shape-Preserving
% Osculatory Quadratic Splines, Feb. 4, 1981 with permission from the
% Association for Computing Machinery (ACM).
function NCASE=soqs_choose(P1,P2,M1,M2,Q1,Q2,eps)
% Initialization
PROD=0;
PROD1=0;
PROD2=0;
MREF=0;
MREF1=0;
MREF2=0;
NCASE=0;
% Calculate the slope SPQ if the line joining (P1,P2),(Q1,Q2)
SPQ = (Q2-P2)/(Q1-P1);
if SPQ==0
if M1*M2<0
NCASE=1;
else
NCASE=2;
end;
return;
else
PROD1=SPQ*M1;
PROD2=SPQ*M2;
MREF=abs(SPQ);
MREF1=abs(M1);
MREF2=abs(M2);
% if the relative deviation of M1 or M2 from SPQ is
% less than eps, then choose case 2 or case 3.
if ((abs(SPQ-M1)>eps*MREF)&(abs(SPQ-M2)>eps*MREF))
if (PROD1>=0 & PROD2>=0)
PROD=(MREF-MREF1)*(MREF-MREF2);
if (PROD<0)
% L1 and L2 intersect inside [P1,Q1]
NCASE=1;
return;
end;
end;
end;
if ((PROD1 < 0)|(PROD2 < 0))
% the sign of at least one of the slopes M1,M2
% does not agree with the sign of the slope SPQ
if (PROD1 < 0) & (PROD2 < 0)
NCASE=2;
return;
end;
if (PROD1 < 0)
if (MREF2 > (1+eps)*MREF)
NCASE=1;
else
NCASE=2;
end;
return;
else
if (MREF1 > (1+eps)*MREF)
NCASE=1;
else
NCASE=2;
end;
return;
end;
end;
if (MREF1 > 2*MREF)
if (MREF2 > (2-eps)*MREF)
NCASE=4;
else
NCASE=3;
end;
return;
end;
if (MREF2 > 2*MREF)
if (MREF1 > (2-eps)*MREF)
NCASE=4;
else
NCASE=3;
end;
return;
end;
NCASE=2;
return;
end;
end
|
github
|
ylucet/CCA-master
|
soqs_slopes.m
|
.m
|
CCA-master/macros/soqs/soqs_slopes.m
| 2,680 |
utf_8
|
aac2eddc8af85ce3b7b288e83cabd628
|
% _soqs_slopes
%
% Auxillary function for _soqs_build to calculate the derivative at each
% data point. The slopes provided will insure that an osculatory
% quadratic spline will have one additional knot between two adjacent
% points of interpolation. Convexity and monotonicity are preserved
% wherever these conditions are compatible with the data.
%
% The code is taken partially from Algorithm 574: Shape-Preserving
% Osculatory Quadratic Splines, Feb. 4, 1981 with permission from the
% Association for Computing Machinery (ACM).
%
% XTAB contains the abscissas of the data points
% YTAB contains the ordinates of the data points
% MTAB contains the value of the first derivative at each data point
function MTAB=soqs_slopes(XTAB,YTAB)
NUM = max(size(XTAB));
NUM1 = NUM - 1;
IM1 = 1;
I = 2;
I1 = 3;
% Calculate the slopes of the two lines joining the first three data points.
YDIF1 = YTAB(2) - YTAB(1);
YDIF2 = YTAB(3) - YTAB(2);
M1 = YDIF1/(XTAB(2)-XTAB(1));
M1S = M1;
M2 = YDIF2/(XTAB(3)-XTAB(2));
M2S = M2;
while (1)
% if one of the preceding slopes is zero or if they have opposite
% sign, assign the value zero to the derivative at the middle point.
if (M1==0|M2==0|(M1*M2)<0)
MTAB(I) = 0;
else
if (abs(M1)>abs(M2))
% calculate the slope by extending the line with slope M1
XBAR = (YDIF2/M1) + XTAB(I);
XHAT = (XBAR+XTAB(I1))/2;
MTAB(I) = YDIF2/(XHAT-XTAB(I));
else
% calculate the slope by extending the line with slope M2
XBAR = (-YDIF1/M2) + XTAB(I);
XHAT = (XTAB(IM1)+XBAR)/2;
MTAB(I) = YDIF1/(XTAB(I)-XHAT);
end;
end;
% increment counters
IM1 = I;
I = I1;
I1 = I1 + 1;
if (I > NUM1)
break;
end;
% Calculate the slopes of the two lines joining three consecutive
% data points.
YDIF1 = YTAB(I) - YTAB(IM1);
YDIF2 = YTAB(I1) - YTAB(I);
M1 = YDIF1/(XTAB(I)-XTAB(IM1));
M2 = YDIF2/(XTAB(I1)-XTAB(I));
end;
% Calculate the slope at the last point, XTAB(NUM).
if ((M1*M2)>=0)
XMID = (XTAB(NUM1)+XTAB(NUM))/2;
YXMID = MTAB(NUM1)*(XMID-XTAB(NUM1)) + YTAB(NUM1);
MTAB(NUM) = (YTAB(NUM)-YXMID)/(XTAB(NUM)-XMID);
if ((MTAB(NUM)*M2)<0)
MTAB(NUM)=0;
end;
else
MTAB(NUM) = 2*M2;
end;
% Calculate the slope at the first point, XTAB(1).
if ((M1S*M2S)<0)
MTAB(1)=2*M1S;
else
XMID = (XTAB(1)+XTAB(2))/2;
YXMID = MTAB(2)*(XMID-XTAB(2)) + YTAB(2);
MTAB(1) = (YXMID-YTAB(1))/(XMID-XTAB(1));
if ((MTAB(1)*M1S)<0)
MTAB(1) =0;
end;
end;
end
|
github
|
ylucet/CCA-master
|
gph_ka.m
|
.m
|
CCA-master/macros/gph/gph_ka.m
| 10,017 |
utf_8
|
6448cbb26cb7e4dbecbab6b7fc75e706
|
% The actual ka calculating function
% All matrices in GPH form and the output also is in GPH form
% We need 5 parameters, representations are quite obvious
% For notation sake, f3 = g here as mentioned in the paper
% Return value ka is the GPH matrix of the kernel average
% Note : The GPH matrix will have an even number of columns always
% TODO : Write unit tests for all subcases
function ka = gph_ka(f1,f2,f3,lambda)
printf('f1 is ')
disp(f1)
printf('f2 is ')
disp(f2)
printf('f3 is ')
disp(f3)
% First of all lets check if its proper
t = gph_ka_isProper(f1,f2,f3,lambda)
lambda1 = lambda
lambda2 = 1-lambda
ka = []
if(t == false)
printf('The KA is not proper. Hence not calculating')
return;
end
sz1 = size(f1,2)
sz2 = size(f2,2)
sz3 = size(f3,2)
% The ka matrix in GPH form to be returned
ka = []
% Iterating over x1 first
i = 1
j = 1 % is the index in f2
k = 1
while i<=sz1
x1 = f1(1,i)
s1 = f1(2,i)
if(j <= sz2)
x2 = f2(1,j)
s2 = f2(2,j)
else
% TODO
% 1. find_values should not be called if the function
% is bounded
% 2. Increment amount should be changed to the previous diff.
x2 = x2 + 1 % right now just incrementing it by 1
[s2,y2] = find_values(f2,sz2-1,x2)
end
x3 = x1-x2
kcols = gph_ka_colsearch(f3,x3)
% kcols can be of maximum size 2
sz_k = size(kcols,2)
% size being 2 means that the intervals share the point
if(sz_k == 2)
printf('Size of kcols is 2')
k1 = kcols(1)
k2 = kcols(2)
s3_1 = f3(2,k1)
s3_2 = f3(2,k2)
if(s3_1 < s2-s1)
% check for s3_2 if its still lesser
if(s3_2 < s2-s1)
% lets increase x1 and see if its greater or equal
i = i + 1;
elseif(s3_2 == s2-s1)
% record and move on
printf('Found a point. Include record code here')
i = i + 1;
else
i = i + 1;
printf('s3_2 < s2-s1')
end
elseif(s3_1 == s2-s1)
% record and increase x1
printf('Found a point2. Include record code here')
else % s3_1 > s2-s1
% going to s3_2 would not help at all as s3 would just inc.
if(s3_2 < s2-s1)
printf('Error with gph reshape of f3')
end
j = j + 1;
end
elseif(sz_k == 1)
% Primary stuff, one piece quadratics should work with this
k = kcols(1)
[s3, y3] = find_values(f3,k,x3)
if(s1 < s2-s3)
printf('Lesser than case')
% We always solve for x2
add_column = gph_ka_solve_equation(f1,f2,f3,i,j,lambda,1)
ka = [ka add_column]
i = i + 1;
elseif(s1 == s2-s3)
x_val = lambda1 * x1 + lambda2*x2
f_val = lambda1 * x1 + lambda2 * x2 + lambda1*lambda2*y3
s_val = s2 - s1
col_add = [x_val;f_val;s_val]
ka = [ka col_add]
% Increase x1 - since equality
i = i + 1;
else
printf('Greater than')
if(j <= sz2)
j = j + 1;
end
end
else
printf('Error: Too many/less values for x3: Not possible')
printf('Error with the code/proof');
end
end
% Iterating over x2 now
i = 1
j = 1
k = 1
while j<=sz2
x2 = f2(1,j)
s2 = f2(2,j)
if(i <= sz1)
x1 = f1(1,i)
s1 = f1(2,i)
else
% TODO
% 1. find_values should not be called if the function
% is bounded
% 2. Increment amount should be changed to the previous diff.
x1 = x1 + 1 % right now just incrementing it by 1
[s1,y1] = find_values(f1,sz1-1,x1)
end
x3 = x1-x2
kcols = gph_ka_colsearch(f3,x3)
% kcols can be of maximum size 2
sz_k = size(kcols,2)
% size being 2 means that the intervals share the point
if(sz_k == 2)
printf('Size of kcols is 2')
k1 = kcols(1)
k2 = kcols(2)
s3_1 = f3(2,k1)
s3_2 = f3(2,k2)
if(s3_1 < s2-s1)
% check for s3_2 if its still lesser
if(s3_2 < s2-s1)
% lets increase x1 and see if its greater or equal
i = i + 1;
elseif(s3_2 == s2-s1)
% record and move on
printf('Found a point. Include record code here')
i = i + 1;
else
i = i + 1;
printf('s3_2 < s2-s1')
end
elseif(s3_1 == s2-s1)
% record and increase x1
printf('Found a point2. Include record code here')
else % s3_1 > s2-s1
% going to s3_2 would not help at all as s3 would just inc.
if(s3_2 < s2-s1)
printf('Error with gph reshape of f3')
end
j = j + 1;
end
elseif(sz_k == 1)
% Primary stuff, one piece quadratics should work with this
k = kcols(1)
[s3, y3] = find_values(f3,k,x3)
if(s1 < s2-s3)
printf('Lesser than case')
if(i <= sz1)
i = i + 1;
end
elseif(s1 == s2-s3)
printf('Equality case')
x_val = lambda1 * x1 + lambda2*x2
f_val = lambda1 * x1 + lambda2 * x2 + lambda1*lambda2*y3
s_val = s2 - s1
col_add = [x_val;f_val;s_val]
ka = [ka col_add]
% Increase x1 - since equality
j = j + 1;
else
% We solve for x1
printf('Greater than')
add_column = gph_ka_solve_equation(f1,f2,f3,i,j,lambda,2)
ka = [ka add_column]
j = j + 1;
end
else
printf('Error: Too many/less values for x3: Not possible')
printf('Error with the code/proof');
end
end % Done with iterating over x2
% Iterating over x3 now
i = 1
j = 1
k = 1
while k<=sz3
x3 = f3(1,k)
s3 = f3(2,k)
if(i <= sz1)
x1 = f1(1,i)
s1 = f1(2,i)
else
% TODO
% 1. find_values should not be called if the function
% is bounded
% 2. Increment amount should be changed to the previous diff.
x1 = x1 + 1 % right now just incrementing it by 1
[s1,y1] = find_values(f1,sz1-1,x1)
end
x3 = x1-x2
kcols = gph_ka_colsearch(f3,x3)
% kcols can be of maximum size 2
sz_k = size(kcols,2)
% size being 2 means that the intervals share the point
if(sz_k == 2)
printf('Size of kcols is 2')
k1 = kcols(1)
k2 = kcols(2)
s3_1 = f3(2,k1)
s3_2 = f3(2,k2)
if(s3_1 < s2-s1)
% check for s3_2 if its still lesser
if(s3_2 < s2-s1)
% lets increase x1 and see if its greater or equal
i = i + 1;
elseif(s3_2 == s2-s1)
% record and move on
printf('Found a point. Include record code here')
i = i + 1;
else
i = i + 1;
printf('s3_2 < s2-s1')
end
elseif(s3_1 == s2-s1)
% record and increase x1
printf('Found a point2. Include record code here')
else % s3_1 > s2-s1
% going to s3_2 would not help at all as s3 would just inc.
if(s3_2 < s2-s1)
printf('Error with gph reshape of f3')
end
j = j + 1;
end
elseif(sz_k == 1)
% Primary stuff, one piece quadratics should work with this
k = kcols(1)
[s3, y3] = find_values(f3,k,x3)
if(s1 < s2-s3)
printf('Lesser than case')
if(i <= sz1)
i = i + 1;
end
elseif(s1 == s2-s3)
printf('Equality case')
x_val = lambda1 * x1 + lambda2*x2
f_val = lambda1 * x1 + lambda2 * x2 + lambda1*lambda2*y3
s_val = s2 - s1
col_add = [x_val;f_val;s_val]
ka = [ka col_add]
% Increase x1 - since equality
j = j + 1;
else
% We solve for x1
printf('Greater than')
add_column = gph_ka_solve_equation(f1,f2,f3,i,j,lambda,2)
ka = [ka add_column]
j = j + 1;
end
else
printf('Error: Too many/less values for x3: Not possible')
printf('Error with the code/proof');
end
end % Done with iterating over x2
disp(ka)
end
|
github
|
ylucet/CCA-master
|
gph_isEqual.m
|
.m
|
CCA-master/macros/gph/gph_isEqual.m
| 139 |
utf_8
|
baea777fec6ab7d18a888d6d313b2480
|
%returns true if both functions are equal
function b = gph_isequal(g1,g2)
p1=plq_gph(g1);
p2=plq_gph(g2);
b = plq_isEqual(p1,p2);
end
|
github
|
ylucet/CCA-master
|
gph_me1.m
|
.m
|
CCA-master/macros/gph/gph_me1.m
| 816 |
utf_8
|
6db3acd48b9b25ca52f496faae0cd5b2
|
%works but requires gph_prox. Can we do better?
function gphstar = gph_me1(gph,lambda)
[b,n] = gph_check(gph);
if ~b
cerror('Unconsistent gph structure in gph_me1');
end;
%do not multiply 3rd row (values of f) to avoid 0*inf giving gphstar = [1 lambda; 0 1] * gph(1:2,:);
x = gph(1,:)';%s=gph(2,:);f=gph(3,:);
Prox = gph_prox(gph,lambda);
prox = gph_eval(Prox,x);
fprox = gph_eval(gph,prox);
gphstar(3,:)= (fprox + (x-prox).^2/(2*lambda))';
% %TO DO: fix bounded domain
% if n>2 then%no fix needed for full domain or singleton
% B = gph_isBounded(gphstar);
% if B(1,1) then gphstar(3,1)=inf;end;
% if B(1,2) then gphstar(3,$)=inf;end;
% end
% B = gph_isBounded(gph);
% if B(1,1) then gphstar(3,1)=s(1)*x(1)-f(2);end;
% if B(1,$) then gphstar(3,$)=s($)*x($)-f($-1);end;
end
|
github
|
ylucet/CCA-master
|
gph_isBounded.m
|
.m
|
CCA-master/macros/gph/gph_isBounded.m
| 168 |
utf_8
|
d4a5346e041ef914a25558d0b4c03501
|
%returns a 1x2 matrix
function B = gph_isBounded(gph)
B = isinf([(gph(2,2)-gph(2,1))/(gph(1,2)-gph(1,1)), (gph(2,end)-gph(2,end-1))/(gph(1,end)-gph(1,end-1))]);
end
|
github
|
ylucet/CCA-master
|
gph_prox.m
|
.m
|
CCA-master/macros/gph/gph_prox.m
| 406 |
utf_8
|
0dfa8497825f26f4ad3b641c61dc60be
|
%TO DO: TEST
%compute the proximal mapping of a GPH function
%from the graph of the subdifferential
%only works for convex functions
function Q = gph_prox(G,alpha)
if alpha<0
Q=[]; cerror('alpha must be nonnegative');
end;
eps=1e-8;
P = [1 alpha;1 0] * G(1:2,:);
P(3,:)=zeros(size(1,size(P,2)));
%convert subdifferential to piecewise linear function
q = pl_gph(P);
Q = gph_plq(q);
end
|
github
|
ylucet/CCA-master
|
intervalIntersect.m
|
.m
|
CCA-master/macros/common/intervalIntersect.m
| 338 |
utf_8
|
20cfbfc07e398d3edde51acc558a546c
|
function J = intervalIntersect(I1,I2)
%compute the intersection of 2 intervals
%I1,I2: intervals stored as a 1x2 matrix: I1=[lb,ub]
%when ub < lb it means the empty set
%J: interval J=I1 intersection I2. (may be empty)
J(1,1)=max(I1(1),I2(1));
J(1,2)=min(I1(2),I2(2));
end
function b = intervalisempty(I)
b = I(1)>I(2);
end
|
github
|
ylucet/CCA-master
|
cerror.m
|
.m
|
CCA-master/macros/common/cerror.m
| 476 |
utf_8
|
6979800df65514b0064c984b5be12456
|
% All CCA functions should use this function instead of error(),
% so that we can act differently depending on when we're generating
% an error to pass a test or generating one for real. Currently
% this function could be eliminated by having __testing_errors = 9999
% in test.sci:errorTestWrapper(), but this way presents more flexibility.
function cerror(msg)
global testing_errors;
if (testing_errors)
error(msg, testing_errors);
else
error(msg);
end;
end
|
github
|
ylucet/CCA-master
|
colMap.m
|
.m
|
CCA-master/macros/common/colMap.m
| 384 |
utf_8
|
9461e54cb1a9cb21e89387075ac3ed52
|
% Map a function to each of the columns of a matrix, putting the resulting column vectors into the output matrix
% @param func A function that takes two parameters (the first is a column vector,
% the second the number of the current column) and returns a column vector
function out=colMap(func,m)
out=[]
s=size(m)
n=s(2)
for i=1:n
out(:,i)=func(m(:,i),i)
end
end
|
github
|
ylucet/CCA-master
|
gph_plot.m
|
.m
|
CCA-master/macros/plots/gph_plot.m
| 1,156 |
utf_8
|
3d4ec654a8b20c3434c895ced533a50d
|
%plot the subdifferential graph of an unknown number of gph functions
%(limit of 5 gph functions)
%automatically compute the display window and extrapolate to its boundary
%see gph_version for utility functions _gph_plotbounds_gph_yCoord,_gph_extendGph
function gph_plot(varargin)
if(isempty(varargin))
error("No argument given to gph_plot function");
end
if(length(varargin)==1)
L=[varargin];
else
L=varargin;
end
rect = gph_plotbounds(varargin); %%FIX THIS
%need to plot graph by graph since graphs may not have same number of points
hold on
%make a vector with the different symbols, colours, and thickness's so as to have multiple plots all unique
%limit up to 5
%NOT WORKING
spec = ['-xr';'-+b';'-sg';'-*m';'-ok';'-dc'];
for i=1:length(varargin)
g = varargin{i};
G = gph_extendGph(g, rect); %%extend graph to boundary by linear extrapolation
%added figure to hold multiple plots
plot(G(1,:)',G(2,:)', spec(i,:));
%plot(G(1,:)',G(2,:)', spec(i+1));
xlim([rect(1) rect(3)]); ylim([rect(2) rect(4)]);
end
hold off
end
|
github
|
ylucet/CCA-master
|
plq_plot.m
|
.m
|
CCA-master/macros/plots/plq_plot.m
| 480 |
utf_8
|
325f581208cb8172b688c23b6a05511e
|
%Quick plot of one or two PLQ functions
%x1, x5 can be finite or infinity values.
function plq_plot(plqf1, plqf2, x1, x5)
if(nargin < 2)
plqf2 = 0;
end
if(nargin < 3 | x1 == -Inf)
x1 = -5;
end
if(nargin < 4 | x5 == Inf)
x5 = 5;
end
x = linspace(x1,x5, 201);
y1 = plq_eval(plqf1, x);
if(~plqf2)
plot(x, y1);
else
y2=plq_eval(plqf2, x);
plot(x, y1, 'r', x, y2, 'b');
end
end
|
github
|
ylucet/CCA-master
|
gph_extendGph.m
|
.m
|
CCA-master/macros/plots/gph_extendGph.m
| 543 |
utf_8
|
e086ecc88dacc9aca1bdab0fb5cddb40
|
%extend the graph to boundary values by linear extrapolation
%only return the first 2 rows and discard the 3rd row
function G = gph_extendGph(g, rect)
if g(1,1) == g(1,2) %vertical line on left %ERROR HERE
G=[[g(1,1);rect(2)],g(1:2,:)];
else
G=[[rect(1); gph_yCoord(rect(1),g(1,1),g(2,1),g(1,2),g(2,2))],g(1:2,:)];
end
if(g(1,end)==g(1, end-1)) %vertical line on right
G=[G, [g(1, end); rect(4)]];
else
G=[G, [rect(3); gph_yCoord(rect(3),g(1,end-1),g(2,end-1),g(1,end),g(2,end))]];
end
end
|
github
|
ylucet/CCA-master
|
gph_yCoord.m
|
.m
|
CCA-master/macros/plots/gph_yCoord.m
| 291 |
utf_8
|
739e84ef71a3408dc304fa4908bb0a46
|
%compute the y coordinate for the poin on the line
%going to (xi, yi) at x
function y = gph_yCoord(x, x1, y1, x2, y2)
if x == x1
%warning("yCoord: x == x1"); %warning message is removed to avoid warning
y=y1;
else
y = (y2-y1)/(x2-x1)* (x-x1) + y1;
end
end
|
github
|
ylucet/CCA-master
|
plq_plotMultiple.m
|
.m
|
CCA-master/macros/plots/plq_plotMultiple.m
| 1,156 |
utf_8
|
3a907cc489ebcaf72b3002edd685d145
|
%Plot mutiple PLQ functions
%x1, x5 can be finite or infinity values
function plq_plotMultiple(x1, x5, varargin)
if(nargin < 1 | x1 == false | x1 == -Inf)
x1 = Inf;
for i = 1:length(varargin)
f = varargin{i};
lb = max(1, min(find(f(:,4) ~= Inf)) -1);
x1 = min(x1, f(lb, 1));
end
if(isinf(x1))
x1 = -5;
end
spaceLeft = 1;
else
spaceLeft = 0;
end
if(nargin < 2 | x5 == false | x5 == Inf)
x5 = - Inf;
for i = 1:length(varargin)
f = varargin{i};
ub = max(find(f(:,4) ~= Inf));
x5 = max(x5, f(ub,1));
end
if(isinf(x5))
x5 = 5;
end
spaceRight = 1;
else
spaceRight = 0;
end
if(length(varargin) == 0)
return;
end
spacing = (x5 - x1) * 0.15;
x = linspace(x1-spacing*spaceLeft, x5+spacing*spaceRight, 200)';
y = [];
%TODO: Plot indicator functions spcially: plot2d(f(1,1), f(1,4), -5);
for i = 1:length(varargin)
f = varargin{i};
y(:, i) = plq_eval(f, x);
end
plot(x, y)
end
|
github
|
panji530/Robust-shape-interaction-matrix-master
|
hungarian.m
|
.m
|
Robust-shape-interaction-matrix-master/hungarian.m
| 11,781 |
utf_8
|
294996aeeca4dadfc427da4f81f8b99d
|
function [C,T]=hungarian(A)
%HUNGARIAN Solve the Assignment problem using the Hungarian method.
%
%[C,T]=hungarian(A)
%A - a square cost matrix.
%C - the optimal assignment.
%T - the cost of the optimal assignment.
%s.t. T = trace(A(C,:)) is minimized over all possible assignments.
% Adapted from the FORTRAN IV code in Carpaneto and Toth, "Algorithm 548:
% Solution of the assignment problem [H]", ACM Transactions on
% Mathematical Software, 6(1):104-111, 1980.
% v1.0 96-06-14. Niclas Borlin, [email protected].
% Department of Computing Science, Ume? University,
% Sweden.
% All standard disclaimers apply.
% A substantial effort was put into this code. If you use it for a
% publication or otherwise, please include an acknowledgement or at least
% notify me by email. /Niclas
[m,n]=size(A);
if (m~=n)
error('HUNGARIAN: Cost matrix must be square!');
end
% Save original cost matrix.
orig=A;
% Reduce matrix.
A=hminired(A);
% Do an initial assignment.
[A,C,U]=hminiass(A);
% Repeat while we have unassigned rows.
while (U(n+1))
% Start with no path, no unchecked zeros, and no unexplored rows.
LR=zeros(1,n);
LC=zeros(1,n);
CH=zeros(1,n);
RH=[zeros(1,n) -1];
% No labelled columns.
SLC=[];
% Start path in first unassigned row.
r=U(n+1);
% Mark row with end-of-path label.
LR(r)=-1;
% Insert row first in labelled row set.
SLR=r;
% Repeat until we manage to find an assignable zero.
while (1)
% If there are free zeros in row r
if (A(r,n+1)~=0)
% ...get column of first free zero.
l=-A(r,n+1);
% If there are more free zeros in row r and row r in not
% yet marked as unexplored..
if (A(r,l)~=0 & RH(r)==0)
% Insert row r first in unexplored list.
RH(r)=RH(n+1);
RH(n+1)=r;
% Mark in which column the next unexplored zero in this row
% is.
CH(r)=-A(r,l);
end
else
% If all rows are explored..
if (RH(n+1)<=0)
% Reduce matrix.
[A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR);
end
% Re-start with first unexplored row.
r=RH(n+1);
% Get column of next free zero in row r.
l=CH(r);
% Advance "column of next free zero".
CH(r)=-A(r,l);
% If this zero is last in the list..
if (A(r,l)==0)
% ...remove row r from unexplored list.
RH(n+1)=RH(r);
RH(r)=0;
end
end
% While the column l is labelled, i.e. in path.
while (LC(l)~=0)
% If row r is explored..
if (RH(r)==0)
% If all rows are explored..
if (RH(n+1)<=0)
% Reduce cost matrix.
[A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR);
end
% Re-start with first unexplored row.
r=RH(n+1);
end
% Get column of next free zero in row r.
l=CH(r);
% Advance "column of next free zero".
CH(r)=-A(r,l);
% If this zero is last in list..
if(A(r,l)==0)
% ...remove row r from unexplored list.
RH(n+1)=RH(r);
RH(r)=0;
end
end
% If the column found is unassigned..
if (C(l)==0)
% Flip all zeros along the path in LR,LC.
[A,C,U]=hmflip(A,C,LC,LR,U,l,r);
% ...and exit to continue with next unassigned row.
break;
else
% ...else add zero to path.
% Label column l with row r.
LC(l)=r;
% Add l to the set of labelled columns.
SLC=[SLC l];
% Continue with the row assigned to column l.
r=C(l);
% Label row r with column l.
LR(r)=l;
% Add r to the set of labelled rows.
SLR=[SLR r];
end
end
end
% Calculate the total cost.
T=sum(orig(logical(sparse(C,1:size(orig,2),1))));
function A=hminired(A)
%HMINIRED Initial reduction of cost matrix for the Hungarian method.
%
%B=assredin(A)
%A - the unreduced cost matris.
%B - the reduced cost matrix with linked zeros in each row.
% v1.0 96-06-13. Niclas Borlin, [email protected].
[m,n]=size(A);
% Subtract column-minimum values from each column.
colMin=min(A);
A=A-colMin(ones(n,1),:);
% Subtract row-minimum values from each row.
rowMin=min(A')';
A=A-rowMin(:,ones(1,n));
% Get positions of all zeros.
[i,j]=find(A==0);
% Extend A to give room for row zero list header column.
A(1,n+1)=0;
for k=1:n
% Get all column in this row.
cols=j(k==i)';
% Insert pointers in matrix.
A(k,[n+1 cols])=[-cols 0];
end
function [A,C,U]=hminiass(A)
%HMINIASS Initial assignment of the Hungarian method.
%
%[B,C,U]=hminiass(A)
%A - the reduced cost matrix.
%B - the reduced cost matrix, with assigned zeros removed from lists.
%C - a vector. C(J)=I means row I is assigned to column J,
% i.e. there is an assigned zero in position I,J.
%U - a vector with a linked list of unassigned rows.
% v1.0 96-06-14. Niclas Borlin, [email protected].
[n,np1]=size(A);
% Initalize return vectors.
C=zeros(1,n);
U=zeros(1,n+1);
% Initialize last/next zero "pointers".
LZ=zeros(1,n);
NZ=zeros(1,n);
for i=1:n
% Set j to first unassigned zero in row i.
lj=n+1;
j=-A(i,lj);
% Repeat until we have no more zeros (j==0) or we find a zero
% in an unassigned column (c(j)==0).
while (C(j)~=0)
% Advance lj and j in zero list.
lj=j;
j=-A(i,lj);
% Stop if we hit end of list.
if (j==0)
break;
end
end
if (j~=0)
% We found a zero in an unassigned column.
% Assign row i to column j.
C(j)=i;
% Remove A(i,j) from unassigned zero list.
A(i,lj)=A(i,j);
% Update next/last unassigned zero pointers.
NZ(i)=-A(i,j);
LZ(i)=lj;
% Indicate A(i,j) is an assigned zero.
A(i,j)=0;
else
% We found no zero in an unassigned column.
% Check all zeros in this row.
lj=n+1;
j=-A(i,lj);
% Check all zeros in this row for a suitable zero in another row.
while (j~=0)
% Check the in the row assigned to this column.
r=C(j);
% Pick up last/next pointers.
lm=LZ(r);
m=NZ(r);
% Check all unchecked zeros in free list of this row.
while (m~=0)
% Stop if we find an unassigned column.
if (C(m)==0)
break;
end
% Advance one step in list.
lm=m;
m=-A(r,lm);
end
if (m==0)
% We failed on row r. Continue with next zero on row i.
lj=j;
j=-A(i,lj);
else
% We found a zero in an unassigned column.
% Replace zero at (r,m) in unassigned list with zero at (r,j)
A(r,lm)=-j;
A(r,j)=A(r,m);
% Update last/next pointers in row r.
NZ(r)=-A(r,m);
LZ(r)=j;
% Mark A(r,m) as an assigned zero in the matrix . . .
A(r,m)=0;
% ...and in the assignment vector.
C(m)=r;
% Remove A(i,j) from unassigned list.
A(i,lj)=A(i,j);
% Update last/next pointers in row r.
NZ(i)=-A(i,j);
LZ(i)=lj;
% Mark A(r,m) as an assigned zero in the matrix . . .
A(i,j)=0;
% ...and in the assignment vector.
C(j)=i;
% Stop search.
break;
end
end
end
end
% Create vector with list of unassigned rows.
% Mark all rows have assignment.
r=zeros(1,n);
rows=C(C~=0);
r(rows)=rows;
empty=find(r==0);
% Create vector with linked list of unassigned rows.
U=zeros(1,n+1);
U([n+1 empty])=[empty 0];
function [A,C,U]=hmflip(A,C,LC,LR,U,l,r)
%HMFLIP Flip assignment state of all zeros along a path.
%
%[A,C,U]=hmflip(A,C,LC,LR,U,l,r)
%Input:
%A - the cost matrix.
%C - the assignment vector.
%LC - the column label vector.
%LR - the row label vector.
%U - the
%r,l - position of last zero in path.
%Output:
%A - updated cost matrix.
%C - updated assignment vector.
%U - updated unassigned row list vector.
% v1.0 96-06-14. Niclas Borlin, [email protected].
n=size(A,1);
while (1)
% Move assignment in column l to row r.
C(l)=r;
% Find zero to be removed from zero list..
% Find zero before this.
m=find(A(r,:)==-l);
% Link past this zero.
A(r,m)=A(r,l);
A(r,l)=0;
% If this was the first zero of the path..
if (LR(r)<0)
...remove row from unassigned row list and return.
U(n+1)=U(r);
U(r)=0;
return;
else
% Move back in this row along the path and get column of next zero.
l=LR(r);
% Insert zero at (r,l) first in zero list.
A(r,l)=A(r,n+1);
A(r,n+1)=-l;
% Continue back along the column to get row of next zero in path.
r=LC(l);
end
end
function [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR)
%HMREDUCE Reduce parts of cost matrix in the Hungerian method.
%
%[A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR)
%Input:
%A - Cost matrix.
%CH - vector of column of 'next zeros' in each row.
%RH - vector with list of unexplored rows.
%LC - column labels.
%RC - row labels.
%SLC - set of column labels.
%SLR - set of row labels.
%
%Output:
%A - Reduced cost matrix.
%CH - Updated vector of 'next zeros' in each row.
%RH - Updated vector of unexplored rows.
% v1.0 96-06-14. Niclas Borlin, [email protected].
n=size(A,1);
% Find which rows are covered, i.e. unlabelled.
coveredRows=LR==0;
% Find which columns are covered, i.e. labelled.
coveredCols=LC~=0;
r=find(~coveredRows);
c=find(~coveredCols);
% Get minimum of uncovered elements.
m=min(min(A(r,c)));
% Subtract minimum from all uncovered elements.
A(r,c)=A(r,c)-m;
% Check all uncovered columns..
for j=c
% ...and uncovered rows in path order..
for i=SLR
% If this is a (new) zero..
if (A(i,j)==0)
% If the row is not in unexplored list..
if (RH(i)==0)
% ...insert it first in unexplored list.
RH(i)=RH(n+1);
RH(n+1)=i;
% Mark this zero as "next free" in this row.
CH(i)=j;
end
% Find last unassigned zero on row I.
row=A(i,:);
colsInList=-row(row<0);
if (length(colsInList)==0)
% No zeros in the list.
l=n+1;
else
l=colsInList(row(colsInList)==0);
end
% Append this zero to end of list.
A(i,l)=-j;
end
end
end
% Add minimum to all doubly covered elements.
r=find(coveredRows);
c=find(coveredCols);
% Take care of the zeros we will remove.
[i,j]=find(A(r,c)<=0);
i=r(i);
j=c(j);
for k=1:length(i)
% Find zero before this in this row.
lj=find(A(i(k),:)==-j(k));
% Link past it.
A(i(k),lj)=A(i(k),j(k));
% Mark it as assigned.
A(i(k),j(k))=0;
end
A(r,c)=A(r,c)+m;
|
github
|
Vincentqyw/light-field-TB-master
|
ViewLightField.m
|
.m
|
light-field-TB-master/ViewLightField.m
| 1,062 |
utf_8
|
2f47d417127b5f68c9bc44bbbc3a43e5
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 2015.05.14 Jaesik Park
% 2017.10.15 Vincent Qin revised
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function fn_ViewLightField
% input : 5D light field image structure (t,s,y,x,ch), single type pixel intensities.
function ViewLightField(LF)
fprintf('ViewLightField...');
ns = size(LF,1);
nt = size(LF,2);
h = size(LF,3);
w = size(LF,4);
% keyboard;
bigimg = zeros(h*nt,w*ns,3);
% cnt=1;
for t=1:nt
ts = (t-1)*h+1;
te = t*h;
for s=1:ns
ss = (s-1)*w+1;
se = s*w;
img = squeeze(LF(t,s,:,:,:));
% bigimg(ts:te,ss:se,:) = img;
bigimg(ts:te,ss:se,1) = img(:,:,1);
bigimg(ts:te,ss:se,2) = img(:,:,2);
bigimg(ts:te,ss:se,3) = img(:,:,3);
% cnt = cnt + 1;
figure(1); imshow(img);
title(sprintf('s : %d, t : %d',s,t));
pause(0.05);
end
end
% bigimg = imresize(bigimg);
figure; imshow(bigimg);
imwrite(bigimg,'bigimg.jpg','jpg');
fprintf('done.\n');
|
github
|
Vincentqyw/light-field-TB-master
|
LFCalRectifyLF.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFCalRectifyLF.m
| 4,859 |
utf_8
|
58ca494191153d4b172d9f8d2408ca25
|
% LFCalRectifyLF - rectify a light field using a calibrated camera model, called as part of LFUtilDecodeLytroFolder
%
% Usage:
% [LF, RectOptions] = LFCalRectifyLF( LF, CalInfo, RectOptions )
% [LF, RectOptions] = LFCalRectifyLF( LF, CalInfo )
%
% This function is called by LFUtilDecodeLytroFolder to rectify a light field. It follows the
% rectification procedure described in:
%
% D. G. Dansereau, O. Pizarro, and S. B. Williams, "Decoding, calibration and rectification for
% lenslet-based plenoptic cameras," in Computer Vision and Pattern Recognition (CVPR), IEEE
% Conference on. IEEE, Jun 2013.
%
% Minor differences from the paper: light field indices [i,j,k,l] are 1-based in this
% implementation, and not 0-based as described in the paper.
%
% Note that a calibration should only be applied to a light field decoded using the same lenslet
% grid model. This is because the lenslet grid model forms an implicit part of the calibration,
% and changing it will invalidate the calibration.
%
% LFCalDispRectIntrinsics is useful for visualizing the sampling pattern associated with a requested
% intrinsic matrix.
%
% Inputs:
%
% LF : The light field to rectify; should be floating point
%
% CalInfo struct contains a calibrated camera model, see LFUtilCalLensletCam:
% .EstCamIntrinsicsH : 5x5 homogeneous matrix describing the lenslet camera intrinsics
% .EstCamDistortionV : Estimated distortion parameters
%
% [optional] RectOptions struct (all fields are optional) :
% .NInverse_Distortion_Iters : Number of iterations in inverse distortion estimation
% .Precision : 'single' or 'double'
% .RectCamIntrinsicsH : Requests a specific set of intrinsics for the rectified light
% field. By default the rectified intrinsic matrix is
% automatically constructed from the calibrated intrinsic
% matrix, but this process can in some instances yield poor
% results: excessive black space at the edges of the light field
% sample space, or excessive loss of scene content off the edges
% of the space. This parameters allows you to fine-tune the
% desired rectified intrinsic matrix.
%
% Outputs :
%
% LF : The rectified light field
% RectOptions : The rectification options as applied, including any default values employed.
%
% See also: LFCalDispRectIntrinsics, LFUtilCalLensletCam, LFUtilDecodeLytroFolder, LFUtilProcessWhiteImages
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [LF, RectOptions] = LFCalRectifyLF( LF, CalInfo, RectOptions )
%---Defaults---
RectOptions = LFDefaultField( 'RectOptions', 'Precision', 'single' );
RectOptions = LFDefaultField( 'RectOptions', 'NInverse_Distortion_Iters', 2 );
RectOptions = LFDefaultField( 'RectOptions', 'MaxUBlkSize', 32 );
LFSize = size(LF);
RectOptions = LFDefaultField( 'RectOptions', 'RectCamIntrinsicsH', LFDefaultIntrinsics( LFSize, CalInfo ) );
%---Build interpolation indices---
fprintf('Generating interpolation indices...\n');
NChans = LFSize(5);
LF = cast(LF, RectOptions.Precision);
%---chop up the LF along u---
fprintf('Interpolating...');
UBlkSize = RectOptions.MaxUBlkSize;
LFOut = LF;
for( UStart = 1:UBlkSize:LFSize(4) )
UStop = UStart + UBlkSize - 1;
UStop = min(UStop, LFSize(4));
t_in=cast(1:LFSize(1), 'uint16'); % saving some mem by using uint16
s_in=cast(1:LFSize(2), 'uint16');
v_in=cast(1:LFSize(3), 'uint16');
u_in=cast(UStart:UStop, 'uint16');
[tt,ss,vv,uu] = ndgrid(t_in,s_in,v_in,u_in);
% InterpIdx initially holds the index of the desired ray, and is evolved through the application
% of the inverse distortion model to eventually hold the continuous-domain index of the undistorted
% ray, and passed to the interpolation step.
InterpIdx = [ss(:)'; tt(:)'; uu(:)'; vv(:)'; ones(size(ss(:)'))];
DestSize = size(tt);
clear tt ss vv uu
InterpIdx = LFMapRectifiedToMeasured( InterpIdx, CalInfo, RectOptions );
for( ColChan = 1:NChans )
% todo[optimization]: use a weighted interpolation scheme to exploit the weight channel
InterpSlice = interpn(squeeze(LF(:,:,:,:,ColChan)), InterpIdx(2,:),InterpIdx(1,:), InterpIdx(4,:),InterpIdx(3,:), 'linear');
InterpSlice = reshape(InterpSlice, DestSize);
LFOut(:,:,:,UStart:UStop,ColChan) = InterpSlice;
end
fprintf('.')
end
LF = LFOut;
clear LFOut;
%---Clip interpolation result, which sometimes rings slightly out of range---
LF(isnan(LF)) = 0;
LF = max(0, min(1, LF));
fprintf('\nDone\n');
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFWriteMetadata.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFWriteMetadata.m
| 10,271 |
utf_8
|
18ac683694e04562a3249c7226bdde52
|
% LFWriteMetadata - saves variables to a file in JSON format
%
% Usage:
% LFWriteMetadata( JsonFileFname, DataToSave )
%
% This function saves data to a JSON file.
%
% Based on JSONlab by Qianqian Fang,
% http://www.mathworks.com.au/matlabcentral/fileexchange/33381-jsonlab-a-toolbox-to-encodedecode-json-files-in-matlaboctave
%
% Minor modifications by Donald G. Dansereau, 2013, to simplify the interface as appropriate for use
% in the Light Field Toolbox.
%
% See also: LFReadMetadata
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LFWriteMetadata( JsonFileFname, DataToSave )
rootname = [];
varname=inputname(1);
opt.FileName = JsonFileFname;
opt.IsOctave=exist('OCTAVE_VERSION');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(DataToSave) || islogical(DataToSave) || ischar(DataToSave) || isstruct(DataToSave) || iscell(DataToSave)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(DataToSave) || iscell(DataToSave))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2json(rootname,DataToSave,rootlevel,opt);
if(rootisarray)
json=sprintf('%s\n',json);
else
json=sprintf('{\n%s\n}\n',json);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);\n',jsonp,json);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
len=numel(item); % let's handle 1D cell first
padding1=repmat(sprintf('\t'),1,level-1);
padding0=repmat(sprintf('\t'),1,level);
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [\n',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[\n',padding0);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": null',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%snull',padding0);
end
end
for i=1:len
txt=sprintf('%s%s%s',txt,padding1,obj2json(name,item{i},level+(len>1),varargin{:}));
if(i<len) txt=sprintf('%s%s',txt,sprintf(',\n')); end
end
if(len>1) txt=sprintf('%s\n%s]',txt,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
len=numel(item);
padding1=repmat(sprintf('\t'),1,level-1);
padding0=repmat(sprintf('\t'),1,level);
sep=',';
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [\n',padding0,checkname(name,varargin{:})); end
else
if(len>1) txt=sprintf('%s[\n',padding0); end
end
for e=1:len
names = fieldnames(item(e));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {\n',txt,repmat(sprintf('\t'),1,level+(len>1)), checkname(name,varargin{:}));
else
txt=sprintf('%s%s{\n',txt,repmat(sprintf('\t'),1,level+(len>1)));
end
if(~isempty(names))
for i=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{i},getfield(item(e),...
names{i}),level+1+(len>1),varargin{:}));
if(i<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,sprintf('\n'));
end
end
txt=sprintf('%s%s}',txt,repmat(sprintf('\t'),1,level+(len>1)));
if(e==len) sep=''; end
if(e<len) txt=sprintf('%s%s',txt,sprintf(',\n')); end
end
if(len>1) txt=sprintf('%s\n%s]',txt,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
sep=sprintf(',\n');
padding1=repmat(sprintf('\t'),1,level);
padding0=repmat(sprintf('\t'),1,level+1);
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [\n',padding1,checkname(name,varargin{:})); end
else
if(len>1) txt=sprintf('%s[\n',padding1); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
if(len==1)
DataToSave=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) DataToSave=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,repmat(sprintf('\t'),1,level),DataToSave);
else
txt=sprintf('%s%s%s%s',txt,repmat(sprintf('\t'),1,level+1),['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s\n%s%s',txt,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
padding1=repmat(sprintf('\t'),1,level);
padding0=repmat(sprintf('\t'),1,level+1);
if(length(size(item))>2 || issparse(item) || ~isreal(item) || jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{\n%s"_ArrayType_": "%s",\n%s"_ArraySize_": %s,\n',...
padding1,padding0,class(item),padding0,regexprep(mat2str(size(item)),'\s+',',') );
else
txt=sprintf('%s"%s": {\n%s"_ArrayType_": "%s",\n%s"_ArraySize_": %s,\n',...
padding1,checkname(name,varargin{:}),padding0,class(item),padding0,regexprep(mat2str(size(item)),'\s+',',') );
end
else
if(isempty(name))
txt=sprintf('%s%s',padding1,matdata2json(item,level+1,varargin{:}));
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),matdata2json(item,level+1,varargin{:}));
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sprintf(',\n'));
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sprintf(',\n'));
if(find(size(item)==1))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), sprintf('\n'));
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), sprintf('\n'));
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), sprintf('\n'));
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sprintf(',\n'));
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), sprintf('\n'));
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[\n');
post=sprintf('\n%s]',repmat(sprintf('\t'),1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],\n')]];
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(sprintf('\t'),1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-1:end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function val=jsonopt(key,default,varargin)
val=default;
if(nargin<=2) return; end
opt=varargin{1};
if(isstruct(opt) && isfield(opt,key))
val=getfield(opt,key);
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFBuild4DFreqDualFan.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFBuild4DFreqDualFan.m
| 4,955 |
utf_8
|
b925c1d38066faa9f44d0c51b8c68d91
|
% LFBuild4DFreqDualFan - construct a 4D dual-fan passband filter in the frequency domain
%
% Usage:
%
% [H, FiltOptions] = LFBuild4DFreqDualFan( LFSize, Slope, BW, FiltOptions )
% H = LFBuild4DFreqDualFan( LFSize, Slope, BW )
%
% This file constructs a real-valued magnitude response in 4D, for which the passband is a dual-fan,
% the intersection of 2 2D fans.
%
% Once constructed the filter must be applied to a light field, e.g. using LFFilt4DFFT. The
% LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters.
%
% A more technical discussion, including the use of filters for denoising and volumetric focus, and
% the inclusion of aliases components, is included in:
%
% [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field
% Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015.
%
% Inputs:
%
% LFSize : Size of the frequency-domain filter. This should match or exceed the size of the
% light field to be filtered. If it's larger than the input light field, the input is
% zero-padded to match the filter's size by LFFilt4DFFT.
%
% Slope : The slope of the planar passband. If different slopes are desired in s,t and u,v,
% the optional aspect parameter should be used.
%
% BW : 3-db Bandwidth of the planar passband.
%
% [optional] FiltOptions : struct controlling filter construction
% SlopeMethod : 'Skew' or 'Rotate' default 'skew'
% Precision : 'single' or 'double', default 'single'
% Rolloff : 'Gaussian' or 'Butter', default 'Gaussian'
% Order : controls the order of the filter when Rolloff is 'Butter', default 3
% Aspect4D : aspect ratio of the light field, default [1 1 1 1]
% Window : Default false. By default the edges of the passband are sharp; this adds
% a smooth rolloff at the edges when used in conjunction with Extent4D or
% IncludeAliased.
% Extent4D : controls where the edge of the passband occurs, the default [1 1 1 1]
% is the edge of the Nyquist box. When less than 1, enabling windowing
% introduces a rolloff after the edge of the passband. Can be greater
% than 1 when using IncludeAliased.
% IncludeAliased : default false; allows the passband to wrap around off the edge of the
% Nyquist box; used in conjunction with Window and/or Extent4D. This can
% increase processing time dramatically, e.g. Extent4D = [2,2,2,2]
% requires a 2^4 = 16-fold increase in time to construct the filter.
% Useful when passband content is aliased, see [2].
%
% Outputs:
%
% H : real-valued frequency magnitude response
% FiltOptions : The filter options including defaults, with an added PassbandInfo field
% detailing the function and time of construction of the filter
%
% See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01,
% LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone,
% LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [H, FiltOptions] = LFBuild4DFreqDualFan( LFSize, Slope1, Slope2, BW, FiltOptions )
FiltOptions = LFDefaultField('FiltOptions', 'Aspect4D', 1);
FiltOptions = LFDefaultField('FiltOptions', 'Extent4D', 1);
if( length(LFSize) == 1 )
LFSize = LFSize .* [1,1,1,1];
end
if( length(FiltOptions.Extent4D) == 1 )
FiltOptions.Extent4D = FiltOptions.Extent4D .* [1,1,1,1];
end
if( length(FiltOptions.Aspect4D) == 1 )
FiltOptions.Aspect4D = FiltOptions.Aspect4D .* [1,1,1,1];
end
FiltOptionsSU = FiltOptions;
FiltOptionsSU.Aspect2D = FiltOptionsSU.Aspect4D([2,4]);
FiltOptionsSU.Extent2D = FiltOptionsSU.Extent4D([2,4]);
Hsu = LFBuild2DFreqFan( LFSize([2,4]), Slope1, Slope2, BW, FiltOptionsSU );
FiltOptionsTV = FiltOptions;
FiltOptionsTV.Aspect2D = FiltOptionsSU.Aspect4D([1,3]);
FiltOptionsTV.Extent2D = FiltOptionsSU.Extent4D([1,3]);
[Htv, FiltOptionsTV] = LFBuild2DFreqFan( LFSize([1,3]), Slope1, Slope2, BW, FiltOptionsTV );
FiltOptions = FiltOptionsTV;
FiltOptions = rmfield(FiltOptions, 'Aspect2D');
FiltOptions = rmfield(FiltOptions, 'Extent2D');
Hsu = reshape(Hsu, [1, size(Hsu,1), 1, size(Hsu,2)]);
Hsu = repmat(Hsu, [LFSize(1),1,LFSize(3),1]);
Htv = reshape(Htv, [size(Htv,1), 1, size(Htv,2), 1]);
Htv = repmat(Htv, [1,LFSize(2),1,LFSize(4)]);
H = Hsu .* Htv;
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
|
github
|
Vincentqyw/light-field-TB-master
|
LFBuild4DFreqHypercone.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFBuild4DFreqHypercone.m
| 4,501 |
utf_8
|
256d28a026711e06809d334c23db0633
|
% LFBuild4DFreqHypercone - construct a 4D hypercone passband filter in the frequency domain
%
% Usage:
%
% [H, FiltOptions] = LFBuild4DFreqHypercone( LFSize, Slope, BW, FiltOptions )
% H = LFBuild4DFreqHypercone( LFSize, Slope, BW )
%
% This file constructs a real-valued magnitude response in 4D, for which the passband is a hypercone.
%
% Once constructed the filter must be applied to a light field, e.g. using LFFilt4DFFT. The
% LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters.
%
% A more technical discussion, including the use of filters for denoising and volumetric focus, and
% the inclusion of aliases components, is included in:
%
% [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field
% Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015.
%
% Inputs:
%
% LFSize : Size of the frequency-domain filter. This should match or exceed the size of the
% light field to be filtered. If it's larger than the input light field, the input is
% zero-padded to match the filter's size by LFFilt4DFFT.
%
% Slope : The slope of the planar passband. If different slopes are desired in s,t and u,v,
% the optional aspect parameter should be used.
%
% BW : 3-db Bandwidth of the planar passband.
%
% [optional] FiltOptions : struct controlling filter construction
% SlopeMethod : 'Skew' or 'Rotate' default 'skew'
% Precision : 'single' or 'double', default 'single'
% Rolloff : 'Gaussian' or 'Butter', default 'Gaussian'
% Order : controls the order of the filter when Rolloff is 'Butter', default 3
% Aspect4D : aspect ratio of the light field, default [1 1 1 1]
% Window : Default false. By default the edges of the passband are sharp; this adds
% a smooth rolloff at the edges when used in conjunction with Extent4D or
% IncludeAliased.
% Extent4D : controls where the edge of the passband occurs, the default [1 1 1 1]
% is the edge of the Nyquist box. When less than 1, enabling windowing
% introduces a rolloff after the edge of the passband. Can be greater
% than 1 when using IncludeAliased.
% IncludeAliased : default false; allows the passband to wrap around off the edge of the
% Nyquist box; used in conjunction with Window and/or Extent4D. This can
% increase processing time dramatically, e.g. Extent4D = [2,2,2,2]
% requires a 2^4 = 16-fold increase in time to construct the filter.
% Useful when passband content is aliased, see [2].
%
% Outputs:
%
% H : real-valued frequency magnitude response
% FiltOptions : The filter options including defaults, with an added PassbandInfo field
% detailing the function and time of construction of the filter
%
% See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01,
% LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone,
% LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [H, FiltOptions] = LFBuild4DFreqHypercone( LFSize, BW, FiltOptions )
FiltOptions = LFDefaultField('FiltOptions', 'HyperconeMethod', 'Rotated'); % 'Direct', 'Rotated'
DistFunc = @(P, FiltOptions) DistFunc_4DCone( P, FiltOptions );
[H, FiltOptions] = LFHelperBuild4DFreq( LFSize, BW, FiltOptions, DistFunc );
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
end
%-----------------------------------------------------------------------------------------------------------------------
function Dist = DistFunc_4DCone( P, FiltOptions )
switch( lower(FiltOptions.HyperconeMethod ))
case 'direct'
Dist = (P(1,:).*P(4,:) - P(2,:).*P(3,:)).^2 * 4;
case 'rotated'
R = 1/sqrt(2) .* [1,0,0,1; 0,1,1,0; 0,1,-1,0; 1,0,0,-1];
P=R*P;
Dist = (sqrt(P(1,:).^2 + P(3,:).^2) - sqrt(P(2,:).^2 + P(4,:).^2)).^2 /2;
otherwise
error('Unrecognized hypercone construction method');
end
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFUtilProcessWhiteImages.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFUtilProcessWhiteImages.m
| 12,517 |
utf_8
|
82b7183214df46d50702d31ad904317c
|
% LFUtilProcessWhiteImages - process a folder/tree of white images by fitting a grid model to each
%
% Usage:
%
% LFUtilProcessWhiteImages
% LFUtilProcessWhiteImages( WhiteImagesPath )
% LFUtilProcessWhiteImages( WhiteImagesPath, FileOptions, GridModelOptions )
% LFUtilProcessWhiteImages( WhiteImagesPath, [], GridModelOptions )
%
% All parameters are optional and take on default values as set in the "Defaults" section at the top
% of the implementation. As such, this can be called as a function or run directly by editing the
% code. When calling as a function, pass an empty array "[]" to omit a parameter.
%
% As released, the default values are set up to match the naming conventions associated with Lytro
% files extracted using LFP Reader v2.0.0.
%
% Lytro cameras come loaded with a database of white images. These are taken through a diffuser,
% and at different zoom and focus settings. They are useful for removing vignetting (darkening near
% edges of images) and for locating lenslet centers in raw light field images.
%
% This function prepares a set of white images for use by the LF Toolbox. To do this, it fits a grid
% model to each white image, using the function LFBuildLensletGridModel. It also builds a database
% for use in selecting an appropriate white image for decoding a light field, as in the function
% LFLytroDecodeImage / LFSelectFromDatabase. The default parameters are set up to deal with the
% white images extracted from a Lytro camera.
%
% For each grid model fit, a display is generated allowing visual confirmation that the grid fit is
% a good one. This displays each estimated grid center as a red dot over top the white image. If
% the function was successful, each red dot should appear at the center of a lenslet -- i.e. near
% the brightest spot on each white bump. It does not matter if there are a few rows of lenslets on
% the edges of the image with no red markers.
%
%
% Inputs -- all are optional, see code below for default values :
%
% WhiteImagesPath : Path to folder containing white images -- note the function operates
% recursively, i.e. it will search sub-folders. The white image database will
% be created at the top level of this path. A typical configuration is to
% create a "Cameras" folder with a separate subfolder of white images for each
% camera in use. The appropriate path to pass to this function is the top
% level of the cameras folder.
%
% FileOptions : struct controlling file naming and saving
% .SaveResult : Set to false to perform a "dry run"
% .ForceRedo : By default, already-processed white images are skipped; set
% this to true to force reprocessing of already-processed files
% .WhiteImageDatabasePath : Name of file to which white image database is saved
% .WhiteMetadataFilenamePattern : File search pattern for finding white image metadata files
% .WhiteRawDataFnameExtension : File extension of raw white image files
% .ProcessedWhiteImagenamePattern : Pattern defining the names of grid model files; must include
% a %s which gets replaced by the white image base filename
% .WhiteImageMinMeanIntensity : Images with mean intensities below this threshold are
% discarded; this is necessary because some of the Lytro white
% images include are very dark and not useful for grid modelling
%
% GridModelOptions : struct controlling grid construction by LFBuildLensletGridModel
% .FilterDiskRadiusMult : Filter disk radius for prefiltering white image for locating
% lenslets; expressed relative to lenslet spacing; e.g. a
% value of 1/3 means a disk filte with a radius of 1/3 the
% lenslet spacing
% .CropAmt : Edge pixels to ignore when finding the grid
% .SkipStep : As a speed optimization, not all lenslet centers contribute
% to the grid estimate; <SkipStep> pixels are skipped between
% the lenslet centers that get used; a value of 1 means use all
%
% Output takes the form of saved grid model files and a white image database.
%
% See also: LFBuildLensletGridModel, LFUtilDecodeLytroFolder, LFUtilProcessCalibrations
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LFUtilProcessWhiteImages( WhiteImagesPath, FileOptions, GridModelOptions )
%---Defaults---
WhiteImagesPath = LFDefaultVal( 'WhiteImagesPath', 'Cameras' );
FileOptions = LFDefaultField( 'FileOptions', 'SaveResult', true );
FileOptions = LFDefaultField( 'FileOptions', 'ForceRedo', false );
FileOptions = LFDefaultField( 'FileOptions', 'WhiteImageDatabasePath', 'WhiteImageDatabase.mat' );
FileOptions = LFDefaultField( 'FileOptions', 'WhiteMetadataFilenamePattern', '*MOD_*.TXT' );
FileOptions = LFDefaultField( 'FileOptions', 'WhiteRawDataFnameExtension', '.RAW' );
FileOptions = LFDefaultField( 'FileOptions', 'ProcessedWhiteImagenamePattern', '%s.grid.json' );
FileOptions = LFDefaultField( 'FileOptions', 'WhiteImageMinMeanIntensity', 500 );
GridModelOptions = LFDefaultField( 'GridModelOptions', 'Orientation', 'horz' );
GridModelOptions = LFDefaultField( 'GridModelOptions', 'FilterDiskRadiusMult', 1/3 );
GridModelOptions = LFDefaultField( 'GridModelOptions', 'CropAmt', 25 );
GridModelOptions = LFDefaultField( 'GridModelOptions', 'SkipStep', 250 );
DispSize_pix = 160; % size of windows for visual confirmation display
DebugBuildGridModel = false; % additional debug display
%---Load white image info---
fprintf('Building database of white files...\n');
WhiteImageInfo = LFGatherCamInfo( WhiteImagesPath, FileOptions.WhiteMetadataFilenamePattern );
% The Lytro F01 database has two exposures per zoom/focus setting -- this eliminates the darker ones
F01Images = find(strcmp({WhiteImageInfo.CamModel}, 'F01'));
IsF01Image = false(size(WhiteImageInfo));
IsF01Image(F01Images) = true;
ExposureDuration = [WhiteImageInfo.ExposureDuration];
MeanDuration = mean(ExposureDuration(F01Images));
DarkF01Images = find(IsF01Image & (ExposureDuration < MeanDuration));
CamInfoValid = true(size(WhiteImageInfo));
CamInfoValid(DarkF01Images) = false;
%---Tagged onto all saved files---
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
%---Iterate through all white images---
fprintf('Processing each white file...\n');
fprintf('Visually confirm the estimated grid centers (red) are a good match to the lenslet centers...\n');
for( iFile = 1:length(WhiteImageInfo) )
[CurFnamePath, CurFnameBase] = fileparts( WhiteImageInfo(iFile).Fname );
fprintf('%s [File %d / %d]:\n', fullfile(CurFnamePath,CurFnameBase), iFile, length(WhiteImageInfo));
ProcessedWhiteFname = sprintf( FileOptions.ProcessedWhiteImagenamePattern, CurFnameBase );
ProcessedWhiteFname = fullfile(WhiteImagesPath, CurFnamePath, ProcessedWhiteFname);
if( ~FileOptions.ForceRedo && exist(ProcessedWhiteFname, 'file') )
fprintf('Output file %s already exists, skipping.\n', ProcessedWhiteFname);
% note that the file can still be added to the database, after the if/else/end,
% unless it's a dark image as detected below
else
if( ~CamInfoValid(iFile) )
fprintf('Dark F01 image, skipping and not adding to database\n');
continue;
end
%---Load white image and white image metadata---
CurMetadataFname = fullfile(WhiteImagesPath, WhiteImageInfo(iFile).Fname);
CurRawImageFname = LFFindLytroPartnerFile( CurMetadataFname, FileOptions.WhiteRawDataFnameExtension );
WhiteImageMetadata = LFReadMetadata( CurMetadataFname );
WhiteImageMetadata = WhiteImageMetadata.master.picture.frameArray.frame.metadata;
ImgSize = [WhiteImageMetadata.image.width, WhiteImageMetadata.image.height];
switch( WhiteImageInfo(iFile).CamModel )
case 'F01'
WhiteImage = LFReadRaw( CurRawImageFname, '12bit' );
%---Detect very dark images in F01 camera---
if( mean(WhiteImage(:)) < FileOptions.WhiteImageMinMeanIntensity )
fprintf('Detected dark image, skipping and not adding to database\n');
CamInfoValid(iFile) = false;
continue
end
case 'B01'
WhiteImage = LFReadRaw( CurRawImageFname, '10bit' );
otherwise
error('Unrecognized camera model');
end
%---Initialize grid finding parameters based on metadata---
GridModelOptions.ApproxLensletSpacing = ...
WhiteImageMetadata.devices.mla.lensPitch / WhiteImageMetadata.devices.sensor.pixelPitch;
%---Find grid params---
[LensletGridModel, GridCoords] = LFBuildLensletGridModel( WhiteImage, GridModelOptions, DebugBuildGridModel );
GridCoordsX = GridCoords(:,:,1);
GridCoordsY = GridCoords(:,:,2);
%---Visual confirmation---
if( strcmpi(GridModelOptions.Orientation, 'vert') )
WhiteImage = WhiteImage';
end
ImgSize = size(WhiteImage);
HPlotSamps = ceil(DispSize_pix/LensletGridModel.HSpacing);
VPlotSamps = ceil(DispSize_pix/LensletGridModel.VSpacing);
LFFigure(1);
clf
subplot(331);
imagesc(WhiteImage(1:DispSize_pix,1:DispSize_pix));
hold on
colormap gray
plot(GridCoordsX(1:VPlotSamps,1:HPlotSamps), GridCoordsY(1:VPlotSamps,1:HPlotSamps), 'r.')
axis off
subplot(333);
imagesc(WhiteImage(1:DispSize_pix, ImgSize(2)-DispSize_pix:ImgSize(2)));
hold on
colormap gray
plot(-(ImgSize(2)-DispSize_pix)+1 + GridCoordsX(1:VPlotSamps, end-HPlotSamps:end), GridCoordsY(1:VPlotSamps, end-HPlotSamps:end), 'r.')
axis off
CenterStart = (ImgSize-DispSize_pix)/2;
HCenterStartSamps = floor(CenterStart(2) / LensletGridModel.HSpacing);
VCenterStartSamps = floor(CenterStart(1) / LensletGridModel.VSpacing);
subplot(335);
imagesc(WhiteImage(CenterStart(1):CenterStart(1)+DispSize_pix, CenterStart(2):CenterStart(2)+DispSize_pix));
hold on
colormap gray
plot(-CenterStart(2)+1 + GridCoordsX(VCenterStartSamps + (1:VPlotSamps), HCenterStartSamps + (1:HPlotSamps)), -CenterStart(1)+1 + GridCoordsY(VCenterStartSamps + (1:VPlotSamps), HCenterStartSamps + (1:HPlotSamps)),'r.');
axis off
subplot(337);
imagesc(WhiteImage(ImgSize(1)-DispSize_pix:ImgSize(1), 1:DispSize_pix));
hold on
colormap gray
plot(GridCoordsX(end-VPlotSamps:end,1:HPlotSamps), -(ImgSize(1)-DispSize_pix)+1 + GridCoordsY(end-VPlotSamps:end,1:HPlotSamps), 'r.')
axis off
subplot(339);
imagesc(WhiteImage(ImgSize(1)-DispSize_pix:ImgSize(1),ImgSize(2)-DispSize_pix:ImgSize(2)));
hold on
colormap gray
plot(-(ImgSize(2)-DispSize_pix)+1 + GridCoordsX(end-VPlotSamps:end, end-HPlotSamps:end), -(ImgSize(1)-DispSize_pix)+1 + GridCoordsY(end-VPlotSamps:end, end-HPlotSamps:end), 'r.')
axis off
truesize % bigger display
drawnow
%---Optionally save---
if( FileOptions.SaveResult )
fprintf('Saving to %s\n', ProcessedWhiteFname);
CamInfo = WhiteImageInfo(iFile);
LFWriteMetadata(ProcessedWhiteFname, LFVar2Struct(GeneratedByInfo, GridModelOptions, CamInfo, LensletGridModel));
end
end
end
CamInfo = WhiteImageInfo(CamInfoValid);
%---Optionally save the white file database---
if( FileOptions.SaveResult )
FileOptions.WhiteImageDatabasePath = fullfile(WhiteImagesPath, FileOptions.WhiteImageDatabasePath);
fprintf('Saving to %s\n', FileOptions.WhiteImageDatabasePath);
save(FileOptions.WhiteImageDatabasePath, 'GeneratedByInfo', 'CamInfo');
end
fprintf('Done\n');
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFCalDispEstPoses.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFCalDispEstPoses.m
| 2,604 |
utf_8
|
1f7d8e57212bcbb143d2c597e59038f3
|
% LFCalDispEstPoses - Visualize pose estimates associated with a calibration info file
%
% Usage:
% LFCalDispEstPoses( InputPath, CalOptions, DrawFrameSizeMult, BaseColour )
%
% Draws a set of frames, one for each camera pose, in the colour defined by BaseColour. All inputs
% except InputPath are optional. Pass an empty array "[]" to omit a parameter. See
% LFUtilCalLensletCam for example usage.
%
% Inputs:
%
% InputPath : Path to folder containing CalInfo file.
%
% [optional] CalOptions : struct controlling calibration parameters
% .CalInfoFname : Name of the file containing calibration estimate; note that this
% parameter is automatically set in the CalOptions struct returned
% by LFCalInit
%
% [optional] DrawFrameSizeMult : Multiplier on the displayed frame sizes
%
% [optional] BaseColour : RGB triplet defining a base drawing colour, RGB values are in the
% range 0-1
%
%
% See also: LFUtilCalLensletCam
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LFCalDispEstPoses( InputPath, CalOptions, DrawFrameSizeMult, BaseColour )
%---Defaults---
CalOptions = LFDefaultField( 'CalOptions', 'CalInfoFname', 'CalInfo.json' );
DrawFrameSizeMult = LFDefaultVal( 'DrawFrameSizeMult', 1 );
BaseColour = LFDefaultVal( 'BaseColour', [1,1,0] );
%---
Fname = fullfile(CalOptions.CalInfoFname);
EstCamPosesV = LFStruct2Var( LFReadMetadata(fullfile(InputPath, Fname)), 'EstCamPosesV' );
% Establish an appropriate scale for the drawing
AutoDrawScale = EstCamPosesV(:,1:3);
AutoDrawScale = AutoDrawScale(:);
AutoDrawScale = (max(AutoDrawScale) - min(AutoDrawScale))/10;
%---Draw cameras---
BaseFrame = ([0 1 0 0 0 0; 0 0 0 1 0 0; 0 0 0 0 0 1]);
DrawFrameMed = [AutoDrawScale * DrawFrameSizeMult * BaseFrame; ones(1,6)];
DrawFrameLong = [AutoDrawScale*3/2 * DrawFrameSizeMult * BaseFrame; ones(1,6)];
for( PoseIdx = 1:size(EstCamPosesV, 1) )
CurH = eye(4);
CurH(1:3,1:3) = rodrigues( EstCamPosesV(PoseIdx,4:6) );
CurH(1:3,4) = EstCamPosesV(PoseIdx,1:3);
CurH = CurH^-1;
CamFrame = CurH * DrawFrameMed(:,1:4);
plot3( CamFrame(1,:), CamFrame(2,:), CamFrame(3,:), '-', 'color', BaseColour.*0.5, 'LineWidth',2 );
hold on
CamFrame = CurH * DrawFrameLong(:,5:6);
plot3( CamFrame(1,:), CamFrame(2,:), CamFrame(3,:), '-', 'color', BaseColour, 'LineWidth',2 );
end
axis equal
grid on
xlabel('x [m]');
ylabel('y [m]');
zlabel('z [m]');
title('Estimated camera poses');
|
github
|
Vincentqyw/light-field-TB-master
|
LFMatlabPathSetup.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFMatlabPathSetup.m
| 629 |
utf_8
|
09c19ebacb36d9e2d70336dd7f62bc9c
|
% LFMatlabPathSetup - convenience function to add the light field toolbox to matlab's path
%
% It may be convenient to add this to your startup.m file.
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LFMatlabPathSetup
% Find the path to this script, and use it as the base path
LFToolboxPath = fileparts(mfilename('fullpath'));
fprintf('Adding paths for LF Toolbox ');
addpath( fullfile(LFToolboxPath) );
addpath( fullfile(LFToolboxPath, 'SupportFunctions') );
addpath( fullfile(LFToolboxPath, 'SupportFunctions', 'CameraCal') );
fprintf('%s, done.\n', LFToolboxVersion);
|
github
|
Vincentqyw/light-field-TB-master
|
LFReadLFP.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFReadLFP.m
| 9,456 |
utf_8
|
12a412c0c96c3bd388028f4eb975749f
|
% LFReadLFP - Load a lytro LFP / LFR file
%
% Usage:
% [LFP, ExtraSections] = LFReadLFP( Fname )
%
% The Lytro LFP is a container format and may contain one of several types of data. The file extension varies based on
% the source of the files, with exported files, on-camera files and image library files variously taking on the
% extensions lfp, lfr, LFP and LFR.
%
% This function loads all the sections of an LFP and interprets those that it recognizes. Recognized sections include
% thumbnails and focal stacks, raw light field and white images, metadata and serial data. If more than one section of
% the same type appears, a cell array is constructed in the output struct -- this is the case for focal stacks, for
% example. Files generated using Lytro Desktop 4.0 and 3.0 are supported.
%
% Additional output information includes the appropriate demosaic order for raw light field images, and the size of raw
% images.
%
% Unrecognized sections are returned in the ExtraSections output argument.
%
% This function is based in part on Nirav Patel's lfpsplitter.c and Doug Kelley's read_lfp; Thanks to Michael Tao for
% help and samples for decoding Illum imagery.
%
% Inputs :
% Fname : path to an input LFP file
%
% Outputs:
% LFP : Struct containing decoded LFP sections and supporting information, which may include one or more of
% .Jpeg : Thumbnails, focal stacks -- see LFUtilExtractLFPThumbs for saving these to disk
% .RawImg : Raw light field image
% .WhiteImg : White image bundled into Illum LFP
% .Metadata, .Serials : Information about the image and camera
% .DemosaicOrder : The appropriate parameter to pass to Matlab's "demosaic" to debayer a RawImg
% .ImgSize : Size of RawImg
%
% ExtraSections : Struct array containing unrecognized LFP sections
% .Data : Buffer of chars containing the section's uninterpreted data block
% .SectType : Descriptive name for the section, e.g. "hotPixelRef"
% .Sha1 : Unique hash identifying the section
% .SectHeader : Header bytes identifying the section as a table of contents or data
%
% See also: LFUtilExtractLFPThumbs, LFUtilUnpackLytroArchive, LFUtilDecodeLytroFolder
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [LFP, ExtraSections] = LFReadLFP( Fname )
%---Consts---
LFPConsts.LFPHeader = hex2dec({'89', '4C', '46', '50', '0D', '0A', '1A', '0A', '00', '00', '00', '01'}); % 12-byte LFPSections header
LFPConsts.SectHeaderLFM = hex2dec({'89', '4C', '46', '4D', '0D', '0A', '1A', '0A'})'; % header for table of contents
LFPConsts.SectHeaderLFC = hex2dec({'89', '4C', '46', '43', '0D', '0A', '1A', '0A'})'; % header for content section
LFPConsts.SecHeaderPaddingLen = 4;
LFPConsts.Sha1Length = 45;
LFPConsts.ShaPaddingLen = 35; % Sha1 codes are followed by 35 null bytes
%---Break out recognized sections---
KnownSectionTypes = { ...
... % Lytro Desktop 4
'Jpeg', 'picture.accelerationArray.vendorContent.imageArray.imageRef', 'jpeg'; ...
'Jpeg', 'thumbnails.imageRef', 'jpeg'; ...
'RawImg', 'frames.frame.imageRef', 'raw'; ...
'WhiteImg', 'frames.frame.modulationDataRef', 'raw';...
'Metadata', 'frames.frame.metadataRef', 'json'; ...
'Serials', 'frames.frame.privateMetadataRef', 'json'; ...
... % Earlier Lytro Desktop versions
'RawImg', 'picture.frameArray.frame.imageRef', 'raw'; ...
'Metadata', 'picture.frameArray.frame.metadataRef', 'json'; ...
'Serials', 'picture.frameArray.frame.privateMetadataRef', 'json'; ...
};
%---
ExtraSections = [];
LFP = [];
InFile=fopen(Fname, 'rb');
%---Check for the magic header---
HeaderBytes = fread( InFile, length(LFPConsts.LFPHeader), 'uchar' );
if( (length(HeaderBytes)~=length(LFPConsts.LFPHeader)) || ~all( HeaderBytes == LFPConsts.LFPHeader ) )
fclose(InFile);
fprintf( 'Unrecognized file type\n' );
return
end
%---Confirm headerlength bytes---
HeaderLength = fread(InFile,1,'uint32','ieee-be');
assert( HeaderLength == 0, 'Unexpected length at top-level header' );
%---Read each section---
NSections = 0;
TOCIdx = [];
while( ~feof(InFile) )
NSections = NSections+1;
LFPSections( NSections ) = ReadSection( InFile, LFPConsts );
%---Mark the table of contents section---
if( all( LFPSections( NSections ).SectHeader == LFPConsts.SectHeaderLFM ) )
assert( isempty(TOCIdx), 'Found more than one LFM metadata section' );
TOCIdx = NSections;
end
end
fclose( InFile );
%---Decode the table of contents---
assert( ~isempty(TOCIdx), 'Found no LFM metadata sections' );
TOC = LFReadMetadata( LFPSections(TOCIdx).Data );
LFPSections(TOCIdx).SectType = 'TOC';
%---find all sha1 refs in TOC---
TocData = LFPSections(TOCIdx).Data;
ShaIdx = strfind( TocData, 'sha1-' );
SeparatorIdx = find( TocData == ':' );
EolIdx = find( TocData == 10 );
for( iSha = 1:length(ShaIdx) )
LabelStopIdx = SeparatorIdx( find( SeparatorIdx < ShaIdx(iSha), 1, 'last' ) );
LabelStartIdx = EolIdx( find( EolIdx < LabelStopIdx, 1, 'last' ) );
ShaEndIdx = EolIdx( find( EolIdx > ShaIdx(iSha), 1, 'first' ) );
CurLabel = TocData(LabelStartIdx:LabelStopIdx);
CurSha = TocData(LabelStopIdx:ShaEndIdx);
CurLabel = strsplit(CurLabel, '"');
CurSha = strsplit(CurSha, '"');
CurLabel = CurLabel{2};
CurSha = CurSha{2};
SectNames{iSha} = CurLabel;
SectIDs{iSha} = CurSha;
end
%---Apply section labels---
for( iSect = 1:length(SectNames) )
CurSectSHA = SectIDs{iSect};
MatchingSectIdx = find( strcmp( CurSectSHA, {LFPSections.Sha1} ) );
if( ~isempty(MatchingSectIdx) )
LFPSections(MatchingSectIdx).SectType = SectNames{iSect};
end
end
for( iSect = 1:size(KnownSectionTypes,1) )
FoundField = true;
while(FoundField)
[LFP, LFPSections, TOC, FoundField] = ExtractNamedField(LFP, LFPSections, TOC, KnownSectionTypes(iSect,:) );
end
end
ExtraSections = LFPSections;
%---unpack the image(s)---
if( isfield( LFP, 'RawImg') )
LFP.ImgSize = [LFP.Metadata.image.width, LFP.Metadata.image.height];
switch( LFP.Metadata.camera.model )
case 'F01'
assert( LFP.Metadata.image.rawDetails.pixelPacking.bitsPerPixel == 12 );
assert( strcmp(LFP.Metadata.image.rawDetails.pixelPacking.endianness, 'big') );
LFP.RawImg = LFUnpackRawBuffer( LFP.RawImg, '12bit', LFP.ImgSize )';
LFP.DemosaicOrder = 'bggr';
case 'ILLUM'
assert( LFP.Metadata.image.pixelPacking.bitsPerPixel == 10 );
assert( strcmp(LFP.Metadata.image.pixelPacking.endianness, 'little') );
LFP.RawImg = LFUnpackRawBuffer( LFP.RawImg, '10bit', LFP.ImgSize )';
if( isfield( LFP, 'WhiteImg' ) )
LFP.WhiteImg = LFUnpackRawBuffer( LFP.WhiteImg, '10bit', LFP.ImgSize )';
end
LFP.DemosaicOrder = 'grbg';
otherwise
warning('Unrecognized camera model');
return
end
end
end
% --------------------------------------------------------------------
function LFPSect = ReadSection( InFile, LFPConsts )
LFPSect.SectHeader = fread(InFile, length(LFPConsts.SectHeaderLFM), 'uchar')';
Padding = fread(InFile, LFPConsts.SecHeaderPaddingLen, 'uint8'); % skip padding
SectLength = fread(InFile, 1, 'uint32', 'ieee-be');
LFPSect.Sha1 = char(fread(InFile, LFPConsts.Sha1Length, 'uchar')');
Padding = fread(InFile, LFPConsts.ShaPaddingLen, 'uint8'); % skip padding
LFPSect.Data = char(fread(InFile, SectLength, 'uchar'))';
while( 1 )
Padding = fread(InFile, 1, 'uchar');
if( feof(InFile) || (Padding ~= 0) )
break;
end
end
if ~feof(InFile)
fseek( InFile, -1, 'cof'); % rewind one byte
end
end
% --------------------------------------------------------------------
function [LFP, LFPSections, TOC, FoundField] = ExtractNamedField(LFP, LFPSections, TOC, FieldInfo)
FoundField = false;
FieldName = FieldInfo{1};
JsonName = FieldInfo{2};
FieldFormat = FieldInfo{3};
JsonTokens = strsplit(JsonName, '.');
TmpToc = TOC;
if( ~iscell(JsonTokens) )
JsonTokens = {JsonTokens};
end
for( i=1:length(JsonTokens) )
if( ~isfield(TmpToc, JsonTokens{i}) || isempty([TmpToc.(JsonTokens{i})]) )
return;
end
TmpToc = TmpToc.(JsonTokens{i}); % takes the first one in the case of an array
end
FieldIdx = find( strcmp( TmpToc, {LFPSections.Sha1} ) );
if( ~isempty(FieldIdx) )
SubField = struct('type','.','subs',FieldName);
%--- detect image array and force progress by removing the currently-processed entry ---
S = struct('type','.','subs',JsonTokens(1:end-1));
t = subsref( TOC, S );
ArrayLen = length(t);
if( (isstruct(t) && ArrayLen>1) || isfield( LFP, FieldName ) )
S(end+1).type = '()';
S(end).subs = {1};
TOC = subsasgn( TOC, S, [] );
% Add an indexing subfield for image arrays
SubField(end+1).type = '{}';
SubField(end).subs = {ArrayLen};
end
%---Copy the data into the LFP struct---
LFP = subsasgn( LFP, SubField, LFPSections(FieldIdx).Data );
LFPSections = LFPSections([1:FieldIdx-1, FieldIdx+1:end]);
%---Decode JSON-formatted sections---
switch( FieldFormat )
case 'json'
LFP.(FieldName) = LFReadMetadata( LFP.(FieldName) );
end
FoundField = true;
end
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFBuild4DFreqHyperfan.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFBuild4DFreqHyperfan.m
| 4,676 |
utf_8
|
2bec28d4e5b0d48494ee457844595957
|
% LFBuild4DFreqHyperfan - construct a 4D hyperfan passband filter in the frequency domain
%
% Usage:
%
% [H, FiltOptions] = LFBuild4DFreqHyperfan( LFSize, Slope, BW, FiltOptions )
% H = LFBuild4DFreqHyperfan( LFSize, Slope, BW )
%
% This file constructs a real-valued magnitude response in 4D, for which the passband is a hyperfan.
% This is useful for selecting objects over a range of depths from a lightfield, i.e. volumetric
% focus.
%
% Once constructed the filter must be applied to a light field, e.g. using LFFilt4DFFT. The
% LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters.
%
% A more technical discussion, including the use of filters for denoising and volumetric focus, and
% the inclusion of aliases components, is included in:
%
% [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field
% Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015.
%
% Inputs:
%
% LFSize : Size of the frequency-domain filter. This should match or exceed the size of the
% light field to be filtered. If it's larger than the input light field, the input is
% zero-padded to match the filter's size by LFFilt4DFFT.
%
% Slope : The slope of the planar passband. If different slopes are desired in s,t and u,v,
% the optional aspect parameter should be used.
%
% BW : 3-db Bandwidth of the planar passband.
%
% [optional] FiltOptions : struct controlling filter construction
% SlopeMethod : 'Skew' or 'Rotate' default 'skew'
% Precision : 'single' or 'double', default 'single'
% Rolloff : 'Gaussian' or 'Butter', default 'Gaussian'
% Order : controls the order of the filter when Rolloff is 'Butter', default 3
% Aspect4D : aspect ratio of the light field, default [1 1 1 1]
% Window : Default false. By default the edges of the passband are sharp; this adds
% a smooth rolloff at the edges when used in conjunction with Extent4D or
% IncludeAliased.
% Extent4D : controls where the edge of the passband occurs, the default [1 1 1 1]
% is the edge of the Nyquist box. When less than 1, enabling windowing
% introduces a rolloff after the edge of the passband. Can be greater
% than 1 when using IncludeAliased.
% IncludeAliased : default false; allows the passband to wrap around off the edge of the
% Nyquist box; used in conjunction with Window and/or Extent4D. This can
% increase processing time dramatically, e.g. Extent4D = [2,2,2,2]
% requires a 2^4 = 16-fold increase in time to construct the filter.
% Useful when passband content is aliased, see [2].
%
% Outputs:
%
% H : real-valued frequency magnitude response
% FiltOptions : The filter options including defaults, with an added PassbandInfo field
% detailing the function and time of construction of the filter
%
% See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01,
% LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone,
% LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [H, FiltOptions] = LFBuild4DFreqHyperfan( LFSize, Slope1, Slope2, BW, FiltOptions )
FiltOptions = LFDefaultField('FiltOptions', 'HyperfanMethod', 'Direct'); % 'Direct', 'Sweep'
switch( lower(FiltOptions.HyperfanMethod ))
case 'sweep'
FiltOptions = LFDefaultField('FiltOptions', 'SweepSteps', 5);
SweepVec = linspace(Slope1, Slope2, FiltOptions.SweepSteps);
[H, FiltOptions] = LFBuild4DFreqPlane( LFSize, SweepVec(1), BW, FiltOptions );
for( CurSlope = SweepVec(2:end) )
H = max(H, LFBuild4DFreqPlane( LFSize, CurSlope, BW, FiltOptions ));
end
case 'direct'
FiltOptions = LFDefaultField('FiltOptions', 'HyperconeBW', BW);
[H, FiltOptions] = LFBuild4DFreqHypercone( LFSize, FiltOptions.HyperconeBW, FiltOptions );
[Hdf, FiltOptions] = LFBuild4DFreqDualFan( LFSize, Slope1, Slope2, BW, FiltOptions );
H = H .* Hdf;
otherwise
error('Unrecognized hyperfan construction method');
end
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
|
github
|
Vincentqyw/light-field-TB-master
|
LFUtilProcessCalibrations.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFUtilProcessCalibrations.m
| 3,086 |
utf_8
|
b7ed374da00985b749186101dccbfc70
|
% LFUtilProcessCalibrations - process a folder/tree of camera calibrations
%
% Usage:
%
% LFUtilProcessCalibrations
% LFUtilProcessCalibrations( CalibrationsPath )
% LFUtilProcessCalibrations( CalibrationsPath, FileOptions )
% LFUtilProcessCalibrations( [], FileOptions )
%
% All parameters are optional and take on default values as set in the "Defaults" section at the top
% of the implementation. As such, this can be called as a function or run directly by editing the
% code. When calling as a function, pass an empty array "[]" to omit a parameter.
%
% This function recursively crawls through a folder identifying camera "calibration info" files and
% building a database for use in selecting a calibration appropriate to a light field. An example
% usage is in the image rectification code in LFUtilDecodeLytroFolder / LFSelectFromDatabase.
%
% Inputs -- all are optional, see code below for default values :
%
% CalibrationsPath : Path to folder containing calibrations -- note the function operates
% recursively, i.e. it will search sub-folders. The calibration database will
% be created at the top level of this path. A typical configuration is to
% create a "Cameras" folder with a separate subfolder of calibrations for each
% camera in use. The appropriate path to pass to this function is the top
% level of that cameras folder.
%
%
% FileOptions : struct controlling file naming and saving
% .SaveResult : Set to false to perform a "dry run"
% .CalibrationDatabaseFname : Name of file to which white image database is saved
% .CalInfoFilenamePattern : File search pattern for finding calibrations
%
% Output takes the form of a saved calibration database.
%
% See also: LFUtilDecodeLytroFolder, LFCalRectifyLF, LFSelectFromDatabase, LFUtilCalLensletCam,
% LFUtilProcessWhiteImages
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LFUtilProcessCalibrations( CalibrationsPath, FileOptions )
%---Defaults---
CalibrationsPath = LFDefaultVal( 'CalibrationsPath', 'Cameras' );
FileOptions = LFDefaultField( 'FileOptions', 'SaveResult', true );
FileOptions = LFDefaultField( 'FileOptions', 'CalibrationDatabaseFname', 'CalibrationDatabase.mat' );
FileOptions = LFDefaultField( 'FileOptions', 'CalInfoFilenamePattern', 'CalInfo*.json' );
%---Crawl folder structure locating calibrations---
fprintf('Building database of calibrations in %s\n', CalibrationsPath);
CamInfo = LFGatherCamInfo( CalibrationsPath, FileOptions.CalInfoFilenamePattern );
%---Optionally save---
if( FileOptions.SaveResult )
SaveFpath = fullfile(CalibrationsPath, FileOptions.CalibrationDatabaseFname);
fprintf('Saving to %s\n', SaveFpath);
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
save(SaveFpath, 'GeneratedByInfo', 'CamInfo');
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFUtilExtractLFPThumbs.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFUtilExtractLFPThumbs.m
| 2,528 |
utf_8
|
bcf530be1d01e6c00268cf5bbf398fde
|
% LFUtilExtractLFPThumbs - extract thumbnails from LFP files and write to disk
%
% Usage:
%
% LFUtilExtractLFPThumbs
% LFUtilExtractLFPThumbs( InputPath )
%
% This extracts the thumbnail preview and focal stack images from LFR and LFP files, and is useful in providing a
% preview, e.g. when copying files directly from an Illum camera.
%
% Inputs -- all are optional :
%
% InputPath : Path / filename pattern for locating LFP files. The function will move recursively through a tree,
% matching one or more filename patterns. See LFFindFilesRecursive for a full description.
%
% The default input path is {'.', '*.LFP','*.LFR','*.lfp','*.lfr'}, i.e. the current folder, recursively searching
% for all files matching uppercase and lowercase 'LFP' and 'LFR' extensions.
%
% Examples:
%
% LFUtilExtractLFPThumbs
%
% Will extract thumbnails from all LFP and LFR images in the current folder and its subfolders.
%
% The following are also valid, see LFFindFilesRecursive for more.
%
% LFUtilExtractLFPThumbs('Images')
% LFUtilExtractLFPThumbs({'*.lfr','*.lfp'})
% LFUtilExtractLFPThumbs({'Images','*.lfr','*.lfp'})
% LFUtilExtractLFPThumbs('Images/*.lfr')
% LFUtilExtractLFPThumbs('*.lfr')
% LFUtilExtractLFPThumbs('Images/IMG_0001.LFR')
% LFUtilExtractLFPThumbs('IMG_0001.LFR')
%
% See also: LFFindFilesRecursive
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LFUtilExtractLFPThumbs( InputPath )
%---Defaults---
InputPath = LFDefaultVal( 'InputPath','.' );
DefaultFileSpec = {'*.LFP','*.LFR','*.lfp','*.lfr'}; % gets overriden below, if a file spec is provided
[FileList, BasePath] = LFFindFilesRecursive( InputPath, DefaultFileSpec );
fprintf('Found :\n');
disp(FileList)
%---Process each file---
for( iFile = 1:length(FileList) )
CurFname = fullfile(BasePath, FileList{iFile});
fprintf('Processing [%d / %d] %s\n', iFile, length(FileList), CurFname);
LFP = LFReadLFP( CurFname );
if( ~isfield(LFP, 'Jpeg') )
continue;
end
if( ~iscell(LFP.Jpeg) )
LFP.Jpeg = {LFP.Jpeg};
end
for( i=1:length(LFP.Jpeg) )
OutFname = sprintf('%s-%03d.jpg', CurFname, i-1);
fprintf('%s', OutFname);
if( exist(OutFname,'file') )
fprintf(' Exists, skipping\n');
else
OutFile = fopen(OutFname, 'wb');
fwrite(OutFile, LFP.Jpeg{i});
fclose(OutFile);
fprintf('\n');
end
end
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFFilt2DFFT.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFFilt2DFFT.m
| 4,344 |
utf_8
|
94c37a901f7a9a1271d469d23be351cc
|
% LFFilt2DFFT - Apply a 2D frequency-domain filter to a 4D light field using the FFT
%
% Usage:
%
% [LF, FiltOptions] = LFFilt2DFFT( LF, H, FiltDims, FiltOptions )
% LF = LFFilt2DFFT( LF, H, FiltDims )
%
%
% This filter works on 2D slices of the input light field, applying the 2D filter H to each in turn. It takes the FFT
% of each slice of the input light field, multiplies by the provided magnitude response H, then calls the inverse FFT.
%
% The FiltDims input specifies the two dimensions along which H should be applied. The frequency-domain filter H should
% match or exceed the size of the light field LF in these dimensions. If H is larger than the input light field, LF is
% zero-padded to match the filter's size. If a weight channel is present in the light field it gets used during
% normalization.
%
% See LFDemoBasicFiltLytro for example usage.
%
%
% Inputs
%
% LF : The light field to be filtered
%
% H : The frequency-domain filter to apply, as constructed by one of the LFBuild4DFreq* functions
%
% FiltDims : The dimensions along which H should be applied
%
% [optional] FiltOptions : struct controlling filter operation
% Precision : 'single' or 'double', default 'single'
% Normalize : default true; when enabled the output is normalized so that darkening near image edges is
% removed
% MinWeight : during normalization, pixels for which the output value is not well defined (i.e. for
% which the filtered weight is very low) get set to 0. MinWeight sets the threshold at which
% this occurs, default is 10 * the numerical precision of the output, as returned by eps
%
% Outputs:
%
% LF : The filtered 4D light field
% FiltOptions : The filter options including defaults, with an added FilterInfo field detailing the function and
% time of filtering.
%
% See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, LFBuild2DFreqFan, LFBuild2DFreqLine,
% LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT,
% LFFiltShiftSum
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [LF, FiltOptions] = LFFilt2DFFT( LF, H, FiltDims, FiltOptions )
FiltOptions = LFDefaultField('FiltOptions', 'Precision', 'single');
FiltOptions = LFDefaultField('FiltOptions', 'Normalize', true);
FiltOptions = LFDefaultField('FiltOptions', 'MinWeight', 10*eps(FiltOptions.Precision));
%---
NColChans = size(LF,5);
HasWeight = ( NColChans == 4 || NColChans == 2 );
if( HasWeight )
NColChans = NColChans-1;
end
%---
IterDims = 1:4;
IterDims(FiltDims) = 0;
IterDims = find(IterDims~=0);
PermuteOrder = [IterDims, FiltDims, 5];
LF = permute(LF, PermuteOrder);
LF = LFConvertToFloat(LF, FiltOptions.Precision);
%---
LFSize = size(LF);
SlicePaddedSize = size(H);
for( IterDim1 = 1:LFSize(1) )
fprintf('.');
for( IterDim2 = 1:LFSize(2) )
CurSlice = squeeze(LF(IterDim1,IterDim2,:,:,:));
if( FiltOptions.Normalize )
if( HasWeight )
for( iColChan = 1:NColChans )
CurSlice(:,:,iColChan) = CurSlice(:,:,iColChan) .* CurSlice(:,:,end);
end
else % add a weight channel
CurSlice(:,:,end+1) = ones(size(CurSlice(:,:,1)), FiltOptions.Precision);
end
end
SliceSize = size(CurSlice);
for( iColChan = 1:SliceSize(end) )
X = fftn(CurSlice(:,:,iColChan), SlicePaddedSize);
X = X .* H;
x = ifftn(X,'symmetric');
x = x(1:LFSize(3), 1:LFSize(4));
CurSlice(:,:,iColChan) = x;
end
if( FiltOptions.Normalize )
WeightChan = CurSlice(:,:,end);
InvalidIdx = find(WeightChan < FiltOptions.MinWeight);
ChanSize = numel(CurSlice(:,:,1));
for( iColChan = 1:NColChans )
CurSlice(:,:,iColChan) = CurSlice(:,:,iColChan) ./ WeightChan;
CurSlice( InvalidIdx + ChanSize.*(iColChan-1) ) = 0;
end
end
% record channel
LF(IterDim1,IterDim2,:,:,:) = CurSlice(:,:,1:LFSize(5));
end
end
LF = max(0,LF);
LF = min(1,LF);
LF = ipermute(LF, PermuteOrder);
%---
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
FiltOptions.FilterInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
fprintf(' Done\n');
|
github
|
Vincentqyw/light-field-TB-master
|
LFBuild2DFreqLine.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFBuild2DFreqLine.m
| 4,431 |
utf_8
|
0dcc452b6b957958b7243b285453790b
|
% LFBuild2DFreqLine - construct a 2D line passband filter in the frequency domain
%
% Usage:
%
% [H, FiltOptions] = LFBuild2DFreqLine( LFSize, Slope, BW, FiltOptions )
% H = LFBuild2DFreqLine( LFSize, Slope, BW )
%
% This file constructs a real-valued magnitude response in 2D, for which the passband is a line. The cascade of two line
% filters, applied in s,u and in t,v, is identical to a 4D planar filter, e.g. that constructed by LFBuild4DFreqPlane.
%
% Once constructed the filter must be applied to a light field, e.g. using LFFilt2DFFT. The
% LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters.
%
% A more technical discussion, including the use of filters for denoising and volumetric focus, and
% the inclusion of aliases components, is included in:
%
% [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field
% Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015.
%
% Inputs:
%
% LFSize : Size of the frequency-domain filter. This should match or exceed the size of the
% light field to be filtered. If it's larger than the input light field, the input is
% zero-padded to match the filter's size by LFFilt2DFFT.
%
% Slope : Slopes at the extents of the fan passband.
%
% BW : 3-db Bandwidth of the planar passband.
%
% [optional] FiltOptions : struct controlling filter construction
% SlopeMethod : only 'Skew' is supported for now
% Precision : 'single' or 'double', default 'single'
% Rolloff : 'Gaussian' or 'Butter', default 'Gaussian'
% Order : controls the order of the filter when Rolloff is 'Butter', default 3
% Aspect2D : aspect ratio of the light field, default [1 1]
% Window : Default false. By default the edges of the passband are sharp; this adds
% a smooth rolloff at the edges when used in conjunction with Extent2D or
% IncludeAliased.
% Extent2D : controls where the edge of the passband occurs, the default [1 1]
% is the edge of the Nyquist box. When less than 1, enabling windowing
% introduces a rolloff after the edge of the passband. Can be greater
% than 1 when using IncludeAliased.
% IncludeAliased : default false; allows the passband to wrap around off the edge of the
% Nyquist box; used in conjunction with Window and/or Extent2D. This can
% increase processing time dramatically, e.g. Extent2D = [2,2]
% requires a 2^2 = 4-fold increase in time to construct the filter.
% Useful when passband content is aliased, see [2].
%
% Outputs:
%
% H : real-valued frequency magnitude response
% FiltOptions : The filter options including defaults, with an added PassbandInfo field
% detailing the function and time of construction of the filter
%
% See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01,
% LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone,
% LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [H, FiltOptions] = LFBuild2DFreqLine( LFSize, Slope, BW, FiltOptions )
FiltOptions = LFDefaultField('FiltOptions', 'SlopeMethod', 'Skew'); % 'Skew', 'Rotate'
DistFunc = @(P, FiltOptions) DistFunc_2DLine( P, Slope, FiltOptions );
[H, FiltOptions] = LFHelperBuild2DFreq( LFSize, BW, FiltOptions, DistFunc );
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
end
%-----------------------------------------------------------------------------------------------------------------------
function Dist = DistFunc_2DLine( P, Slope, FiltOptions )
switch( lower(FiltOptions.SlopeMethod) )
case 'skew'
R = eye(2);
R(1,2) = Slope;
case 'rotate'
Angle = -atan2(Slope,1);
R = LFRotz( Angle );
R = R(1:2,1:2);
otherwise
error('Unrecognized slope method');
end
P = R * P;
Dist = P(1,:).^2;
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFColourCorrect.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFColourCorrect.m
| 1,999 |
utf_8
|
07c213f4b7fbcaa5ad2fae5e30c82edf
|
% LFColourCorrect - applies a colour correction matrix, balance vector, and gamma, called by LFUtilDecodeLytroFolder
%
% Usage:
% LF = LFColourCorrect( LF, ColMatrix, ColBalance, Gamma )
%
% This implementation deals with saturated input pixels by aggressively saturating output pixels.
%
% Inputs :
%
% LF : a light field or image to colour correct. It should be a floating point array, and
% may be of any dimensinality so long as the last dimension has length 3. For example, a 2D
% image of size [Nl,Nk,3], a 4D image of size [Nj,Ni,Nl,Nk,3], and a 1D list of size [N,3]
% are all valid.
%
% ColMatrix : a 3x3 colour conversion matrix. This can be built from the metadata provided
% with Lytro imagery using the command:
% ColMatrix = reshape(cell2mat(LFMetadata.image.color.ccmRgbToSrgbArray), 3,3);
% as demonstrated in LFUtilDecodeLytroFolder.
%
% ColBalance : 3-element vector containing a multiplicative colour balance.
%
% Gamma : rudimentary gamma correction is applied of the form LF = LF.^Gamma.
%
% Outputs :
%
% LF, of the same dimensionality as the input.
%
%
% See also: LFHistEqualize, LFUtilDecodeLytroFolder
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LF = LFColourCorrect(LF, ColMatrix, ColBalance, Gamma)
LFSize = size(LF);
% Flatten input to a flat list of RGB triplets
NDims = numel(LFSize);
LF = reshape(LF, [prod(LFSize(1:NDims-1)), 3]);
LF = bsxfun(@times, LF, ColBalance);
LF = LF * ColMatrix;
% Unflatten result
LF = reshape(LF, [LFSize(1:NDims-1),3]);
% Saturating eliminates some issues with clipped pixels, but is aggressive and loses information
% todo[optimization]: find a better approach to dealing with saturated pixels
SaturationLevel = ColBalance*ColMatrix;
SaturationLevel = min(SaturationLevel);
LF = min(SaturationLevel,max(0,LF)) ./ SaturationLevel;
% Apply gamma
LF = LF .^ Gamma;
|
github
|
Vincentqyw/light-field-TB-master
|
LFBuild4DFreqPlane.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFBuild4DFreqPlane.m
| 4,768 |
utf_8
|
44b35c86e926ed95961fbf34e0872ffb
|
% LFBuild4DFreqPlane - construct a 4D planar passband filter in the frequency domain
%
% Usage:
%
% [H, FiltOptions] = LFBuild4DFreqPlane( LFSize, Slope, BW, FiltOptions )
% H = LFBuild4DFreqPlane( LFSize, Slope, BW )
%
% This file constructs a real-valued magnitude response in 4D, for which the passband is a plane.
% This is useful for selecting objects at a single depth from a lightfield, and is similar in effect
% to refocus using, for example, the shift sum filter LFFiltShiftSum.
%
% Once constructed the filter must be applied to a light field, e.g. using LFFilt4DFFT. The
% LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters.
%
% A more technical discussion, including the use of filters for denoising and volumetric focus, and
% the inclusion of aliases components, is included in:
%
% [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field
% Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015.
%
% Inputs:
%
% LFSize : Size of the frequency-domain filter. This should match or exceed the size of the
% light field to be filtered. If it's larger than the input light field, the input is
% zero-padded to match the filter's size by LFFilt4DFFT.
%
% Slope : The slope of the planar passband. If different slopes are desired in s,t and u,v,
% the optional aspect parameter should be used.
%
% BW : 3-db Bandwidth of the planar passband.
%
% [optional] FiltOptions : struct controlling filter construction
% SlopeMethod : 'Skew' or 'Rotate' default 'skew'
% Precision : 'single' or 'double', default 'single'
% Rolloff : 'Gaussian' or 'Butter', default 'Gaussian'
% Order : controls the order of the filter when Rolloff is 'Butter', default 3
% Aspect4D : aspect ratio of the light field, default [1 1 1 1]
% Window : Default false. By default the edges of the passband are sharp; this adds
% a smooth rolloff at the edges when used in conjunction with Extent4D or
% IncludeAliased.
% Extent4D : controls where the edge of the passband occurs, the default [1 1 1 1]
% is the edge of the Nyquist box. When less than 1, enabling windowing
% introduces a rolloff after the edge of the passband. Can be greater
% than 1 when using IncludeAliased.
% IncludeAliased : default false; allows the passband to wrap around off the edge of the
% Nyquist box; used in conjunction with Window and/or Extent4D. This can
% increase processing time dramatically, e.g. Extent4D = [2,2,2,2]
% requires a 2^4 = 16-fold increase in time to construct the filter.
% Useful when passband content is aliased, see [2].
%
% Outputs:
%
% H : real-valued frequency magnitude response
% FiltOptions : The filter options including defaults, with an added PassbandInfo field
% detailing the function and time of construction of the filter
%
% See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01,
% LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone,
% LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [H, FiltOptions] = LFBuild4DFreqPlane( LFSize, Slope, BW, FiltOptions )
FiltOptions = LFDefaultField('FiltOptions', 'SlopeMethod', 'Skew'); % 'Skew', 'Rotate'
DistFunc = @(P, FiltOptions) DistFunc_4DPlane( P, Slope, FiltOptions );
[H, FiltOptions] = LFHelperBuild4DFreq( LFSize, BW, FiltOptions, DistFunc );
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
end
%-----------------------------------------------------------------------------------------------------------------------
function Dist = DistFunc_4DPlane( P, Slope, FiltOptions )
switch( lower(FiltOptions.SlopeMethod) )
case 'skew'
R = eye(4);
R(1,3) = Slope;
R(2,4) = Slope;
case 'rotate'
Angle = -atan2(Slope,1);
R2D = LFRotz( Angle );
R = eye(4);
R(1,1) = R2D(1,1);
R(1,3) = R2D(1,2);
R(3,1) = R2D(2,1);
R(3,3) = R2D(2,2);
R(2,2) = R2D(1,1);
R(2,4) = R2D(1,2);
R(4,2) = R2D(2,1);
R(4,4) = R2D(2,2);
otherwise
error('Unrecognized slope method');
end
P = R * P;
Dist = P(2,:).^2 + P(1,:).^2;
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFFindFilesRecursive.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFFindFilesRecursive.m
| 3,789 |
utf_8
|
d7e26a587e0dd5460fb2f59371802d2e
|
% LFFindFilesRecursive - Recursively searches a folder for files matching one or more patterns
%
% Usage:
%
% [AllFiles, BasePath, FolderList, PerFolderFiles] = LFFindFilesRecursive( InputPath )
%
% Inputs:
%
% InputPath: the folder to recursively search
%
% Outputs:
%
% Allfiles : A list of all files found
% BasePath : Top of the searched tree, excluding wildcards
% FolderList : A list of all the folders explored
% PerFolderFiles : A list of files organied by folder -- e.g. PerFolderFiles{1} are all the files
% found in FolderList{1}
%
% Examples:
%
% LFFindFilesRecursive('Images')
% LFFindFilesRecursive({'*.lfr','*.lfp'})
% LFFindFilesRecursive({'Images','*.lfr','*.lfp'})
% LFFindFilesRecursive('Images/*.lfr')
% LFFindFilesRecursive('*.lfr')
% LFFindFilesRecursive('Images/IMG_0001.LFR')
% LFFindFilesRecursive('IMG_0001.LFR')
%
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [AllFiles, BasePath, FolderList, PerFolderFiles] = LFFindFilesRecursive( InputPath, DefaultFileSpec, DefaultPath )
PerFolderFiles = [];
AllFiles = [];
%---Defaults---
DefaultFileSpec = LFDefaultVal( 'DefaultFileSpec', {'*'} );
DefaultPath = LFDefaultVal( 'DefaultPath', '.' );
InputPath = LFDefaultVal( 'InputPath', '.' );
PathOnly = '';
if( ~iscell(InputPath) )
InputPath = {InputPath};
end
if( ~iscell(DefaultFileSpec) )
DefaultFileSpec = {DefaultFileSpec};
end
InputFileSpec = DefaultFileSpec;
if( exist(InputPath{1}, 'dir') ) % try interpreting first param as a folder, if it exists, grab is as such
PathOnly = InputPath{1};
InputPath(1) = [];
end
if( numel(InputPath) > 0 ) % interpret remaining elements as filespecs
% Check if the filespec includes a folder name, and crack it out as part of the input path
[MorePath, Stripped, Ext] = fileparts(InputPath{1});
PathOnly = fullfile(PathOnly, MorePath);
InputPath{1} = [Stripped,Ext];
InputFileSpec = InputPath;
end
PathOnly = LFDefaultVal('PathOnly', DefaultPath);
InputPath = PathOnly;
% Clean up the inputpath to omit trailing slashes
while( InputPath(end) == filesep )
InputPath = InputPath(1:end-1);
end
BasePath = InputPath;
%---Crawl folder structure locating raw lenslet images---
fprintf('Searching for files [ ');
fprintf('%s ', InputFileSpec{:});
fprintf('] in %s\n', InputPath);
%---
FolderList = genpath(InputPath);
if( isempty(FolderList) )
error(['Input path not found... are you running from the correct folder? ' ...
'Current folder: %s'], pwd);
end
FolderList = textscan(FolderList, '%s', 'Delimiter', pathsep);
FolderList = FolderList{1};
%---Compile a list of all files---
PerFolderFiles = cell(length(FolderList),1);
for( iFileSpec=1:length(InputFileSpec) )
FilePattern = InputFileSpec{iFileSpec};
for( iFolder = 1:length(FolderList) )
%---Search each subfolder for raw lenslet files---
CurFolder = FolderList{iFolder};
CurDirList = dir(fullfile(CurFolder, FilePattern));
CurDirList = CurDirList(~[CurDirList.isdir]);
CurDirList = {CurDirList.name};
PerFolderFiles{iFolder} = [PerFolderFiles{iFolder}, CurDirList];
% Prepend the current folder name for a complete path to each file
% but fist strip off the leading InputPath so that all files are expressed relative to InputPath
CurFolder = CurFolder(length(InputPath)+1:end);
while( ~isempty(CurFolder) && CurFolder(1) == filesep )
CurFolder = CurFolder(2:end);
end
CurDirList = cellfun(@(Fname) fullfile(CurFolder, Fname), CurDirList, 'UniformOutput',false);
AllFiles = [AllFiles; CurDirList'];
end
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFDispMousePan.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFDispMousePan.m
| 3,147 |
utf_8
|
19664da990653623f36d25770af65dec
|
% LFDispMousePan - visualize a 4D light field using the mouse to pan through two dimensions
%
% Usage:
% FigureHandle = LFDispMousePan( LF )
% FigureHandle = LFDispMousePan( LF, ScaleFactor )
%
% A figure is set up for high-performance display, with the tag 'LFDisplay'. Subsequent calls to
% this function and LFDispVidCirc will reuse the same figure, rather than creating a new window on
% each call. The window should be closed when changing ScaleFactor.
%
% Inputs:
%
% LF : a colour or single-channel light field, and can a floating point or integer format. For
% display, it is converted to 8 bits per channel. If LF contains more than three colour
% channels, as is the case when a weight channel is present, only the first three are used.
%
% Optional Inputs:
%
% ScaleFactor : Adjusts the size of the display -- 1 means no change, 2 means twice as big, etc.
% Integer values are recommended to avoid scaling artifacts. Note that the scale
% factor is only applied the first time a figure is created. To change the scale
% factor, close the figure before calling LFDispMousePan.
%
% Outputs:
%
% FigureHandle
%
%
% See also: LFDisp, LFDispVidCirc
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function FigureHandle = LFDispMousePan( LF, varargin )
%---Defaults---
MouseRateDivider = 30;
%---Check for weight channel---
HasWeight = (size(LF,5) == 4);
%---Discard weight channel---
if( HasWeight )
LF = LF(:,:,:,:,1:3);
end
%---Rescale for 8-bit display---
if( isfloat(LF) )
LF = uint8(LF ./ max(LF(:)) .* 255);
else
LF = uint8(LF.*(255 / double(intmax(class(LF)))));
end
%---Setup the display---
[ImageHandle,FigureHandle] = LFDispSetup( squeeze(LF(max(1,floor(end/2)),max(1,floor(end/2)),:,:,:)), varargin{:} );
BDH = @(varargin) ButtonDownCallback(FigureHandle, varargin);
BUH = @(varargin) ButtonUpCallback(FigureHandle, varargin);
set(FigureHandle, 'WindowButtonDownFcn', BDH );
set(FigureHandle, 'WindowButtonUpFcn', BUH );
[TSize,SSize, ~,~] = size(LF(:,:,:,:,1));
CurX = max(1,floor((SSize-1)/2+1));
CurY = max(1,floor((TSize-1)/2+1));
DragStart = 0;
%---Update frame before first mouse drag---
LFRender = squeeze(LF(round(CurY), round(CurX), :,:,:));
set(ImageHandle,'cdata', LFRender);
fprintf('Click and drag to shift perspective\n');
function ButtonDownCallback(FigureHandle,varargin)
set(FigureHandle, 'WindowButtonMotionFcn', @ButtonMotionCallback);
DragStart = get(gca,'CurrentPoint')';
DragStart = DragStart(1:2,1)';
end
function ButtonUpCallback(FigureHandle, varargin)
set(FigureHandle, 'WindowButtonMotionFcn', '');
end
function ButtonMotionCallback(varargin)
CurPoint = get(gca,'CurrentPoint');
CurPoint = CurPoint(1,1:2);
RelPoint = CurPoint - DragStart;
CurX = max(1,min(SSize, CurX - RelPoint(1)/MouseRateDivider));
CurY = max(1,min(TSize, CurY - RelPoint(2)/MouseRateDivider));
DragStart = CurPoint;
LFRender = squeeze(LF(round(CurY), round(CurX), :,:,:));
set(ImageHandle,'cdata', LFRender);
end
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFReadGantryArray.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFReadGantryArray.m
| 4,902 |
utf_8
|
80dc406ff9c8008ff8aa0877a0fcdb0f
|
% LFReadGantryArray - load gantry-style light field, e.g. the Stanford light fields at lightfield.stanford.edu
%
% Usage:
%
% LF = LFReadGantryArray( InputPath, DecodeOptions )
%
% To use, download and unzip an image archive from the Stanford light field archive, and pass this function the path to
% the unzipped files. All inputs are optional, by default the light field is loaded from the current directory.
% DecodeOptions.UVScale and DecodeOptions.UVLimit allow the input images to be scaled, either by the constant factor
% UVScale, or to achieve the maximum u,v image size specified by UVLimit. If both UVScale and UVLimit are specified, the
% one resulting in smaller images is applied.
%
% The defaults are all set to load Stanford Lego Gantry light fields, and must be adjusted for differently sized or
% ordered light fields.
%
% Inputs :
%
% InputPath : path to folder of image files, e.g. as obtained by decompressing a Stanford light field
%
% DecodeOptions :
% UVScale : constant scaling factor applied to each input image; default: 1
% UVLimit : scale is adjusted to ensure a maximum image dimension of DecodeOptions.UVLimit
% Order : 'RowMajor' or 'ColumnMajor', specifies the order in which images appear when sorted
% alphabetically; default: 'RowMajor'
% STSize : Size of the array of images; default: [17, 17]
% FnamePattern : Pattern used to locate input file, using standard wildcards; default '*.png'
%
% Outputs:
%
% LF : 5D array containing a 3-channel (RGB) light field, indexed in the order [j,i,l,k, colour]
% DecodeOptions : Reflects the parameters as applied, including the UVScale resulting from UVLimit
%
%
% Example 1:
%
% After unzipping the LegoKnights Stanford light fields into '~/Data/Stanford/LegoKnights/rectified', the following
% reads the light field at full resolution, yielding a 17 x 17 x 1024 x 1024 x 3 array, occupying 909 MBytes of RAM:
%
% LF = LFReadGantryArray('~/Data/Stanford/LegoKnights/rectified');
%
% Example 2:
%
% As above, but scales each image to a maximum dimension of 256 pixels, yielding a 17 x 17 x 256 x 256 x 3 array.
% LFDIspMousePan then displays the light field, click and pan around to view the light field.
%
% LF = LFReadGantryArray('~/Data/Stanford/LegoKnights/rectified', struct('UVLimit', 256));
% LFDispMousePan(LF)
%
% Example 3:
%
% A few of the Stanford "Gantry" (not "Lego Gantry") light fields follow a lawnmower pattern. These can be read and
% adjusted as follows:
%
% LF = LFReadGantryArray('humvee-tree', struct('STSize', [16,16]));
% LF(1:2:end,:,:,:,:) = LF(1:2:end,end:-1:1,:,:,:);
% See also: LFDispMousePan, LFDispVidCirc
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [LF, DecodeOptions] = LFReadGantryArray( InputPath, DecodeOptions )
InputPath = LFDefaultVal('InputPath', '.');
DecodeOptions = LFDefaultField('DecodeOptions','UVScale', 1);
DecodeOptions = LFDefaultField('DecodeOptions','UVLimit', []);
DecodeOptions = LFDefaultField('DecodeOptions','STSize', [17,17]);
DecodeOptions = LFDefaultField('DecodeOptions','FnamePattern', '*.png');
DecodeOptions = LFDefaultField('DecodeOptions','Order', 'RowMajor');
%---Gather info---
FList = dir(fullfile(InputPath, DecodeOptions.FnamePattern));
if( isempty(FList) )
error('No files found');
end
NumImgs = length(FList);
assert( NumImgs == prod(DecodeOptions.STSize), 'Unexpected image count: expected %d x %d = %d found %d', ...
DecodeOptions.STSize(1), DecodeOptions.STSize(2), prod(DecodeOptions.STSize), NumImgs );
%---Get size, scaling info from first file, assuming all are same size---
Img = imread(fullfile(InputPath, FList(1).name));
ImgClass = class(Img);
UVSizeIn = size(Img);
if( ~isempty(DecodeOptions.UVLimit) )
UVMinScale = min(DecodeOptions.UVLimit ./ UVSizeIn(1:2));
DecodeOptions.UVScale = min(DecodeOptions.UVScale, UVMinScale);
end
Img = imresize(Img, DecodeOptions.UVScale);
UVSize = size(Img);
TSize = DecodeOptions.STSize(2);
SSize = DecodeOptions.STSize(1);
VSize = UVSize(1);
USize = UVSize(2);
%---Allocate mem---
LF = zeros(TSize, SSize, VSize,USize, 3, ImgClass);
LF(1,1,:,:,:) = Img;
switch( lower(DecodeOptions.Order) )
case 'rowmajor'
[SIdx,TIdx] = ndgrid( 1:SSize, 1:TSize );
case 'columnmajor'
[TIdx,SIdx] = ndgrid( 1:TSize, 1:SSize );
otherwise
error( 'Unrecognized image order' );
end
%---Load and scale images---
fprintf('Loading %d images', NumImgs);
for(i=2:NumImgs)
if( mod(i, ceil(length(FList)/10)) == 0 )
fprintf('.');
end
Img = imread(fullfile(InputPath, FList(i).name));
Img = imresize(Img, DecodeOptions.UVScale);
LF(TIdx(i),SIdx(i),:,:,:) = Img;
end
fprintf(' done\n');
|
github
|
Vincentqyw/light-field-TB-master
|
LFRecenterIntrinsics.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFRecenterIntrinsics.m
| 599 |
utf_8
|
95e4073ad162508fcaf1705124873fc5
|
% LFRecenterIntrinsics - Recenter a light field intrinsic matrix
%
% Usage:
% H = LFRecenterIntrinsics( H, LFSize )
%
% The recentering works by forcing the central sample in a light field of LFSize samples to
% correspond to the ray [s,t,u,v] = 0. Note that 1-based indexing is assumed in [i,j,k,l].
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function H = LFRecenterIntrinsics( H, LFSize )
CenterRay = [(LFSize([2,1,4,3])-1)/2 + 1, 1]'; % note indices start at 1
H(1:4,5) = 0;
Decentering = H * CenterRay;
H(1:4,5) = -Decentering(1:4);
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFCalDispRectIntrinsics.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFCalDispRectIntrinsics.m
| 3,804 |
utf_8
|
9881daba2d9060eef02a39e1c9ac81dd
|
% LFCalDispRectIntrinsics - Visualize sampling pattern resulting from a prescribed intrinsic matrix
%
% Usage:
% RectOptions = LFCalDispRectIntrinsics( LF, LFMetadata, RectOptions, PaintColour )
%
% During rectification, the matrix RectOptions.RectCamIntrinsicsH determines which subset of the light field gets
% sampled into the rectified light field. LFCalDispRectIntrinsics visualizes the resulting sampling pattern. The
% display is interactive, generated using LFDispMousePan, and can be explored by clicking and dragging the mouse.
%
% If no intrinsic matrix is provided, a default best-guess is constructed and returned in
% RectOptions.RectCamIntrinsicsH.
%
% A typical usage pattern is to load a light field, call LFCalDispRectIntrinsics to set up the default intrinsic
% matrix, manipulate the matrix, then visualize the manipulated sampling pattern prior to employing it in one or more
% rectification calls. The function LFRecenterIntrinsics is useful in maintaining a centered sampling pattern.
%
% This function relies on the presence of a calibration file and associated database, see LFUtilCalLensletCam and
% LFUtilDecodeLytroFolder.
%
% Inputs:
%
% LF : Light field to visualize
%
% LFMetadata : The light field's associated metadata - needed to locate the appropriate calibration file
%
% [optional] RectOptions : all fields are optional, see LFCalRectifyLF for all fields
% .RectCamIntrinsicsH : The intrinsic matrix to visualize
%
% [optional] PaintColour : RGB triplet defining a base drawing colour, RGB values are in the range 0-1
%
% Outputs:
%
% RectOptions : RectOptions updated with any defaults that were applied
% LF : The light field with visualized sample pattern
%
% See also: LFCalRectifyLF, LFRecenterIntrinsics, LFUtilCalLensletCam, LFUtilDecodeLytroFolder
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [RectOptions, LF] = LFCalDispRectIntrinsics( LF, LFMetadata, RectOptions, PaintColour )
PaintColour = LFDefaultVal( 'PaintColour', [0.5,1,1] );
[CalInfo, RectOptions] = LFFindCalInfo( LFMetadata, RectOptions );
%---Discard weight channel---
HasWeight = (size(LF,5) == 4);
if( HasWeight )
LF = LF(:,:,:,:,1:3);
end
LFSize = size(LF);
RectOptions = LFDefaultField( 'RectOptions', 'Precision', 'single' );
RectOptions = LFDefaultField( 'RectOptions', 'NInverse_Distortion_Iters', 2 );
RectOptions = LFDefaultField( 'RectOptions', 'RectCamIntrinsicsH', LFDefaultIntrinsics( LFSize, CalInfo ) );
if( isempty( CalInfo ) )
warning('No suitable calibration found, skipping');
return;
end
%--- visualize image utilization---
t_in=cast(1:LFSize(1), 'uint16');
s_in=cast(1:LFSize(2), 'uint16');
v_in=cast(1:10:LFSize(3), 'uint16');
u_in=cast(1:10:LFSize(4), 'uint16');
[tt,ss,vv,uu] = ndgrid(t_in,s_in,v_in,u_in);
InterpIdx = [ss(:)'; tt(:)'; uu(:)'; vv(:)'; ones(size(ss(:)'))];
InterpIdx = LFMapRectifiedToMeasured( InterpIdx, CalInfo, RectOptions );
InterpIdx = round(double(InterpIdx));
PaintVal = cast(double(max(LF(:))).*PaintColour, 'like', LF);
LF = 0.7*LF;
%---Clamp indices---
STUVChan = [2,1,4,3];
for( Chan=1:4 )
InterpIdx(Chan,:) = min(LFSize(STUVChan(Chan)), max(1,InterpIdx(Chan,:)));
end
%---Paint onto LF---
RInterpIdx = sub2ind( LFSize, InterpIdx(2,:), InterpIdx(1,:), InterpIdx(4,:), InterpIdx(3,:), 1*ones(size(InterpIdx(1,:))));
LF(RInterpIdx) = PaintVal(1);
RInterpIdx = sub2ind( LFSize, InterpIdx(2,:), InterpIdx(1,:), InterpIdx(4,:), InterpIdx(3,:), 2*ones(size(InterpIdx(1,:))));
LF(RInterpIdx) = PaintVal(2);
RInterpIdx = sub2ind( LFSize, InterpIdx(2,:), InterpIdx(1,:), InterpIdx(4,:), InterpIdx(3,:), 3*ones(size(InterpIdx(1,:))));
LF(RInterpIdx) = PaintVal(3);
%---Display LF---
LFDispMousePan( LF );
|
github
|
Vincentqyw/light-field-TB-master
|
LFFiltShiftSum.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFFiltShiftSum.m
| 5,666 |
utf_8
|
08be7f6f27c502a03f85f49912ae8183
|
% LFFiltShiftSum - a spatial-domain depth-selective filter, with an effect similar to planar focus
%
% Usage:
%
% [ImgOut, FiltOptions, LF] = LFFiltShiftSum( LF, Slope, FiltOptions )
% ImgOut = LFFiltShiftSum( LF, Slope )
%
%
% This filter works by shifting all u,v slices of the light field to a common depth, then adding the slices together to
% yield a single 2D output. The effect is very similar to planar focus, and by controlling the amount of shift one may
% focus on different depths. If a weight channel is present in the light field it gets used during normalization.
%
%
% See LFDemoBasicFiltLytro for example usage.
%
%
% Inputs
%
% LF : The light field to be filtered
%
% Slope : The amount by which light field slices should be shifted, this encodes the depth at which the output will
% be focused. The relationship between slope and depth depends on light field parameterization, but in
% general a slope of 0 lies near the center of the captured depth of field.
%
% [optional] FiltOptions : struct controlling filter operation
% Precision : 'single' or 'double', default 'single'
% Aspect4D : aspect ratio of the light field, default [1 1 1 1]
% Normalize : default true; when enabled the output is normalized so that darkening near image edges is
% removed
% FlattenMethod : 'Sum', 'Max' or 'Median', default 'Sum'; when the shifted light field slices are combined,
% they are by default added together, but median and max can also yield useful results.
% InterpMethod : default 'linear'; this is passed on to interpn to determine how shifted light field slices
% are found; other useful settings are 'nearest', 'cubic' and 'spline'
% ExtrapVal : default 0; when shifting light field slices, pixels falling outside the input light field
% are set to this value
% MinWeight : during normalization, pixels for which the output value is not well defined (i.e. for
% which the filtered weight is very low) get set to 0. MinWeight sets the threshold at which
% this occurs, default is 10 * the numerical precision of the output, as returned by eps
%
% Outputs:
%
% ImgOut : A 2D filtered image
% FiltOptions : The filter options including defaults, with an added FilterInfo field detailing the function and
% time of filtering.
% LF : The 4D light field resulting from the shifting operation
%
% See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, LFBuild2DFreqFan, LFBuild2DFreqLine,
% LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT,
% LFFiltShiftSum
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [ImgOut, FiltOptions, LF] = LFFiltShiftSum( LF, Slope, FiltOptions )
FiltOptions = LFDefaultField('FiltOptions', 'Precision', 'single');
FiltOptions = LFDefaultField('FiltOptions', 'Normalize', true);
FiltOptions = LFDefaultField('FiltOptions', 'MinWeight', 10*eps(FiltOptions.Precision));
FiltOptions = LFDefaultField('FiltOptions', 'Aspect4D', 1);
FiltOptions = LFDefaultField('FiltOptions', 'FlattenMethod', 'sum'); % 'Sum', 'Max', 'Median'
FiltOptions = LFDefaultField('FiltOptions', 'InterpMethod', 'linear');
FiltOptions = LFDefaultField('FiltOptions', 'ExtrapVal', 0);
if( length(FiltOptions.Aspect4D) == 1 )
FiltOptions.Aspect4D = FiltOptions.Aspect4D .* [1,1,1,1];
end
LFSize = size(LF);
NColChans = size(LF,5);
HasWeight = ( NColChans == 4 || NColChans == 2 );
if( HasWeight )
NColChans = NColChans-1;
end
LF = LFConvertToFloat(LF, FiltOptions.Precision);
%---
if( FiltOptions.Normalize )
if( HasWeight )
for( iColChan = 1:NColChans )
LF(:,:,:,:,iColChan) = LF(:,:,:,:,iColChan) .* LF(:,:,:,:,end);
end
else % add a weight channel
LF(:,:,:,:,end+1) = ones(size(LF(:,:,:,:,1)), FiltOptions.Precision);
end
end
%---
TVSlope = Slope * FiltOptions.Aspect4D(3) / FiltOptions.Aspect4D(1);
SUSlope = Slope * FiltOptions.Aspect4D(4) / FiltOptions.Aspect4D(2);
[vv, uu] = ndgrid(1:LFSize(3), 1:LFSize(4));
VVec = linspace(-0.5,0.5, LFSize(1)) * TVSlope*LFSize(1);
UVec = linspace(-0.5,0.5, LFSize(2)) * SUSlope*LFSize(2);
for( TIdx = 1:LFSize(1) )
VOffset = VVec(TIdx);
for( SIdx = 1:LFSize(2) )
UOffset = UVec(SIdx);
for( iChan=1:size(LF,5) )
CurSlice = squeeze(LF(TIdx, SIdx, :,:, iChan));
CurSlice = interpn(CurSlice, vv+VOffset, uu+UOffset, FiltOptions.InterpMethod, FiltOptions.ExtrapVal);
LF(TIdx,SIdx, :,:, iChan) = CurSlice;
end
end
fprintf('.');
end
switch( lower(FiltOptions.FlattenMethod) )
case 'sum'
ImgOut = squeeze(sum(sum(LF,1),2));
case 'max'
ImgOut = squeeze(max(max(LF,[],1),[],2));
case 'median'
t = reshape(LF, [prod(LFSize(1:2)), LFSize(3:end)]);
ImgOut = squeeze(median(t));
otherwise
error('Unrecognized method');
end
%---
if( FiltOptions.Normalize )
WeightChan = ImgOut(:,:,end);
InvalidIdx = find(WeightChan < FiltOptions.MinWeight);
ChanSize = numel(ImgOut(:,:,1));
for( iColChan = 1:NColChans )
ImgOut(:,:,iColChan) = ImgOut(:,:,iColChan) ./ WeightChan;
ImgOut( InvalidIdx + ChanSize.*(iColChan-1) ) = 0;
end
end
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
FiltOptions.FilterInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
|
github
|
Vincentqyw/light-field-TB-master
|
LFUtilUnpackLytroArchive.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFUtilUnpackLytroArchive.m
| 5,667 |
utf_8
|
0af0d42eaef631b6f44fbfc81dd81b3e
|
% LFUtilUnpackLytroArchive - extract white images and other files from a multi-volume Lytro archive
%
% Usage:
% LFUtilUnpackLytroArchive
% LFUtilUnpackLytroArchive( InputPath )
% LFUtilUnpackLytroArchive( InputPath, FirstVolumeFname )
% LFUtilUnpackLytroArchive( [], FirstVolumeFname )
%
% This extracts all the files from all Lytro archives found in the requested path. Archives typically take on names like
% data.C.0, data.C.1 and so forth, and contain white images, metadata and other information.
%
% The function searches for archives recursively, so if there are archives in multiple sub-folders, they will all be
% expanded. The file LFToolbox.json is created to mark completion of the extraction in a folder. Already-expanded
% archives are skipped; delete LFToolbox.json to force re-extraction in a folder.
%
% Based in part on Nirav Patel and Doug Kelley's LFP readers. Thanks to Michael Tao for help and samples for decoding
% Illum imagery.
%
% Inputs -- all are optional :
%
% InputPath : Path to folder containing the archive, default 'Cameras'
% FirstVolumeFname : Name of the first file in the archive, default 'data.C.0'
%
% Example:
%
% LFUtilUnpackLytroArchive
%
% Will extract the contents of all archives in all subfolders of the current folder. If you are working with
% multiple cameras, place each multi-volume archve in its own sub-folder, then call this from the top-level folder
% to expand them all.
%
% See also: LFUtilProcessWhiteImages, LFReadLFP, LFUtilExtractLFPThumbs
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LFUtilUnpackLytroArchive( InputPath, FirstVolumeFname )
%---Defaults---
InputPath = LFDefaultVal('InputPath','Cameras');
FirstVolumeFname = LFDefaultVal('FirstVolumeFname','data.C.0');
[AllVolumes, BasePath] = LFFindFilesRecursive(InputPath, FirstVolumeFname);
fprintf('Found :\n');
disp(AllVolumes)
%---Consts---
LFPConsts.LFPHeader = hex2dec({'89', '4C', '46', '50', '0D', '0A', '1A', '0A', '00', '00', '00', '01'}); % 12-byte LFPSections header
LFPConsts.SectHeaderLFM = hex2dec({'89', '4C', '46', '4D', '0D', '0A', '1A', '0A'})'; % header for table of contents
LFPConsts.SectHeaderLFC = hex2dec({'89', '4C', '46', '43', '0D', '0A', '1A', '0A'})'; % header for content section
LFPConsts.SecHeaderPaddingLen = 4;
LFPConsts.Sha1Length = 45;
LFPConsts.ShaPaddingLen = 35; % Sha1 codes are followed by 35 null bytes
LFToolboxInfoFname = 'LFToolbox.json';
%---
for( VolumeIdx = 1:length(AllVolumes) )
CurFile = fullfile(BasePath, AllVolumes{VolumeIdx});
OutPath = fileparts(CurFile);
fprintf('Extracting files in "%s"...\n', OutPath);
CurInfoFname = fullfile( OutPath, LFToolboxInfoFname );
if( exist(CurInfoFname, 'file') )
fprintf('Already done, skipping (delete "%s" to force redo)\n\n', CurInfoFname);
continue;
end
while( 1 )
fprintf(' %s...\n', CurFile);
InFile=fopen(CurFile, 'rb');
%---Check for the magic header---
HeaderBytes = fread( InFile, length(LFPConsts.LFPHeader), 'uchar' );
if( ~all( HeaderBytes == LFPConsts.LFPHeader ) )
fclose(InFile);
fprintf( 'Unrecognized file type' );
return
end
%---Confirm headerlength bytes---
HeaderLength = fread(InFile,1,'uint32','ieee-be');
assert( HeaderLength == 0, 'Unexpected length at top-level header' );
%---Read each section---
% This implementation assumes the TOC appears first in each file
clear TOC
while( ~feof(InFile) )
CurSection = ReadSection( InFile, LFPConsts );
if( all( CurSection.SectHeader == LFPConsts.SectHeaderLFM ) )
TOC = LFReadMetadata( CurSection.Data );
else
assert( exist('TOC','var')==1, 'Expected to find table of contents at top of file' );
MatchingSectIdx = find( strcmp( CurSection.Sha1, {TOC.files.dataRef} ) );
CurFname = TOC.files(MatchingSectIdx).name;
CurFname = strrep( CurFname, 'C:\', '' );
CurFname = strrep( CurFname, '\', '__' );
OutFile = fopen( fullfile(OutPath, CurFname), 'wb' );
fwrite( OutFile, CurSection.Data );
fclose(OutFile);
end
end
fclose( InFile );
if( isfield(TOC, 'nextFile') )
CurFile = fullfile(OutPath, TOC.nextFile);
else
break;
end
end
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
fprintf( 'Marking completion in "%s"\n\n', CurInfoFname );
LFWriteMetadata( CurInfoFname, GeneratedByInfo );
end
fprintf('Done\n');
end
% --------------------------------------------------------------------
function LFPSect = ReadSection( InFile, LFPConsts )
LFPSect.SectHeader = fread(InFile, length(LFPConsts.SectHeaderLFM), 'uchar')';
Padding = fread(InFile, LFPConsts.SecHeaderPaddingLen, 'uint8'); % skip padding
SectLength = fread(InFile, 1, 'uint32', 'ieee-be');
LFPSect.Sha1 = char(fread(InFile, LFPConsts.Sha1Length, 'uchar')');
Padding = fread(InFile, LFPConsts.ShaPaddingLen, 'uint8'); % skip padding
LFPSect.Data = char(fread(InFile, SectLength, 'uchar'))';
while( 1 )
Padding = fread(InFile, 1, 'uchar');
if( feof(InFile) || (Padding ~= 0) )
break;
end
end
if ~feof(InFile)
fseek( InFile, -1, 'cof'); % rewind one byte
end
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFReadMetadata.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFReadMetadata.m
| 14,953 |
utf_8
|
98e987806e2f748e70644b1801d2bf95
|
% LFReadMetadata - reads the metadata files in the JSON file format, from a file or a char buffer
%
% Usage:
%
% Data = LFReadMetadata( JsonFileFname )
%
% This function parses a JSON file and returns the data contained therein. If a char buffer is passed in, it's
% interpreted directly.
%
% Based on code from JSONlab by Qianqian Fang,
% http://www.mathworks.com.au/matlabcentral/fileexchange/33381-jsonlab-a-toolbox-to-encodedecode-json-files-in-matlaboctave
%
% Minor modifications by Donald G. Dansereau, 2013, to simplify the interface as appropriate for use
% in the Light Field Toolbox, and to tolerate the sha keys appearing at the end of some Lytro JSON
% files
%
% See also: LFWriteMetadata
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function data = LFReadMetadata( JsonFileFname )
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(JsonFileFname,'[\{\}\]\[]','once'))
string=JsonFileFname;
elseif(exist(JsonFileFname,'file'))
fid = fopen(JsonFileFname,'rt');
string = fscanf(fid,'%c');
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt = []; % opt=varargin2struct(varargin{:});
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
pos = len+1;
continue;
% error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
else
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
if next_char ~= ']'
[endpos e1l e1r maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(find(arraystr==sprintf('\n')))=[];
arraystr(find(arraystr==sprintf('\r')))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(find(astr==sprintf('\n')))=[];
astr(find(astr==sprintf('\r')))=[];
astr(find(astr==' '))='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(find(astr==' '))='';
[obj count errmsg nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(find(astr=='['))='';
astr(find(astr==']'))='';
astr(find(astr==' '))='';
[obj count errmsg nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
try
object=cell2mat(object')';
if(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
parse_char(']');
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFUtilDecodeLytroFolder.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFUtilDecodeLytroFolder.m
| 16,946 |
utf_8
|
6867204a9b31f8807a667ab1fe4fa420
|
% LFUtilDecodeLytroFolder - decode and optionally colour correct and rectify Lytro light fields
%
% Usage:
%
% LFUtilDecodeLytroFolder
% LFUtilDecodeLytroFolder( InputPath )
% LFUtilDecodeLytroFolder( InputPath, FileOptions, DecodeOptions, RectOptions )
% LFUtilDecodeLytroFolder( InputPath, [], [], RectOptions )
%
% All parameters are optional and take on default values as set in the "Defaults" section at the top
% of the implementation. As such, this can be called as a function or run directly by editing the
% code. When calling as a function, pass an empty array "[]" to omit a parameter.
%
% As released, the default values are set up to match the naming conventions of LFP Reader v2.0.0.
%
% This function demonstrates decoding and optionally colour-correction and rectification of 2D
% lenslet images into 4D light fields. It recursively crawls through a prescribed folder and its
% subfolders, operating on each light field. It can be used incrementally: previously-decoded light
% fields can be subsequently colour-corected, rectified, or both. Previously-completed tasks will
% not be re-applied. A filename pattern can be provided to work on individual files. All paths and
% naming are configurable.
%
% Decoding and rectification follow the process described in:
%
% [1] D. G. Dansereau, O. Pizarro, and S. B. Williams, "Decoding, calibration and rectification for
% lenslet-based plenoptic cameras," in Computer Vision and Pattern Recognition (CVPR), IEEE
% Conference on. IEEE, Jun 2013.
%
% Decoding requires that an appropriate database of white images be created using
% LFUtilProcessWhiteImages. Rectification similarly requires a calibration database be created using
% LFUtilProcessCalibrations.
%
% To decode a single light field, it is simplest to include a file specification in InputPath (see
% below). It is also possible to call LFLytroDecodeImage directly.
%
% Colour correction employs the metadata associated with each Lytro picture. It also applies
% histogram-based contrast adjustment. It calls the functions LFColourCorrect and LFHistEqualize.
%
% Rectification employs a calibration info file to rectify the light field, correcting for lens
% distortion, making pixels square, and yielding an intrinsics matrix which allows easy conversion
% from a pixel index [i,j,k,l] to a ray [s,t,u,v]. A calibration info file is generated by
% processing a series of checkeboard images, following the calibration procedure described in
% LFToolbox.pdf. A calibration only applies to one specific camera at one specific zoom and focus
% setting, and decoded using one specific lenslet grid model. The tool LFUtilProcessCalibrations is
% used to build a database of rectifications, and LFSelectFromDatabase isused to select a
% calibration appropriate to a given light field.
%
% This function was written to deal with Lytro imagery, but adapting it to operate with other
% lenslet-based cameras should be straightforward. For more information on the decoding process,
% refer to LFDecodeLensletImageSimple, [1], and LFToolbox.pdf.
%
% Some optional parameters are not used or documented at this level -- see each of LFCalRectifyLF,
% LFLytroDecodeImage, LFDecodeLensletImageSimple, and LFColourCorrect for further information.
%
%
% Inputs -- all are optional, see code below for default values :
%
% InputPath : Path to folder containing light fields, or to a specific light field, optionally including one or
% more wildcard filename specifications. In case wildcards are used, this searches sub-folders recursively. See
% LFFindFilesRecursive.m for more information and examples of how InputPath is interpreted.
%
% FileOptions : struct controlling file naming and saving
% .SaveResult : Set to false to perform a "dry run"
% .ForceRedo : If true previous results are ignored and decoding starts from scratch
% .SaveFnamePattern : String defining the pattern used in generating the output filename;
% sprintf is used to complete this pattern, such that %s gets replaced
% with the base name of the input light field
% .ThumbFnamePattern : As with SaveFnamePattern, defines the name of the output thumbnail
% image
%
% DecodeOptions : struct controlling the decoding process, see LFDecodeLensletImageSimple for more info
% .OptionalTasks : Cell array containing any combination of 'ColourCorrect' and
% 'Rectify'; an empty array "{}" means no additional tasks are
% requested; case sensitive
% .LensletImageFnamePattern : Pattern used to locate input files -- the pattern %s stands in
% for the base filename
% .ColourHistThresh : Threshold used by LFHistEqualize in optional colour correction
% .WhiteImageDatabasePath : Full path to the white images database, as created by
% LFUtilProcessWhiteImages
% .DoDehex : Controls whether hexagonal sampling is converted to rectangular, default true
% .DoSquareST : Controls whether s,t dimensions are resampled to square pixels, default true
% .ResampMethod : 'fast'(default) or 'triangulation'
% .LevelLimits : a two-element vector defining the black and white levels
% .Precision : 'single'(default) or 'double'
%
% RectOptions : struct controlling the optional rectification process
% .CalibrationDatabaseFname : Full path to the calibration file database, as created by
% LFUtilProcessCalibrations;
%
% Example:
%
% LFUtilDecodeLytroFolder
%
% Run from the top level of the 'Samples' folder will decode all the light fields in all the
% sub-folders, with default settings as set up in the opening section of the code. The
% calibration database created by LFUtilProcessWhiteImages is expected to be in
% 'Cameras/CaliCalibrationDatabase.mat' by default.
%
% LFUtilDecodeLytroFolder('Images', [], struct('OptionalTasks', 'ColourCorrect'))
%
% Run from the top level of the 'Samples' folder will decode and colour correct all light fields in the Images
% folder and its sub-folders.
%
% DecodeOptions.OptionalTasks = {'ColourCorrect', 'Rectify'};
% LFUtilDecodeLytroFolder([], [], DecodeOptions)
%
% Will perform both colour correction and rectification in the Images folder.
%
% LFUtilDecodeLytroFolder('Images/Illum/Lorikeet.lfp')
% LFUtilDecodeLytroFolder('Lorikeet.lfp')
% LFUtilDecodeLytroFolder({'Images', '*Hiding*', 'Jacaranda*'})
% LFUtilDecodeLytroFolder('*.raw')
% LFUtilDecodeLytroFolder({'*0002*', '*0003*'})
%
% Any of these, run from the top level of the 'Samples' folder, will decode the matching files. See
% LFFindFilesRecursive.
%
% See also: LFUtilExtractLFPThumbs, LFUtilProcessWhiteImages, LFUtilProcessCalibrations, LFUtilCalLensletCam,
% LFColourCorrect, LFHistEqualize, LFFindFilesRecursive, LFLytroDecodeImage, LFDecodeLensletImageSimple,
% LFSelectFromDatabase
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LFUtilDecodeLytroFolder( InputPath, FileOptions, DecodeOptions, RectOptions )
%---Defaults---
InputPath = LFDefaultVal( 'InputPath', 'Images' );
FileOptions = LFDefaultField('FileOptions', 'SaveResult', true);
FileOptions = LFDefaultField('FileOptions', 'ForceRedo', false);
FileOptions = LFDefaultField('FileOptions', 'SaveFnamePattern', '%s__Decoded.mat');
FileOptions = LFDefaultField('FileOptions', 'ThumbFnamePattern', '%s__Decoded_Thumb.png');
DecodeOptions = LFDefaultField('DecodeOptions', 'OptionalTasks', {}); % 'ColourCorrect', 'Rectify'
DecodeOptions = LFDefaultField('DecodeOptions', 'ColourHistThresh', 0.01);
DecodeOptions = LFDefaultField(...
'DecodeOptions', 'WhiteImageDatabasePath', fullfile('Cameras','WhiteImageDatabase.mat'));
RectOptions = LFDefaultField(...
'RectOptions', 'CalibrationDatabaseFname', fullfile('Cameras','CalibrationDatabase.mat'));
% Used to decide if two lenslet grid models are "close enough"... if they're not a warning is raised
RectOptions = LFDefaultField( 'RectOptions', 'MaxGridModelDiff', 1e-5 );
% Massage a single-element OptionalTasks list to behave as a cell array
while( ~iscell(DecodeOptions.OptionalTasks) )
DecodeOptions.OptionalTasks = {DecodeOptions.OptionalTasks};
end
%---Crawl folder structure locating raw lenslet images---
DefaultFileSpec = {'*.lfr', '*.lfp', '*.LFR', '*.raw'}; % gets overriden below, if a file spec is provided
DefaultPath = 'Images';
[FileList, BasePath] = LFFindFilesRecursive( InputPath, DefaultFileSpec, DefaultPath );
fprintf('Found :\n');
disp(FileList)
%---Process each raw lenslet file---
% Store options so we can reset them for each file
OrigDecodeOptions = DecodeOptions;
OrigRectOptions = RectOptions;
for( iFile = 1:length(FileList) )
SaveRequired = false;
%---Start from orig options, avoids values bleeding between iterations---
DecodeOptions = OrigDecodeOptions;
RectOptions = OrigRectOptions;
%---Find current / base filename---
CurFname = FileList{iFile};
CurFname = fullfile(BasePath, CurFname);
% Build filename base without extension, auto-remove '__frame' for legacy .raw format
LFFnameBase = CurFname;
[~,~,Extension] = fileparts(LFFnameBase);
LFFnameBase = LFFnameBase(1:end-length(Extension));
CullIdx = strfind(LFFnameBase, '__frame');
if( ~isempty(CullIdx) )
LFFnameBase = LFFnameBase(1:CullIdx-1);
end
fprintf('\n---%s [%d / %d]...\n', CurFname, iFile, length(FileList));
%---Decode---
fprintf('Decoding...\n');
% First check if a decoded file already exists
[SDecoded, FileExists, CompletedTasks, TasksRemaining, SaveFname] = CheckIfExists( ...
LFFnameBase, DecodeOptions, FileOptions.SaveFnamePattern, FileOptions.ForceRedo );
if( ~FileExists )
% No previous result, decode
[LF, LFMetadata, WhiteImageMetadata, LensletGridModel, DecodeOptions] = ...
LFLytroDecodeImage( CurFname, DecodeOptions );
if( isempty(LF) )
continue;
end
fprintf('Decode complete\n');
SaveRequired = true;
elseif( isempty(TasksRemaining) )
% File exists, and nothing more to do
continue;
else
% File exists and tasks remain: unpack previous decoding results
[LF, LFMetadata, WhiteImageMetadata, LensletGridModel, DecodeOptions] = LFStruct2Var( ...
SDecoded, 'LF', 'LFMetadata', 'WhiteImageMetadata', 'LensletGridModel', 'DecodeOptions' );
clear SDecoded
end
%---Display thumbnail---
Thumb = DispThumb(LF, CurFname, CompletedTasks);
%---Optionally colour correct---
if( ismember( 'ColourCorrect', TasksRemaining ) )
LF = ColourCorrect( LF, LFMetadata, DecodeOptions );
CompletedTasks = [CompletedTasks, 'ColourCorrect'];
SaveRequired = true;
fprintf('Done\n');
%---Display thumbnail---
Thumb = DispThumb(LF, CurFname, CompletedTasks);
end
%---Optionally rectify---
if( ismember( 'Rectify', TasksRemaining ) )
[LF, RectOptions, Success] = Rectify( LF, LFMetadata, DecodeOptions, RectOptions, LensletGridModel );
if( Success )
CompletedTasks = [CompletedTasks, 'Rectify'];
SaveRequired = true;
end
%---Display thumbnail---
Thumb = DispThumb(LF, CurFname, CompletedTasks);
end
%---Check that all tasks are completed---
UncompletedTaskIdx = find(~ismember(TasksRemaining, CompletedTasks));
if( ~isempty(UncompletedTaskIdx) )
UncompletedTasks = [];
for( i=UncompletedTaskIdx )
UncompletedTasks = [UncompletedTasks, ' ', TasksRemaining{UncompletedTaskIdx}];
end
warning(['Could not complete all tasks requested in DecodeOptions.OptionalTasks: ', UncompletedTasks]);
end
DecodeOptions.OptionalTasks = CompletedTasks;
%---Optionally save---
if( SaveRequired && FileOptions.SaveResult )
if( isfloat(LF) )
LF = uint16( LF .* double(intmax('uint16')) );
end
ThumbFname = sprintf(FileOptions.ThumbFnamePattern, LFFnameBase);
fprintf('Saving to:\n\t%s,\n\t%s...\n', SaveFname, ThumbFname);
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
save('-v7.3', SaveFname, 'GeneratedByInfo', 'LF', 'LFMetadata', 'WhiteImageMetadata', 'LensletGridModel', 'DecodeOptions', 'RectOptions');
imwrite(Thumb, ThumbFname);
end
end
end
%---------------------------------------------------------------------------------------------------
function [SDecoded, FileExists, CompletedTasks, TasksRemaining, SaveFname] = ...
CheckIfExists( LFFnameBase, DecodeOptions, SaveFnamePattern, ForceRedo )
SDecoded = [];
FileExists = false;
SaveFname = sprintf(SaveFnamePattern, LFFnameBase);
if( ~ForceRedo && exist(SaveFname, 'file') )
%---Task previously completed, check if there's more to do---
FileExists = true;
fprintf( ' %s already exists\n', SaveFname );
PrevDecodeOptions = load( SaveFname, 'DecodeOptions' );
PrevOptionalTasks = PrevDecodeOptions.DecodeOptions.OptionalTasks;
CompletedTasks = PrevOptionalTasks;
TasksRemaining = find(~ismember(DecodeOptions.OptionalTasks, PrevOptionalTasks));
if( ~isempty(TasksRemaining) )
%---Additional tasks remain---
TasksRemaining = {DecodeOptions.OptionalTasks{TasksRemaining}}; % by name
fprintf(' Additional tasks remain, loading existing file...\n');
SDecoded = load( SaveFname );
AllTasks = [SDecoded.DecodeOptions.OptionalTasks, TasksRemaining];
SDecoded.DecodeOptions.OptionalTasks = AllTasks;
%---Convert to float as this is what subsequent operations require---
OrigClass = class(SDecoded.LF);
SDecoded.LF = cast( SDecoded.LF, SDecoded.DecodeOptions.Precision ) ./ ...
cast( intmax(OrigClass), SDecoded.DecodeOptions.Precision );
fprintf('Done\n');
else
%---No further tasks... move on---
fprintf( ' No further tasks requested\n');
TasksRemaining = {};
end
else
%---File doesn't exist, all tasks remain---
TasksRemaining = DecodeOptions.OptionalTasks;
CompletedTasks = {};
end
end
%---------------------------------------------------------------------------------------------------
function Thumb = DispThumb( LF, CurFname, CompletedTasks)
Thumb = squeeze(LF(floor(end/2),floor(end/2),:,:,:)); % including weight channel for hist equalize
Thumb = uint8(LFHistEqualize(Thumb).*double(intmax('uint8')));
Thumb = Thumb(:,:,1:3); % strip off weight channel
LFDispSetup(Thumb);
Title = CurFname;
for( i=1:length(CompletedTasks) )
Title = [Title, ', ', CompletedTasks{i}];
end
title(Title, 'Interpreter', 'none');
drawnow
end
%---------------------------------------------------------------------------------------------------
function LF = ColourCorrect( LF, LFMetadata, DecodeOptions )
fprintf('Applying colour correction... ');
%---Weight channel is not used by colour correction, so strip it out---
LFWeight = LF(:,:,:,:,4);
LF = LF(:,:,:,:,1:3);
%---Apply the color conversion and saturate---
LF = LFColourCorrect( LF, DecodeOptions.ColourMatrix, DecodeOptions.ColourBalance, DecodeOptions.Gamma );
%---Put the weight channel back---
LF(:,:,:,:,4) = LFWeight;
end
%---------------------------------------------------------------------------------------------------
function [LF, RectOptions, Success] = Rectify( LF, LFMetadata, DecodeOptions, RectOptions, LensletGridModel )
Success = false;
fprintf('Applying rectification... ');
%---Load cal info---
fprintf('Selecting calibration...\n');
[CalInfo, RectOptions] = LFFindCalInfo( LFMetadata, RectOptions );
if( isempty( CalInfo ) )
warning('No suitable calibration found, skipping');
return;
end
%---Compare structs
a = CalInfo.LensletGridModel;
b = LensletGridModel;
a.Orientation = strcmp(a.Orientation, 'horz');
b.Orientation = strcmp(b.Orientation, 'horz');
FractionalDiff = abs( (struct2array(a) - struct2array(b)) ./ struct2array(a) );
if( ~all( FractionalDiff < RectOptions.MaxGridModelDiff ) )
warning(['Lenslet grid models differ -- ideally the same grid model and white image are ' ...
' used to decode during calibration and rectification']);
end
%---Perform rectification---
[LF, RectOptions] = LFCalRectifyLF( LF, CalInfo, RectOptions );
Success = true;
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFFilt4DFFT.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFFilt4DFFT.m
| 3,622 |
utf_8
|
bb1d9662c072ab5fb38568d45f44bd28
|
% LFFilt4DFFT -Applies a 4D frequency-domain filter using the FFT
%
% Usage:
%
% [LF, FiltOptions] = LFFilt4DFFT( LF, H, FiltOptions )
% LF = LFFilt4DFFT( LF, H )
%
%
% This filter works by taking the FFT of the input light field, multiplying by the provided magnitude response H, then
% calling the inverse FFT. The frequency-domain filter H should match or exceed the size of the light field LF. If H is
% larger than the input light field, LF is zero-padded to match the filter's size. If a weight channel is present in
% the light field it gets used during normalization.
%
% See LFDemoBasicFiltLytro for example usage.
%
%
% Inputs
%
% LF : The light field to be filtered
%
% H : The frequency-domain filter to apply, as constructed by one of the LFBuild4DFreq* functions
%
% [optional] FiltOptions : struct controlling filter operation
% Precision : 'single' or 'double', default 'single'
% Normalize : default true; when enabled the output is normalized so that darkening near image edges is
% removed
% MinWeight : during normalization, pixels for which the output value is not well defined (i.e. for
% which the filtered weight is very low) get set to 0. MinWeight sets the threshold at which
% this occurs, default is 10 * the numerical precision of the output, as returned by eps
%
% Outputs:
%
% LF : The filtered 4D light field
% FiltOptions : The filter options including defaults, with an added FilterInfo field detailing the function and
% time of filtering.
%
% See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, LFBuild2DFreqFan, LFBuild2DFreqLine,
% LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT,
% LFFiltShiftSum
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [LF, FiltOptions] = LFFilt4DFFT( LF, H, FiltOptions )
FiltOptions = LFDefaultField('FiltOptions', 'Precision', 'single');
FiltOptions = LFDefaultField('FiltOptions', 'Normalize', true);
FiltOptions = LFDefaultField('FiltOptions', 'MinWeight', 10*eps(FiltOptions.Precision));
%---
NColChans = size(LF,5);
HasWeight = ( NColChans == 4 || NColChans == 2 );
HasColour = ( NColChans == 4 || NColChans == 3 );
if( HasWeight )
NColChans = NColChans-1;
end
%---
LFSize = size(LF);
LFPaddedSize = size(H);
LF = LFConvertToFloat(LF, FiltOptions.Precision);
if( FiltOptions.Normalize )
if( HasWeight )
for( iColChan = 1:NColChans )
LF(:,:,:,:,iColChan) = LF(:,:,:,:,iColChan) .* LF(:,:,:,:,end);
end
else % add a weight channel
LF(:,:,:,:,end+1) = ones(size(LF(:,:,:,:,1)), FiltOptions.Precision);
end
end
SliceSize = size(LF);
for( iColChan = 1:SliceSize(end) )
fprintf('.');
X = fftn(LF(:,:,:,:,iColChan), LFPaddedSize);
X = X .* H;
x = ifftn(X,'symmetric');
x = x(1:LFSize(1), 1:LFSize(2), 1:LFSize(3), 1:LFSize(4));
LF(:,:,:,:,iColChan) = x;
end
if( FiltOptions.Normalize )
WeightChan = LF(:,:,:,:,end);
InvalidIdx = find(WeightChan <= FiltOptions.MinWeight);
ChanSize = numel(LF(:,:,:,:,1));
for( iColChan = 1:NColChans )
LF(:,:,:,:,iColChan) = LF(:,:,:,:,iColChan) ./ WeightChan;
LF( InvalidIdx + ChanSize.*(iColChan-1) ) = 0;
end
end
LF = max(0,LF);
LF = min(1,LF);
%---
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
FiltOptions.FilterInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
fprintf(' Done\n');
|
github
|
Vincentqyw/light-field-TB-master
|
LFUtilCalLensletCam.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFUtilCalLensletCam.m
| 8,438 |
utf_8
|
56382b29c1b601dbae1ec2d6763a51b0
|
% LFUtilCalLensletCam - calibrate a lenslet-based light field camera
%
% Usage:
%
% LFUtilCalLensletCam
% LFUtilCalLensletCam( Inputpath )
% LFUtilCalLensletCam( InputPath, CalOptions )
% LFUtilProcessCalibrations( [], CalOptions )
%
% All parameters are optional and take on default values as set in the "Defaults" section at the top
% of the implementation. As such, this can be called as a function or run directly by editing the
% code. When calling as a function, pass an empty array "[]" to omit a parameter.
%
% This function recursively crawls through a folder identifying decoded light field images and
% performing a calibration based on those images. It follows the calibration procedure described in:
%
% D. G. Dansereau, O. Pizarro, and S. B. Williams, "Decoding, calibration and rectification for
% lenslet-based plenoptic cameras," in Computer Vision and Pattern Recognition (CVPR), IEEE
% Conference on. IEEE, Jun 2013.
%
% Minor differences from the paper: camera parameters are automatically initialized, so no prior
% knowledge of the camera's parameters is required; the free intrinsic parameters have been reduced
% by two: H(3:4,5) were previously redundant with the camera's extrinsics, and are now automatically
% centered; and the light field indices [i,j,k,l] are 1-based in this implementation, and not
% 0-based as described in the paper.
%
% The calibration produced by this process is saved in a JSON file, by default named 'CalInfo.json',
% in the top-level folder of the calibration images. The calibration includes a 5x5 homogeneous
% intrinsic matrix EstCamIntrinsicsH, a 5-element vector EstCamDistortionV describing its distortion
% parameters, and the lenslet grid model formed from the white image used to decode the
% checkerboard images. Taken together, these relate light field indices [i,j,k,l] to spatial rays
% [s,t,u,v], and can be utilized to rectify light fields, as demonstrated in LFUtilDecodeLytroFolder
% / LFCalRectifyLF.
%
% The input light fields are ideally of a small checkerboard (order mm per square), taken at close
% range, and over a diverse set of poses to maximize the quality of the calibration. The
% checkerboard light field images should be decoded without rectification, and colour correction is
% not required.
%
% Calibration is described in more detail in LFToolbox.pdf, including links to example datasets and
% a walkthrough of a calibration process.
%
% Inputs -- all are optional, see code below for default values :
%
% InputPath : Path to folder containing decoded checkerboard images -- note the function
% operates recursively, i.e. it will search sub-folders.
%
% CalOptions : struct controlling calibration parameters
% .ExpectedCheckerSize : Number of checkerboard corners, as recognized by the automatic
% corner detector; edge corners are not recognized, so a standard
% 8x8-square chess board yields 7x7 corners
% .ExpectedCheckerSpacing_m : Physical extents of the checkerboard, in meters
% .LensletBorderSize : Number of pixels to skip around the edges of lenslets; a low
% value of 1 or 0 is generally appropriate, as invalid pixels are
% automatically skipped
% .SaveResult : Set to false to perform a "dry run"
% .ShowDisplay : Enables various displays throughout the calibration process
% .ForceRedoCornerFinding : Forces the corner finding procedure to run, overwriting existing
% results
% .ForceRedoInit : Forces the parameter initialization step to run, overwriting
% existing results
% .OptTolX : Determines when the optimization process terminates. When the
% estimted parameter values change by less than this amount, the
% optimization terminates. See the Matlab documentation on lsqnonlin,
% option `TolX' for more information. The default value of 5e-5 is set
% within the LFCalRefine function; a value of 0 means the optimization
% never terminates based on this criterion.
% .OptTolFun : Similar to OptTolX, except this tolerance deals with the error value.
% This corresponds to Matlab's lsqnonlin option `TolFun'. The default
% value of 0 is set within the LFCalRefine function, and means the
% optimization never terminates based on this criterion.
%
% Output takes the form of saved checkerboard info and calibration files.
%
% Example :
%
% LFUtilCalLensletCam('.', ...
% struct('ExpectedCheckerSize', [8,6], 'ExpectedCheckerSpacing_m', 1e-3*[35.1, 35.0]))
%
% Run from within the top-level path of a set of decoded calibration images of an 8x6 checkerboard
% of dimensions 35.1x35.0 mm, will carry out all the stages of a calibration. See the toolbox
% documentation for a more complete example.
%
% See also: LFCalFindCheckerCorners, LFCalInit, LFCalRefine, LFUtilDecodeLytroFolder, LFSelectFromDatabase
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LFUtilCalLensletCam( InputPath, CalOptions )
%---Tweakables---
InputPath = LFDefaultVal('InputPath', '.');
CalOptions = LFDefaultField( 'CalOptions', 'ExpectedCheckerSize', [19, 19] );
CalOptions = LFDefaultField( 'CalOptions', 'ExpectedCheckerSpacing_m', [3.61, 3.61] * 1e-3 );
CalOptions = LFDefaultField( 'CalOptions', 'LensletBorderSize', 1 );
CalOptions = LFDefaultField( 'CalOptions', 'SaveResult', true );
CalOptions = LFDefaultField( 'CalOptions', 'ForceRedoCornerFinding', false );
CalOptions = LFDefaultField( 'CalOptions', 'ForceRedoInit', false );
CalOptions = LFDefaultField( 'CalOptions', 'ShowDisplay', true );
CalOptions = LFDefaultField( 'CalOptions', 'CalInfoFname', 'CalInfo.json' );
%---Check for previously started calibration---
CalInfoFname = fullfile(InputPath, CalOptions.CalInfoFname);
if( ~CalOptions.ForceRedoInit && exist(CalInfoFname, 'file') )
fprintf('---File %s already exists\n Loading calibration state and options\n', CalInfoFname);
CalOptions = LFStruct2Var( LFReadMetadata(CalInfoFname), 'CalOptions' );
else
CalOptions.Phase = 'Start';
end
RefineComplete = false; % always at least refine once
%---Step through the calibration phases---
while( ~strcmp(CalOptions.Phase, 'Refine') || ~RefineComplete )
switch( CalOptions.Phase )
case 'Start'
%---Find checkerboard corners---
CalOptions.Phase = 'Corners';
CalOptions = LFCalFindCheckerCorners( InputPath, CalOptions );
case 'Corners'
%---Initialize calibration process---
CalOptions.Phase = 'Init';
CalOptions = LFCalInit( InputPath, CalOptions );
if( CalOptions.ShowDisplay )
LFFigure(2);
clf
LFCalDispEstPoses( InputPath, CalOptions, [], [0.7,0.7,0.7] );
end
case 'Init'
%---First step of optimization process will exclude distortion---
CalOptions.Phase = 'NoDistort';
CalOptions = LFCalRefine( InputPath, CalOptions );
if( CalOptions.ShowDisplay )
LFFigure(2);
LFCalDispEstPoses( InputPath, CalOptions, [], [0,0.7,0] );
end
case 'NoDistort'
%---Next step of optimization process adds distortion---
CalOptions.Phase = 'WithDistort';
CalOptions = LFCalRefine( InputPath, CalOptions );
if( CalOptions.ShowDisplay )
LFFigure(2);
LFCalDispEstPoses( InputPath, CalOptions, [], [0,0,1] );
end
otherwise
%---Subsequent calls refine the estimate---
CalOptions.Phase = 'Refine';
CalOptions = LFCalRefine( InputPath, CalOptions );
RefineComplete = true;
if( CalOptions.ShowDisplay )
LFFigure(2);
LFCalDispEstPoses( InputPath, CalOptions, [], [1,0,0] );
end
end
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFHistEqualize.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFHistEqualize.m
| 6,002 |
utf_8
|
aaaa0313c7b80ba9ccf5524a24026bdb
|
% LFHistEqualize - histogram-based contrast adjustment
%
% Usage:
%
% LF = LFHistEqualize( LF )
% [LF, LowerBound, UpperBound] = LFHistEqualize( LF, Cutoff_percent )
% LF = LFHistEqualize( LF, [], LowerBound, UpperBound )
% LF = LFHistEqualize(LF, Cutoff_percent, [], [], Precision)
%
% This function performs contrast adjustment on images based on a histogram of intensity. Colour
% images are handled by building a histogram of the `value' channel in the HSV colour space.
% Saturation points are computed based on a desired percentage of saturated white / black pixels.
%
% All parameters except LF are optional. Pass an empty array "[]" to omit a parameter.
%
% Inputs:
%
% LF : a light field or image to adjust. Integer formats are automatically converted to floating
% point. The default precision is 'single', though this is controllable via the optional
% Precision parameter. The function can handle most input dimensionalities as well as
% colour and monochrome inputs. For example, a colour 2D image of size [Nl,Nk,3], a mono 2D
% image of size [Nl,Nk], a colour 4D image of size [Nj,Ni,Nl,Nk,3], and a mono 4D image of
% size [Nj,Ni,Nl,Nk] are all valid.
%
% Including a weight channel will result in zero-weight pixels being ignored. Weight should
% be included as a fourth colour channel -- e.g. an image of size [Nl,Nk,4].
%
% Optional inputs:
%
% Cutoff_percent : controls how much of the histogram gets saturated on both the high
% and lower ends. Higher values result in more saturated black and
% white pixels. The default value is 0.1%.
%
% LowerBound, UpperBound : bypass the histogram computation and instead directly saturate the
% input image at the prescribed limits. If no bounds are provided, they
% are computed from the histogram.
%
% Precision : 'single' or 'double'
%
%
% Outputs:
%
% LF : the contrast-adjusted image, in floating point values scaled between
% 0 and 1.
%
% LowerBound, UpperBound : the saturation points used, on the intensity scale of the input after
% converting to the requested floating point precision. These are
% useful in applying the same contrast adjustment to a number of light
% fields, by saving and passing these bounds on subsequent function
% calls.
%
% Example:
%
% load('Images/F01/IMG_0002__Decoded.mat', 'LF');
% LF = LFHistEqualize(LF);
% LFDispMousePan(LF, 2);
%
% Run from the top level of the light field samples will load the decoded sample, apply histogram
% equalization, then display the result in a shifting-perspective display with x2 magnification.
% LFUtilProcessWhiteImages and LFUtilDecodeLytroFolder must be run to decode the light field.
%
% See also: LFUtilDecodeLytroFolder, LFUtilProcessWhiteImages, LFColourCorrect
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [LF, LowerBound, UpperBound] = ...
LFHistEqualize(LF, Cutoff_percent, LowerBound, UpperBound, Precision)
%---Defaults---
Cutoff_percent = LFDefaultVal( 'Cutoff_percent', 0.1 );
Precision = LFDefaultVal( 'Precision', 'single' );
MaxBlkSize = LFDefaultVal( 'MaxBlkSize', 10e6 ); % slice up to limit memory utilization
%---Make sure LF is floating point, as required by hist function---
if( ~strcmp(class(LF), Precision) )
LF = cast(LF, Precision);
end
%---Flatten to a single list of N x NChans entries---
LFSize = size(LF);
NDims = numel(LFSize);
NChans = LFSize(end);
LF = reshape(LF, [prod(LFSize(1:NDims-1)), NChans]);
%---Strip out and use the weight channel if it's present---
if( NChans == 4 )
% Weight channel found, strip it out and use it
LFW = LF(:,4);
LF = LF(:,1:3);
ValidIdx = find(LFW > 0);
else
LFW = [];
ValidIdx = ':';
end
%---Convert colour images to HSV, and operate on value only---
if( size(LF,2) == 3 )
LF = LF - min(LF(ValidIdx));
LF = LF ./ max(LF(ValidIdx));
LF = max(0,min(1,LF));
fprintf('Converting to HSV...');
for( UStart = 1:MaxBlkSize:size(LF,1) )
UStop = UStart + MaxBlkSize - 1;
UStop = min(UStop, size(LF,1));
% matlab 2014b's rgb2hsv requires doubles
LF(UStart:UStop,:) = cast(rgb2hsv( double(LF(UStart:UStop,:)) ), Precision);
fprintf('.')
end
LF_hsv = LF(:,1:2);
LF = LF(:,3); % operate on value channel only
else
LF_hsv = [];
end
fprintf(' Equalizing...');
%---Compute bounds from histogram---
if( ~exist('LowerBound','var') || ~exist('UpperBound','var') || ...
isempty(LowerBound) || isempty(UpperBound))
[ha,xa] = hist(LF(ValidIdx), 2^16);
ha = cumsum(ha);
ha = ha ./ max(ha(:));
Cutoff = Cutoff_percent / 100;
LowerBound = xa(find(ha >= Cutoff, 1, 'first'));
UpperBound = xa(find(ha <= 1-Cutoff, 1, 'last'));
end
if( isempty(UpperBound) )
UpperBound = max(LF(ValidIdx));
end
if( isempty(LowerBound) )
LowerBound = min(LF(ValidIdx));
end
clear ValidIdx
%---Apply bounds and rescale to 0-1 range---
LF = max(LowerBound, min(UpperBound, LF));
LF = (LF - LowerBound) ./ (UpperBound - LowerBound);
%---Rebuild hsv, then rgb colour light field---
if( ~isempty(LF_hsv) )
LF = cat(2,LF_hsv,LF);
clear LF_hsv
fprintf(' Converting to RGB...');
for( UStart = 1:MaxBlkSize:size(LF,1) )
UStop = UStart + MaxBlkSize - 1;
UStop = min(UStop, size(LF,1));
LF(UStart:UStop,:) = hsv2rgb(LF(UStart:UStop,:));
fprintf('.');
end
end
%---Return the weight channel---
if( ~isempty(LFW) )
LF(:,4) = LFW;
end
%---Unflatten---
LF = reshape(LF, [LFSize(1:NDims-1),NChans]);
fprintf(' Done.\n');
|
github
|
Vincentqyw/light-field-TB-master
|
LFReadRaw.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFReadRaw.m
| 2,387 |
utf_8
|
f61af2a213353cf523d8d47f5fd665aa
|
% LFReadRaw - Reads 8, 10, 12 and 16-bit raw image files
%
% Usage:
%
% Img = LFReadRaw( Fname )
% Img = LFReadRaw( Fname, BitPacking, ImgSize )
% Img = LFReadRaw( Fname, [], ImgSize )
%
% There is no universal `RAW' file format. This function reads a few variants, including the 12-bit and 10-bit files
% commonly employed in Lytro cameras, and the 16-bit files produced by some third-party LFP extraction tools. The output
% is always an array of type uint16, except for 8-bit files which produce an 8-bit output.
%
% Raw images may be converted to more portable formats, including .png, using an external tool such as the
% cross-platform ImageMagick tool.
%
% Inputs :
%
% Fname : path to raw file to read
%
% [optional] BitPacking : one of '12bit', '10bit' or '16bit'; default is '12bit'
%
% [optional] ImgSize : a 2D vector defining the size of the image, in pixels. The default value varies according to
% the value of 'BitPacking', to correspond to commonly-found Lytro file formats: 12 bit images are employed by the
% Lytro F01, producing images of size 3280x3280, while 10-bit images are produced by the Illum at a resolutio of
% 7728x5368; 16-bit images default to 3280x3280.
%
% Outputs:
%
% Img : an array of uint16 gray levels. No demosaicing (decoding Bayer pattern) is performed.
%
% See also: LFReadLFP, LFDecodeLensletImageSimple, demosaic
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function Img = LFReadRaw( Fname, BitPacking, ImgSize )
%---Defaults---
BitPacking = LFDefaultVal( 'BitPacking', '12bit' );
switch( BitPacking )
case '8bit'
ImgSize = LFDefaultVal( 'ImgSize', [3280,3280] );
BuffSize = prod(ImgSize);
case '12bit'
ImgSize = LFDefaultVal( 'ImgSize', [3280,3280] );
BuffSize = prod(ImgSize) * 12/8;
case '10bit'
ImgSize = LFDefaultVal( 'ImgSize', [7728, 5368] );
BuffSize = prod(ImgSize) * 10/8;
case '16bit'
ImgSize = LFDefaultVal( 'ImgSize', [3280,3280] );
BuffSize = prod(ImgSize) * 16/8;
otherwise
error('Unrecognized bit packing format');
end
%---Read and unpack---
f = fopen( Fname );
Img = fread( f, BuffSize, 'uchar' );
Img = LFUnpackRawBuffer( Img, BitPacking, ImgSize )'; % note the ' is necessary to get the rotation right
fclose( f );
|
github
|
Vincentqyw/light-field-TB-master
|
LFDispVidCirc.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFDispVidCirc.m
| 3,251 |
utf_8
|
7f29b601b697f1bf5daf1621b54fe7b0
|
% LFDispVidCirc - visualize a 4D light field animating a circular path through two dimensions
%
% Usage:
%
% FigureHandle = LFDispVidCirc( LF )
% FigureHandle = LFDispVidCirc( LF, PathRadius_percent, FrameDelay )
% FigureHandle = LFDispVidCirc( LF, PathRadius_percent, FrameDelay, ScaleFactor )
% FigureHandle = LFDispVidCirc( LF, [], [], ScaleFactor )
%
%
% A figure is set up for high-performance display, with the tag 'LFDisplay'. Subsequent calls to
% this function and LFDispVidCirc will reuse the same figure, rather than creating a new window on
% each call. All parameters except LF are optional -- pass an empty array "[]" to omit an optional
% parameter.
%
%
% Inputs:
%
% LF : a colour or single-channel light field, and can a floating point or integer format. For
% display, it is converted to 8 bits per channel. If LF contains more than three colour
% channels, as is the case when a weight channel is present, only the first three are used.
%
% Optional Inputs:
%
% PathRadius_percent : radius of the circular path taken by the viewpoint. Values that are too
% high can result in collision with the edges of the lenslet image, while
% values that are too small result in a less impressive visualization. The
% default value is 60%.
%
% FrameDelay : sets the delay between frames, in seconds. The default value is 1/60th of
% a second.
%
% ScaleFactor : Adjusts the size of the display -- 1 means no change, 2 means twice as
% big, etc. Integer values are recommended to avoid scaling artifacts. Note
% that the scale factor is only applied the first time a figure is created.
% To change the scale factor, close the figure before calling
% LFDispMousePan.
%
% Outputs:
%
% FigureHandle
%
%
% See also: LFDisp, LFDispMousePan
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function FigureHandle = LFDispVidCirc( LF, PathRadius_percent, FrameDelay, varargin )
%---Defaults---
PathRadius_percent = LFDefaultVal( 'PathRadius_percent', 60 );
FrameDelay = LFDefaultVal( 'FrameDelay', 1/60 );
%---Check for mono and clip off the weight channel if present---
Mono = (ndims(LF) == 4);
if( ~Mono )
LF = LF(:,:,:,:,1:3);
end
%---Rescale for 8-bit display---
if( isfloat(LF) )
LF = uint8(LF ./ max(LF(:)) .* 255);
else
LF = uint8(LF.*(255 / double(intmax(class(LF)))));
end
%---Setup the display---
[ImageHandle,FigureHandle] = LFDispSetup( squeeze(LF(floor(end/2),floor(end/2),:,:,:)), varargin{:} );
%---Setup the motion path---
[TSize,SSize, ~,~] = size(LF(:,:,:,:,1));
TCent = (TSize-1)/2 + 1;
SCent = (SSize-1)/2 + 1;
t = 0;
RotRate = 0.05;
RotRad = TCent*PathRadius_percent/100;
while(1)
TVal = TCent + RotRad * cos( 2*pi*RotRate * t );
SVal = SCent + RotRad * sin( 2*pi*RotRate * t );
SIdx = round(SVal);
TIdx = round(TVal);
CurFrame = squeeze(LF( TIdx, SIdx, :,:,: ));
set(ImageHandle,'cdata', CurFrame );
pause(FrameDelay)
t = t + 1;
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFDisp.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFDisp.m
| 1,447 |
utf_8
|
e7dcaf88325fd23f136fac4a166709e5
|
% LFDisp - Convenience function to display a 2D slice of a light field
%
% Usage:
% LFSlice = LFDispMousePan( LF )
% LFDispMousePan( LF )
%
%
% The centermost image is taken in s and t. Also works with 3D arrays of images. If an output argument is included, no
% display is generated, but the extracted slice is returned instead.
%
% Inputs:
%
% LF : a colour or single-channel light field, and can a floating point or integer format. For
% display, it is scaled as in imagesc. If LF contains more than three colour
% channels, as is the case when a weight channel is present, only the first three are used.
%
%
% Outputs:
%
% LFSlice : if an output argument is used, no display is generated, but the extracted slice is returned.
%
%
% See also: LFDispVidCirc, LFDispMousePan
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function ImgOut = LFDisp( LF )
LF = squeeze(LF);
LFSize = size(LF);
HasWeight = (ndims(LF)>2 && LFSize(end)==2 || LFSize(end)==4);
HasColor = (ndims(LF)>2 && (LFSize(end)==3 || LFSize(end)==4) );
HasMonoAndWeight = (ndims(LF)>2 && LFSize(end)==2);
if( HasColor || HasMonoAndWeight )
GoalDims = 3;
else
GoalDims = 2;
end
while( ndims(LF) > GoalDims )
LF = squeeze(LF(round(end/2),:,:,:,:,:,:));
end
if( HasWeight )
LF = squeeze(LF(:,:,1:end-1));
end
if( nargout > 0 )
ImgOut = LF;
else
imagesc(LF);
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFBuild2DFreqFan.m
|
.m
|
light-field-TB-master/LFToolbox0.4/LFBuild2DFreqFan.m
| 4,507 |
utf_8
|
d3bc64badf14c750b5f1f2a996936c1f
|
% LFBuild2DFreqFan - construct a 2D fan passband filter in the frequency domain
%
% Usage:
%
% [H, FiltOptions] = LFBuild2DFreqFan( LFSize, Slope1, Slope2, BW, FiltOptions )
% H = LFBuild2DFreqFan( LFSize, Slope, BW )
%
% This file constructs a real-valued magnitude response in 2D, for which the passband is a fan.
%
% Once constructed the filter must be applied to a light field, e.g. using LFFilt2DFFT. The
% LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters.
%
% A more technical discussion, including the use of filters for denoising and volumetric focus, and
% the inclusion of aliases components, is included in:
%
% [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field
% Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015.
%
% Inputs:
%
% LFSize : Size of the frequency-domain filter. This should match or exceed the size of the
% light field to be filtered. If it's larger than the input light field, the input is
% zero-padded to match the filter's size by LFFilt2DFFT.
%
% Slope1, Slope2 : Slopes at the extents of the fan passband.
%
% BW : 3-db Bandwidth of the planar passband.
%
% [optional] FiltOptions : struct controlling filter construction
% SlopeMethod : only 'Skew' is supported for now
% Precision : 'single' or 'double', default 'single'
% Rolloff : 'Gaussian' or 'Butter', default 'Gaussian'
% Order : controls the order of the filter when Rolloff is 'Butter', default 3
% Aspect2D : aspect ratio of the light field, default [1 1]
% Window : Default false. By default the edges of the passband are sharp; this adds
% a smooth rolloff at the edges when used in conjunction with Extent2D or
% IncludeAliased.
% Extent2D : controls where the edge of the passband occurs, the default [1 1]
% is the edge of the Nyquist box. When less than 1, enabling windowing
% introduces a rolloff after the edge of the passband. Can be greater
% than 1 when using IncludeAliased.
% IncludeAliased : default false; allows the passband to wrap around off the edge of the
% Nyquist box; used in conjunction with Window and/or Extent2D. This can
% increase processing time dramatically, e.g. Extent2D = [2,2]
% requires a 2^2 = 4-fold increase in time to construct the filter.
% Useful when passband content is aliased, see [2].
%
% Outputs:
%
% H : real-valued frequency magnitude response
% FiltOptions : The filter options including defaults, with an added PassbandInfo field
% detailing the function and time of construction of the filter
%
% See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, LFBuild2DFreqFan, LFBuild2DFreqLine,
% LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT,
% LFFiltShiftSum
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [H, FiltOptions] = LFBuild2DFreqFan( LFSize, Slope1, Slope2, BW, FiltOptions )
FiltOptions = LFDefaultField('FiltOptions', 'SlopeMethod', 'Skew'); % 'Skew' only for now
DistFunc = @(P, FiltOptions) DistFunc_2DFan( P, Slope1, Slope2, FiltOptions );
[H, FiltOptions] = LFHelperBuild2DFreq( LFSize, BW, FiltOptions, DistFunc );
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
end
%-----------------------------------------------------------------------------------------------------------------------
function Dist = DistFunc_2DFan( P, Slope1, Slope2, FiltOptions )
switch( lower(FiltOptions.SlopeMethod) )
case 'skew'
if( Slope2 < Slope1 )
t = Slope1;
Slope1 = Slope2;
Slope2 = t;
end
R1 = eye(2);
R2 = R1;
R1(1,2) = Slope1;
R2(1,2) = Slope2;
otherwise
error('Unrecognized slope method');
end
P1 = R1 * P;
P2 = R2 * P;
TransitionPt = LFSign(P1(2,:));
CurDist1 = max(0, TransitionPt .* P1(1,:));
CurDist2 = max(0,-TransitionPt .* P2(1,:));
Dist = max(CurDist1, CurDist2).^2;
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFDefaultIntrinsics.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFDefaultIntrinsics.m
| 2,030 |
utf_8
|
948ce39fff4f94ed954e090033778c04
|
% LFDefaultIntrinsics - Initializes a set of intrinsics for use in rectifying light fields
%
% Usage:
%
% RectCamIntrinsicsH = LFDefaultIntrinsics( LFSize, CalInfo )
%
% This gets called by LFCalDispRectIntrinsics to set up a default set of intrinsics for rectification. Based on the
% calibration information and the dimensions of the light field, a set of intrinsics is selected which yields square
% pixels in ST and UV. Ideally the values will use the hypercube-shaped light field space efficiently, leaving few black
% pixels at the edges, and bumping as little information /outside/ the hypercube as possible.
%
% The sampling pattern yielded by the resulting intrinsics can be visualized using LFCalDispRectIntrinsics.
%
% Inputs :
%
% LFSize : Size of the light field to rectify
%
% CalInfo : Calibration info as loaded by LFFindCalInfo, for example.
%
% Outputs:
%
% RectCamIntrinsicsH : The resulting intrinsics.
%
% See also: LFCalDispRectIntrinsics, LFRecenterIntrinsics, LFFindCalInfo, LFUtilDecodeLytroFolder
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function RectCamIntrinsicsH = LFDefaultIntrinsics( LFSize, CalInfo )
RectCamIntrinsicsH = CalInfo.EstCamIntrinsicsH;
ST_ST_Slope = mean([CalInfo.EstCamIntrinsicsH(1,1), CalInfo.EstCamIntrinsicsH(2,2)]);
ST_UV_Slope = mean([CalInfo.EstCamIntrinsicsH(1,3), CalInfo.EstCamIntrinsicsH(2,4)]);
UV_ST_Slope = mean([CalInfo.EstCamIntrinsicsH(3,1), CalInfo.EstCamIntrinsicsH(4,2)]);
UV_UV_Slope = mean([CalInfo.EstCamIntrinsicsH(3,3), CalInfo.EstCamIntrinsicsH(4,4)]);
RectCamIntrinsicsH(1,1) = ST_ST_Slope;
RectCamIntrinsicsH(2,2) = ST_ST_Slope;
RectCamIntrinsicsH(1,3) = ST_UV_Slope;
RectCamIntrinsicsH(2,4) = ST_UV_Slope;
RectCamIntrinsicsH(3,1) = UV_ST_Slope;
RectCamIntrinsicsH(4,2) = UV_ST_Slope;
RectCamIntrinsicsH(3,3) = UV_UV_Slope;
RectCamIntrinsicsH(4,4) = UV_UV_Slope;
%---force s,t translation to CENTER---
RectCamIntrinsicsH = LFRecenterIntrinsics( RectCamIntrinsicsH, LFSize );
|
github
|
Vincentqyw/light-field-TB-master
|
LFDefaultField.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFDefaultField.m
| 1,979 |
utf_8
|
485dfac0b4aba775cf4d1d20f537f0f7
|
% LFDefaultField - Convenience function to set up structs with default field values
%
% Usage:
%
% ParentStruct = LFDefaultField( ParentStruct, FieldName, DefaultVal )
%
% This provides an elegant way to establish default field values in a struct. See LFDefaultValue for
% setting up non-struct variables with default values.
%
% Inputs:
%
% ParentStruct: string giving the name of the struct; the struct need not already exist
% FieldName: string giving the name of the field
% DefaultVal: default value for the field
%
% Outputs:
%
% ParentStruct: if the named struct and field already existed, the output matches the struct's
% original value; otherwise the output is a struct with an additional field taking
% on the specified default value
%
% Example:
%
% clearvars
% ExistingStruct.ExistingField = 42;
% ExistingStruct = LFDefaultField( 'ExistingStruct', 'ExistingField', 3 )
% ExistingStruct = LFDefaultField( 'ExistingStruct', 'NewField', 36 )
% OtherStruct = LFDefaultField( 'OtherStruct', 'Cheese', 'Indeed' )
%
%
% Results in :
% ExistingStruct =
% ExistingField: 42
% NewField: 36
% OtherStruct =
% Cheese: 'Indeed'
%
% Usage for setting up default function arguments is demonstrated in most of the LF Toolbox
% functions.
%
% See also: LFDefaultVal
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function ParentStruct = LFDefaultField( ParentStruct, FieldName, DefaultVal )
%---First make sure the struct exists---
CheckIfExists = sprintf('exist(''%s'', ''var'') && ~isempty(%s)', ParentStruct, ParentStruct);
VarExists = evalin( 'caller', CheckIfExists );
if( ~VarExists )
ParentStruct = [];
else
ParentStruct = evalin( 'caller', ParentStruct );
end
%---Now make sure the field exists---
if( ~isfield( ParentStruct, FieldName ) )
ParentStruct.(FieldName) = DefaultVal;
end
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFSign.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFSign.m
| 225 |
utf_8
|
901dea01bff401571d8125711feeffad
|
% LFSign - Like Matlab's sign, but never returns 0, treating 0 as positive
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function s = LFSign(i)
s = ones(size(i));
s(i<0) = -1;
|
github
|
Vincentqyw/light-field-TB-master
|
LFRotz.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFRotz.m
| 306 |
utf_8
|
2a4fc216ff9e1b6b35762c010ebe50f2
|
% LFRotz - simple 3D rotation matrix, rotation about z
%
% Usage:
% R = LFRotz( psi )
%
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function R = LFRotz(psi)
c = cos(psi);
s = sin(psi);
R = [ c, -s, 0; ...
s, c, 0; ...
0, 0, 1 ];
|
github
|
Vincentqyw/light-field-TB-master
|
LFHelperBuild4DFreq.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFHelperBuild4DFreq.m
| 4,143 |
utf_8
|
5cefe44f63c8fd80b66ad5e267298bff
|
% LFHelperBuild4DFreq - Helper function used to construct 4D frequency-domain filters
%
% Much of the complexity in constructing MD frequency-domain filters, especially around including aliased components and
% controlling the filter rolloff, is common between filter shapes. This function wraps much of this complexity.
%
% This gets called by the LFBuild4DFreq* functions.
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [H, FiltOptions] = LFHelperBuild4DFreq( LFSize, BW, FiltOptions, DistFunc )
FiltOptions = LFDefaultField('FiltOptions', 'Precision', 'single');
FiltOptions = LFDefaultField('FiltOptions', 'Rolloff', 'Gaussian'); %Gaussian or Butter
FiltOptions = LFDefaultField('FiltOptions', 'Aspect4D', 1);
FiltOptions = LFDefaultField('FiltOptions', 'Window', false);
FiltOptions = LFDefaultField('FiltOptions', 'Extent4D', 1.0);
FiltOptions = LFDefaultField('FiltOptions', 'IncludeAliased', false);
FiltOptions.Extent4D = cast(FiltOptions.Extent4D, FiltOptions.Precision); % avoid rounding error during comparisons
FiltOptions.Aspect4D = cast(FiltOptions.Aspect4D, FiltOptions.Precision); % avoid rounding error during comparisons
if( length(LFSize) == 1 )
LFSize = LFSize .* [1,1,1,1];
end
if( length(LFSize) == 5 )
LFSize = LFSize(1:4);
end
if( length(FiltOptions.Extent4D) == 1 )
FiltOptions.Extent4D = FiltOptions.Extent4D .* [1,1,1,1];
end
if( length(FiltOptions.Aspect4D) == 1 )
FiltOptions.Aspect4D = FiltOptions.Aspect4D .* [1,1,1,1];
end
ExtentWithAspect = FiltOptions.Extent4D.*FiltOptions.Aspect4D / 2;
t = LFNormalizedFreqAxis( LFSize(1), FiltOptions.Precision ) .* FiltOptions.Aspect4D(1);
s = LFNormalizedFreqAxis( LFSize(2), FiltOptions.Precision ) .* FiltOptions.Aspect4D(2);
v = LFNormalizedFreqAxis( LFSize(3), FiltOptions.Precision ) .* FiltOptions.Aspect4D(3);
u = LFNormalizedFreqAxis( LFSize(4), FiltOptions.Precision ) .* FiltOptions.Aspect4D(4);
[tt,ss,vv,uu] = ndgrid(cast(t,FiltOptions.Precision),cast(s,FiltOptions.Precision),cast(v,FiltOptions.Precision),cast(u,FiltOptions.Precision));
P = [tt(:),ss(:),vv(:),uu(:)]';
clear s t u v ss tt uu vv
if( ~FiltOptions.IncludeAliased )
Tiles = [0,0,0,0];
else
Tiles = ceil(ExtentWithAspect);
end
if( FiltOptions.IncludeAliased )
AADist = inf(LFSize, FiltOptions.Precision);
end
WinDist = 0;
% Tiling proceeds only in positive directions, symmetry is enforced afterward, saving some computation overall
for( TTile = 0:Tiles(1) )
for( STile = 0:Tiles(2) )
for( VTile = 0:Tiles(3) )
for( UTile = 0:Tiles(4) )
Dist = inf(LFSize, FiltOptions.Precision);
if( FiltOptions.Window )
ValidIdx = ':';
WinDist = bsxfun(@minus, abs(P)', ExtentWithAspect);
WinDist = sum(max(0,WinDist).^2, 2);
WinDist = reshape(WinDist, LFSize);
else
ValidIdx = find(all(bsxfun(@le, abs(P), ExtentWithAspect')));
end
Dist(ValidIdx) = DistFunc(P(:,ValidIdx), FiltOptions);
Dist = Dist + WinDist;
if( FiltOptions.IncludeAliased )
AADist(:) = min(AADist(:), Dist(:));
end
P(4,:) = P(4,:) + FiltOptions.Aspect4D(4);
end
P(4,:) = P(4,:) - (Tiles(4)+1) .* FiltOptions.Aspect4D(4);
P(3,:) = P(3,:) + FiltOptions.Aspect4D(3);
end
P(3,:) = P(3,:) - (Tiles(3)+1) .* FiltOptions.Aspect4D(3);
P(2,:) = P(2,:) + FiltOptions.Aspect4D(2);
end
P(2,:) = P(2,:) - (Tiles(2)+1) .* FiltOptions.Aspect4D(2);
P(1,:) = P(1,:) + FiltOptions.Aspect4D(1);
end
if( FiltOptions.IncludeAliased )
Dist = AADist;
clear AADist
end
H = zeros(LFSize, FiltOptions.Precision);
switch lower(FiltOptions.Rolloff)
case 'gaussian'
BW = BW.^2 / log(sqrt(2));
H(:) = exp( -Dist / BW ); % Gaussian rolloff
case 'butter'
FiltOptions = LFDefaultField('FiltOptions', 'Order', 3);
Dist = sqrt(Dist) ./ BW;
H(:) = sqrt( 1.0 ./ (1.0 + Dist.^(2*FiltOptions.Order)) ); % Butterworth-like rolloff
otherwise
error('unrecognized rolloff method');
end
H = ifftshift(H);
% force symmetric
H = max(H, H(mod(LFSize(1):-1:1,LFSize(1))+1, mod(LFSize(2):-1:1,LFSize(2))+1,mod(LFSize(3):-1:1,LFSize(3))+1,mod(LFSize(4):-1:1,LFSize(4))+1));
|
github
|
Vincentqyw/light-field-TB-master
|
LFCalInit.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFCalInit.m
| 10,538 |
utf_8
|
50b5d42f601852034d9bfaa26788439a
|
% LFCalInit - initialize calibration estimate, called by LFUtilCalLensletCam
%
% Usage:
% CalOptions = LFCalInit( InputPath, CalOptions )
% CalOptions = LFCalInit( InputPath )
%
% This function is called by LFUtilCalLensletCam to initialize a pose and camera model estimate
% given a set of extracted checkerboard corners.
%
% Inputs:
%
% InputPath : Path to folder containing processed checkerboard images. Checkerboard corners must
% be identified prior to calling this function, by running LFCalFindCheckerCorners
% for example. This is demonstrated by LFUtilCalLensletCam.
%
% [optional] CalOptions : struct controlling calibration parameters, all fields are optional
% .SaveResult : Set to false to perform a "dry run"
% .CheckerCornersFnamePattern : Pattern for finding checkerboard corner files, as generated by
% LFCalFindCheckerCorners; %s is a placeholder for the base filename
% .CheckerInfoFname : Name of the output file containing the summarized checkerboard
% information
% .CalInfoFname : Name of the file containing an initial estimate, to be refined.
% Note that this parameter is automatically set in the CalOptions
% struct returned by LFCalInit
% .ForceRedoInit : Forces the function to overwrite existing results
%
% Outputs :
%
% CalOptions struct as applied, including any default values as set up by the function.
%
% The checkerboard info file and calibration info file are the key outputs of this function.
%
% See also: LFUtilCalLensletCam, LFCalFindCheckerCorners, LFCalRefine
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function CalOptions = LFCalInit( InputPath, CalOptions )
%---Defaults---
CalOptions = LFDefaultField( 'CalOptions', 'SaveResult', true );
CalOptions = LFDefaultField( 'CalOptions', 'CheckerCornersFnamePattern', '%s__CheckerCorners.mat' );
CalOptions = LFDefaultField( 'CalOptions', 'CheckerInfoFname', 'CheckerboardCorners.mat' );
CalOptions = LFDefaultField( 'CalOptions', 'CalInfoFname', 'CalInfo.json' );
CalOptions = LFDefaultField( 'CalOptions', 'ForceRedoInit', false );
%---Start by checking if this step has already been completed---
fprintf('\n===Initializing calibration process===\n');
CalInfoSaveFname = fullfile(InputPath, CalOptions.CalInfoFname);
if( ~CalOptions.ForceRedoInit && exist(CalInfoSaveFname, 'file') )
fprintf(' ---File %s already exists, skipping---\n', CalInfoSaveFname);
return;
end
%---Compute ideal checkerboard geometry - order matters---
IdealCheckerX = CalOptions.ExpectedCheckerSpacing_m(1) .* (0:CalOptions.ExpectedCheckerSize(1)-1);
IdealCheckerY = CalOptions.ExpectedCheckerSpacing_m(2) .* (0:CalOptions.ExpectedCheckerSize(2)-1);
[IdealCheckerY, IdealCheckerX] = ndgrid(IdealCheckerY, IdealCheckerX);
IdealChecker = cat(3,IdealCheckerX, IdealCheckerY, zeros(size(IdealCheckerX)));
IdealChecker = reshape(IdealChecker, [], 3)';
%---Crawl folder structure locating corner info files---
fprintf('\n===Locating checkerboard corner files in %s===\n', InputPath);
[CalOptions.FileList, BasePath] = LFFindFilesRecursive( InputPath, sprintf(CalOptions.CheckerCornersFnamePattern, '*') );
fprintf('Found :\n');
disp(CalOptions.FileList)
%---Initial estimate of focal length---
fprintf('Initial estimate of focal length...\n');
SkippedFileCount = 0;
ValidSuperPoseCount = 0;
ValidCheckerCount = 0;
%---Process each checkerboard corner file---
for( iFile = 1:length(CalOptions.FileList) )
ValidSuperPoseCount = ValidSuperPoseCount + 1;
CurFname = CalOptions.FileList{iFile};
[~,ShortFname] = fileparts(CurFname);
fprintf('---%s [%3d / %3d]...', ShortFname, ValidSuperPoseCount+SkippedFileCount, length(CalOptions.FileList));
load(fullfile(BasePath, CurFname), 'CheckerCorners', 'LFSize', 'CamInfo', 'LensletGridModel', 'DecodeOptions');
PerImageValidCount = 0;
for( TIdx = 1:size(CheckerCorners,1) )
for( SIdx = 1:size(CheckerCorners,2) )
CurChecker = CheckerCorners{TIdx, SIdx}';
CurSize = size(CurChecker);
CurValid = (CurSize(2) == prod(CalOptions.ExpectedCheckerSize));
CheckerValid(ValidSuperPoseCount, TIdx, SIdx) = CurValid;
%---For valid poses (having expected corner count), compute a homography---
if( CurValid )
ValidCheckerCount = ValidCheckerCount + 1;
PerImageValidCount = PerImageValidCount + 1;
%--- reorient to expected ---
Centroid = mean( CurChecker,2 );
IsTopLeft = all(CurChecker(:,1) < Centroid);
IsTopRight = (CurChecker(1,1) > Centroid(1) && CurChecker(2,1) < Centroid(2));
if( IsTopRight )
CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]);
CurChecker = CurChecker(:, end:-1:1, :);
CurChecker = permute(CurChecker, [1,3,2]);
CurChecker = reshape(CurChecker, 2, []);
end
IsTopLeft = all(CurChecker(:,1) < Centroid);
assert( IsTopLeft, 'Error: unexpected point order from detectCheckerboardPoints' );
CheckerObs{ValidSuperPoseCount, TIdx, SIdx} = CurChecker;
%---Compute homography for each subcam pose---
CurH = compute_homography( CurChecker, IdealChecker(1:2,:) );
H(ValidCheckerCount, :,:) = CurH;
end
end
end
CalOptions.ValidSubimageCount(iFile) = PerImageValidCount;
fprintf(' %d / %d valid.\n', PerImageValidCount, prod(LFSize(1:2)));
end
A = [];
b = [];
%---Initialize principal point at the center of the image---
% This section of code is based heavily on code from the Camera Calibration Toolbox for Matlab by
% Jean-Yves Bouguet
CInit = LFSize([4,3])'/2 - 0.5;
RecenterH = [1, 0, -CInit(1); 0, 1, -CInit(2); 0, 0, 1];
for iHomography = 1:size(H,1)
CurH = squeeze(H(iHomography,:,:));
CurH = RecenterH * CurH;
%---Extract vanishing points (direct and diagonal)---
V_hori_pix = CurH(:,1);
V_vert_pix = CurH(:,2);
V_diag1_pix = (CurH(:,1)+CurH(:,2))/2;
V_diag2_pix = (CurH(:,1)-CurH(:,2))/2;
V_hori_pix = V_hori_pix/norm(V_hori_pix);
V_vert_pix = V_vert_pix/norm(V_vert_pix);
V_diag1_pix = V_diag1_pix/norm(V_diag1_pix);
V_diag2_pix = V_diag2_pix/norm(V_diag2_pix);
a1 = V_hori_pix(1);
b1 = V_hori_pix(2);
c1 = V_hori_pix(3);
a2 = V_vert_pix(1);
b2 = V_vert_pix(2);
c2 = V_vert_pix(3);
a3 = V_diag1_pix(1);
b3 = V_diag1_pix(2);
c3 = V_diag1_pix(3);
a4 = V_diag2_pix(1);
b4 = V_diag2_pix(2);
c4 = V_diag2_pix(3);
CurA = [a1*a2, b1*b2; a3*a4, b3*b4];
CurB = -[c1*c2; c3*c4];
if( isempty(find(isnan(CurA), 1)) && isempty(find(isnan(CurB), 1)) )
A = [A; CurA];
b = [b; CurB];
end
end
FocInit = sqrt(b'*(sum(A')') / (b'*b)) * ones(2,1);
fprintf('Init focal length est: %.2f, %.2f\n', FocInit);
%---Initial estimate of extrinsics---
fprintf('\nInitial estimate of extrinsics...\n');
for( iSuperPoseIdx = 1:ValidSuperPoseCount )
fprintf('---[%d / %d]', iSuperPoseIdx, ValidSuperPoseCount);
for( TIdx = 1:size(CheckerCorners,1) )
fprintf('.');
for( SIdx = 1:size(CheckerCorners,2) )
if( ~CheckerValid(iSuperPoseIdx, TIdx, SIdx) )
continue;
end
CurChecker = CheckerObs{iSuperPoseIdx, TIdx, SIdx};
[CurRot, CurTrans] = compute_extrinsic_init(CurChecker, IdealChecker, FocInit, CInit, zeros(1,5), 0);
[CurRot, CurTrans] = compute_extrinsic_refine(CurRot, CurTrans, CurChecker, IdealChecker, FocInit, CInit, zeros(1,5), 0,20,1000000);
RotVals{iSuperPoseIdx, TIdx, SIdx} = CurRot;
TransVals{iSuperPoseIdx, TIdx, SIdx} = CurTrans;
end
end
%---Approximate each superpose as the median of its sub-poses---
% note the approximation in finding the mean orientation: mean of rodrigues... works because all
% sub-orientations within a superpose are nearly identical.
MeanRotVals(iSuperPoseIdx,:) = median([RotVals{iSuperPoseIdx, :, :}], 2);
MeanTransVals(iSuperPoseIdx,:) = median([TransVals{iSuperPoseIdx, :, :}], 2);
fprintf('\n');
%---Track the apparent "baseline" of the camera at each pose---
CurDist = bsxfun(@minus, [TransVals{iSuperPoseIdx, :, :}], MeanTransVals(iSuperPoseIdx,:)');
CurAbsDist = sqrt(sum(CurDist.^2));
% store as estimated diameter; the 3/2 comes from the mean radius of points on a disk (2R/3)
BaselineApprox(iSuperPoseIdx) = 2 * 3/2 * mean(CurAbsDist);
end
%---Initialize the superpose estimates---
EstCamPosesV = [MeanTransVals, MeanRotVals];
%---Estimate full intrinsic matrix---
ST_IJ_SlopeApprox = mean(BaselineApprox) ./ (LFSize(2:-1:1)-1);
UV_KL_SlopeApprox = 1./FocInit';
EstCamIntrinsicsH = eye(5);
EstCamIntrinsicsH(1,1) = ST_IJ_SlopeApprox(1);
EstCamIntrinsicsH(2,2) = ST_IJ_SlopeApprox(2);
EstCamIntrinsicsH(3,3) = UV_KL_SlopeApprox(1);
EstCamIntrinsicsH(4,4) = UV_KL_SlopeApprox(2);
% Force central ray as s,t,u,v = 0, note all indices start at 1, not 0
EstCamIntrinsicsH = LFRecenterIntrinsics( EstCamIntrinsicsH, LFSize );
fprintf('\nInitializing estimate of camera intrinsics to: \n');
disp(EstCamIntrinsicsH);
%---Start with no distortion estimate---
EstCamDistortionV = [];
%---Optionally save the results---
if( CalOptions.SaveResult )
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
CheckerSaveFname = fullfile(BasePath, CalOptions.CheckerInfoFname);
fprintf('\nSaving to %s...\n', CheckerSaveFname);
save(CheckerSaveFname, 'GeneratedByInfo', 'CalOptions', 'CheckerObs', 'IdealChecker', 'LFSize', 'CamInfo', 'LensletGridModel', 'DecodeOptions');
fprintf('Saving to %s...\n', CalInfoSaveFname);
LFWriteMetadata(CalInfoSaveFname, LFVar2Struct(GeneratedByInfo, LensletGridModel, EstCamIntrinsicsH, EstCamDistortionV, EstCamPosesV, CamInfo, CalOptions, DecodeOptions));
end
fprintf(' ---Calibration initialization done---\n');
|
github
|
Vincentqyw/light-field-TB-master
|
LFHelperBuild2DFreq.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFHelperBuild2DFreq.m
| 3,367 |
utf_8
|
3cd16d8e0a260aa2447e46ea325a04f9
|
% LFHelperBuild2DFreq - Helper function used to construct 2D frequency-domain filters
%
% Much of the complexity in constructing MD frequency-domain filters, especially around including aliased components and
% controlling the filter rolloff, is common between filter shapes. This function wraps much of this complexity.
%
% This gets called by the LFBuild2DFreq* functions.
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [H, FiltOptions] = LFHelperBuild2DFreq( LFSize, BW, FiltOptions, DistFunc )
FiltOptions = LFDefaultField('FiltOptions', 'Precision', 'single');
FiltOptions = LFDefaultField('FiltOptions', 'Rolloff', 'Gaussian'); %Gaussian or Butter
FiltOptions = LFDefaultField('FiltOptions', 'Aspect2D', 1);
FiltOptions = LFDefaultField('FiltOptions', 'Window', false);
FiltOptions = LFDefaultField('FiltOptions', 'Extent2D', 1.0);
FiltOptions = LFDefaultField('FiltOptions', 'IncludeAliased', false);
FiltOptions.Extent2D = cast(FiltOptions.Extent2D, FiltOptions.Precision); % avoid rounding error during comparisons
FiltOptions.Aspect2D = cast(FiltOptions.Aspect2D, FiltOptions.Precision); % avoid rounding error during comparisons
if( length(LFSize) == 1 )
LFSize = LFSize .* [1,1];
end
if( length(FiltOptions.Extent2D) == 1 )
FiltOptions.Extent2D = FiltOptions.Extent2D .* [1,1];
end
if( length(FiltOptions.Aspect2D) == 1 )
FiltOptions.Aspect2D = FiltOptions.Aspect2D .* [1,1];
end
ExtentWithAspect = FiltOptions.Extent2D.*FiltOptions.Aspect2D / 2;
s = LFNormalizedFreqAxis( LFSize(1), FiltOptions.Precision ) .* FiltOptions.Aspect2D(1);
u = LFNormalizedFreqAxis( LFSize(2), FiltOptions.Precision ) .* FiltOptions.Aspect2D(2);
[ss,uu] = ndgrid(s,u);
P = [ss(:),uu(:)]';
clear s u ss uu
if( ~FiltOptions.IncludeAliased )
Tiles = [0,0];
else
Tiles = ceil(ExtentWithAspect);
end
if( FiltOptions.IncludeAliased )
AADist = inf(LFSize, FiltOptions.Precision);
end
WinDist = 0;
% Tiling proceeds only in positive directions, symmetry is enforced afterward, saving some computation overall
for( STile = 0:Tiles(1) )
for( UTile = 0:Tiles(2) )
Dist = inf(LFSize, FiltOptions.Precision);
if( FiltOptions.Window )
ValidIdx = ':';
WinDist = bsxfun(@minus, abs(P)', ExtentWithAspect);
WinDist = sum(max(0,WinDist).^2, 2);
WinDist = reshape(WinDist, LFSize);
else
ValidIdx = find(all(bsxfun(@le, abs(P), ExtentWithAspect')));
end
Dist(ValidIdx) = DistFunc(P(:,ValidIdx), FiltOptions);
Dist = Dist + WinDist;
if( FiltOptions.IncludeAliased )
AADist(:) = min(AADist(:), Dist(:));
end
P(2,:) = P(2,:) + FiltOptions.Aspect2D(2);
end
P(2,:) = P(2,:) - (Tiles(2)+1) .* FiltOptions.Aspect2D(2);
P(1,:) = P(1,:) + FiltOptions.Aspect2D(1);
end
if( FiltOptions.IncludeAliased )
Dist = AADist;
clear AADist
end
H = zeros(LFSize, FiltOptions.Precision);
switch lower(FiltOptions.Rolloff)
case 'gaussian'
BW = BW.^2 / log(sqrt(2));
H(:) = exp( -Dist / BW ); % Gaussian rolloff
case 'butter'
FiltOptions = LFDefaultField('FiltOptions', 'Order', 3);
Dist = sqrt(Dist) ./ BW;
H(:) = sqrt( 1.0 ./ (1.0 + Dist.^(2*FiltOptions.Order)) ); % Butterworth-like rolloff
otherwise
error('unrecognized rolloff method');
end
H = ifftshift(H);
% force symmetric
H = max(H, H(mod(LFSize(1):-1:1,LFSize(1))+1, mod(LFSize(2):-1:1,LFSize(2))+1));
|
github
|
Vincentqyw/light-field-TB-master
|
LFFindLytroPartnerFile.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFFindLytroPartnerFile.m
| 1,439 |
utf_8
|
a4f3d1519bad3b234bde99c00a97ea3d
|
% LFFindLytroPartnerFile - Finds metadata / raw data file partner for Lytro white images
%
% Usage:
%
% PartnerFilename = LFFindLytroPartnerFile( OrigFilename, PartnerFilenameExtension )
%
% The LF Reader tool prepends filenames extracted from LFP storage files, complicating .txt / .raw
% file association as the prefix can vary between two files in a pair. This function finds a file's
% partner based on a known filename pattern (using underscores to separate the base filename), and a
% know partner filename extension. Note this is set up to work specifically with the naming
% conventions used by the LFP Reader tool.
%
% Inputs:
% OrigFilename is the known filename
% PartnerFilenameExtension is the extension of the file to find
%
% Output:
% PartnerFilename is the name of the first file found matching the specified extension
%
% See also: LFUtilProcessWhiteImages, LFUtilProcessCalibrations
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function PartnerFilename = LFFindLytroPartnerFile( OrigFilename, PartnerFilenameExtension )
[CurFnamePath, CurFnameBase] = fileparts( OrigFilename );
PrependIdx = find(CurFnameBase == '_', 1);
CurFnamePattern = strcat('*', CurFnameBase(PrependIdx:end), PartnerFilenameExtension);
DirResult = dir(fullfile(CurFnamePath, CurFnamePattern));
DirResult = DirResult(1).name;
PartnerFilename = fullfile(CurFnamePath, DirResult);
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFVar2Struct.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFVar2Struct.m
| 646 |
utf_8
|
8e9d0eed0d9242fdf45c14ba302e05d2
|
% LFVar2Struct - Convenience function to build a struct from a set of variables
%
% Usage:
% StructOut = LFVar2Struct( var1, var2, ... )
%
% Example:
% Apples = 3;
% Oranges = 4;
% FruitCount = LFVar2Struct( Apples, Oranges )
%
% Results in a struct FruitCount:
% FruitCount =
% Apples: 3
% Oranges: 4
%
% See also: LFStruct2Var
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function StructOut = LFVar2Struct( varargin )
VarNames = arrayfun( @inputname, 1:nargin, 'UniformOutput', false );
StructOut = cell2struct( varargin, VarNames, 2 );
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFBuildLensletGridModel.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFBuildLensletGridModel.m
| 9,749 |
utf_8
|
77a704b9345494e7a5ab0bc07f763d10
|
% LFBuildLensletGridModel - builds a lenslet grid model from a white image, called by LFUtilProcessWhiteImages
%
% Usage:
% [LensletGridModel, GridCoords] = LFBuildLensletGridModel( WhiteImg, GridModelOptions, DebugDisplay )
%
% Inputs:
% WhiteImg : path of an image taken through a diffuser, or of an entirely white scene
%
% GridModelOptions : struct controlling the model-bulding options
% .ApproxLensletSpacing : A rough initial estimate to initialize the lenslet spacing
% computation
% .FilterDiskRadiusMult : Filter disk radius for prefiltering white image for locating
% lenslets; expressed relative to lenslet spacing; e.g. a
% value of 1/3 means a disk filte with a radius of 1/3 the
% lenslet spacing
% .CropAmt : Image edge pixels to ignore when finding the grid
% .SkipStep : As a speed optimization, not all lenslet centers contribute
% to the grid estimate; <SkipStep> pixels are skipped between
% lenslet centers that get used; a value of 1 means use all
% [optional] .Precision : 'single' or 'double'
%
% [optional] DebugDisplay : enables a debugging display, default false
%
% Outputs:
%
% LensletGridModel : struct describing the lenslet grid
% .HSpacing, .VSpacing : Spacing between lenslets, in pixels
% .HOffset, .VOffset : Offset of first lenslet, in pixels
% .Rot : Rotation of lenslets, in radians
%
% GridCoords : a list of N x M x 2 pixel coordinates generated from the estimated
% LensletGridModel, where N and M are the estimated number of lenslets in the
% horizontal and vertical directions, respectively.
%
% See also: LFUtilProcessWhiteImages
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [LensletGridModel, GridCoords] = LFBuildLensletGridModel( WhiteImg, GridModelOptions, DebugDisplay )
%---Defaults---
GridModelOptions = LFDefaultField( 'GridModelOptions', 'Precision', 'single' );
DebugDisplay = LFDefaultVal( 'DebugDisplay', false );
%---Optionally rotate for vertically-oriented grids---
if( strcmpi(GridModelOptions.Orientation, 'vert') )
WhiteImg = WhiteImg';
end
% Try locating lenslets by convolving with a disk
% Also tested Gaussian... the disk seems to yield a stronger result
h = zeros( size(WhiteImg), GridModelOptions.Precision );
hr = fspecial( 'disk', GridModelOptions.ApproxLensletSpacing * GridModelOptions.FilterDiskRadiusMult );
hr = hr ./ max( hr(:) );
hs = size( hr,1 );
DiskOffset = round( (size(WhiteImg) - hs)/2 );
h( (1:hs) + DiskOffset(1), (1:hs) + DiskOffset(2) ) = hr;
fprintf( 'Filtering...\n' );
% Convolve using fft
WhiteImg = fft2(WhiteImg);
h = fft2(h);
WhiteImg = WhiteImg.*h;
WhiteImg = ifftshift(ifft2(WhiteImg));
WhiteImg = (WhiteImg - min(WhiteImg(:))) ./ abs(max(WhiteImg(:))-min(WhiteImg(:)));
WhiteImg = cast(WhiteImg, GridModelOptions.Precision);
clear h
fprintf('Finding Peaks...\n');
% Find peaks in convolution... ideally these are the lenslet centers
Peaks = imregionalmax(WhiteImg);
PeakIdx = find(Peaks==1);
[PeakIdxY,PeakIdxX] = ind2sub(size(Peaks),PeakIdx);
clear Peaks
% Crop to central peaks; eliminates edge effects
InsidePts = find(PeakIdxY>GridModelOptions.CropAmt & PeakIdxY<size(WhiteImg,1)-GridModelOptions.CropAmt & ...
PeakIdxX>GridModelOptions.CropAmt & PeakIdxX<size(WhiteImg,2)-GridModelOptions.CropAmt);
PeakIdxY = PeakIdxY(InsidePts);
PeakIdxX = PeakIdxX(InsidePts);
%---Form a Delaunay triangulation to facilitate row/column traversal---
Triangulation = DelaunayTri(PeakIdxY, PeakIdxX);
%---Traverse rows and columns of lenslets, collecting stats---
if( DebugDisplay )
LFFigure(3);
cla
imagesc( WhiteImg );
colormap gray
hold on
end
%--Traverse vertically--
fprintf('Vertical fit...\n');
YStart = GridModelOptions.CropAmt*2;
YStop = size(WhiteImg,1)-GridModelOptions.CropAmt*2;
XIdx = 1;
for( XStart = GridModelOptions.CropAmt*2:GridModelOptions.SkipStep:size(WhiteImg,2)-GridModelOptions.CropAmt*2 )
CurPos = [XStart, YStart];
YIdx = 1;
while( 1 )
ClosestLabel = nearestNeighbor(Triangulation, CurPos(2), CurPos(1));
ClosestPt = [PeakIdxX(ClosestLabel), PeakIdxY(ClosestLabel)];
RecPtsY(XIdx,YIdx,:) = ClosestPt;
if( DebugDisplay ) plot( ClosestPt(1), ClosestPt(2), 'r.' ); end
CurPos = ClosestPt;
CurPos(2) = round(CurPos(2) + GridModelOptions.ApproxLensletSpacing * sqrt(3));
if( CurPos(2) > YStop )
break;
end
YIdx = YIdx + 1;
end
%--Estimate angle for this most recent line--
LineFitY(XIdx,:) = polyfit(RecPtsY(XIdx, 3:end-3,2), RecPtsY(XIdx, 3:end-3,1), 1);
XIdx = XIdx + 1;
end
if( DebugDisplay ) drawnow; end
%--Traverse horizontally--
fprintf('Horizontal fit...\n');
XStart = GridModelOptions.CropAmt*2;
XStop = size(WhiteImg,2)-GridModelOptions.CropAmt*2;
YIdx = 1;
for( YStart = GridModelOptions.CropAmt*2:GridModelOptions.SkipStep:size(WhiteImg,1)-GridModelOptions.CropAmt*2 )
CurPos = [XStart, YStart];
XIdx = 1;
while( 1 )
ClosestLabel = nearestNeighbor(Triangulation, CurPos(2), CurPos(1));
ClosestPt = [PeakIdxX(ClosestLabel), PeakIdxY(ClosestLabel)];
RecPtsX(XIdx,YIdx,:) = ClosestPt;
if( DebugDisplay ) plot( ClosestPt(1), ClosestPt(2), 'y.' ); end
CurPos = ClosestPt;
CurPos(1) = round(CurPos(1) + GridModelOptions.ApproxLensletSpacing);
if( CurPos(1) > XStop )
break;
end
XIdx = XIdx + 1;
end
%--Estimate angle for this most recent line--
LineFitX(YIdx,:) = polyfit(RecPtsX(3:end-3,YIdx,1), RecPtsX(3:end-3,YIdx,2), 1);
YIdx = YIdx + 1;
end
if( DebugDisplay ) drawnow; end
%--Trim ends to wipe out alignment, initial estimate artefacts--
RecPtsY = RecPtsY(3:end-2, 3:end-2,:);
RecPtsX = RecPtsX(3:end-2, 3:end-2,:);
%--Estimate angle--
SlopeX = mean(LineFitX(:,1));
SlopeY = mean(LineFitY(:,1));
AngleX = atan2(-SlopeX,1);
AngleY = atan2(SlopeY,1);
EstAngle = mean([AngleX,AngleY]);
%--Estimate spacing, assuming approx zero angle--
t=squeeze(RecPtsY(:,:,2));
YSpacing = diff(t,1,2);
YSpacing = mean(YSpacing(:))/2 / (sqrt(3)/2);
t=squeeze(RecPtsX(:,:,1));
XSpacing = diff(t,1,1);
XSpacing = mean(XSpacing(:));
%--Correct for angle--
XSpacing = XSpacing / cos(EstAngle);
YSpacing = YSpacing / cos(EstAngle);
%--Build initial grid estimate, starting with CropAmt for the offsets--
LensletGridModel = struct('HSpacing',XSpacing, 'VSpacing',YSpacing*sqrt(3)/2, 'HOffset',GridModelOptions.CropAmt, ...
'VOffset',GridModelOptions.CropAmt, 'Rot',-EstAngle, 'Orientation', GridModelOptions.Orientation, ...
'FirstPosShiftRow', 2 );
LensletGridModel.UMax = ceil( (size(WhiteImg,2)-GridModelOptions.CropAmt*2)/XSpacing );
LensletGridModel.VMax = ceil( (size(WhiteImg,1)-GridModelOptions.CropAmt*2)/YSpacing/(sqrt(3)/2) );
GridCoords = LFBuildHexGrid( LensletGridModel );
%--Find offset to nearest peak for each--
GridCoordsX = GridCoords(:,:,1);
GridCoordsY = GridCoords(:,:,2);
BuildGridCoords = [GridCoordsX(:), GridCoordsY(:)];
IdealPts = nearestNeighbor(Triangulation, round(GridCoordsY(:)), round(GridCoordsX(:)));
IdealPtCoords = [PeakIdxX(IdealPts), PeakIdxY(IdealPts)];
%--Estimate single offset for whole grid--
EstOffset = IdealPtCoords - BuildGridCoords;
EstOffset = median(EstOffset);
LensletGridModel.HOffset = LensletGridModel.HOffset + EstOffset(1);
LensletGridModel.VOffset = LensletGridModel.VOffset + EstOffset(2);
%--Remove crop offset / find top-left lenslet--
NewVOffset = mod( LensletGridModel.VOffset, LensletGridModel.VSpacing );
VSteps = round( (LensletGridModel.VOffset - NewVOffset) / LensletGridModel.VSpacing ); % should be a whole number
VStepParity = mod( VSteps, 2 );
if( VStepParity == 1 )
LensletGridModel.HOffset = LensletGridModel.HOffset + LensletGridModel.HSpacing/2;
end
NewHOffset = mod( LensletGridModel.HOffset, LensletGridModel.HSpacing/2 );
HSteps = round( (LensletGridModel.HOffset - NewHOffset) / (LensletGridModel.HSpacing/2) ); % should be a whole number
HStepParity = mod( HSteps, 2 );
LensletGridModel.FirstPosShiftRow = 2-HStepParity;
if( DebugDisplay )
plot( LensletGridModel.HOffset, LensletGridModel.VOffset, 'ro' );
plot( NewHOffset, NewVOffset, 'yx');
drawnow
end
LensletGridModel.HOffset = NewHOffset;
LensletGridModel.VOffset = NewVOffset;
%---Finalize grid---
LensletGridModel.UMax = floor((size(WhiteImg,2)-LensletGridModel.HOffset)/LensletGridModel.HSpacing) + 1;
LensletGridModel.VMax = floor((size(WhiteImg,1)-LensletGridModel.VOffset)/LensletGridModel.VSpacing) + 1;
GridCoords = LFBuildHexGrid( LensletGridModel );
fprintf('...Done.\n');
end
function [GridCoords] = LFBuildHexGrid( LensletGridModel )
RotCent = eye(3);
RotCent(1:2,3) = [LensletGridModel.HOffset, LensletGridModel.VOffset];
ToOffset = eye(3);
ToOffset(1:2,3) = [LensletGridModel.HOffset, LensletGridModel.VOffset];
R = ToOffset * RotCent * LFRotz(LensletGridModel.Rot) * RotCent^-1;
[vv,uu] = ndgrid((0:LensletGridModel.VMax-1).*LensletGridModel.VSpacing, (0:LensletGridModel.UMax-1).*LensletGridModel.HSpacing);
uu(LensletGridModel.FirstPosShiftRow:2:end,:) = uu(LensletGridModel.FirstPosShiftRow:2:end,:) + 0.5.*LensletGridModel.HSpacing;
GridCoords = [uu(:), vv(:), ones(numel(vv),1)];
GridCoords = (R*GridCoords')';
GridCoords = reshape(GridCoords(:,1:2), [LensletGridModel.VMax,LensletGridModel.UMax,2]);
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFDefaultVal.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFDefaultVal.m
| 1,291 |
utf_8
|
c246f7b5e263b013ced34d42170f53b4
|
% LFDefaultVal - Convenience function to set up default parameter values
%
% Usage:
%
% Var = LFDefaultVal( Var, DefaultVal )
%
%
% This provides an elegant way to establish default parameter values. See LFDefaultField for setting
% up structs with default field values.
%
% Inputs:
%
% Var: string giving the name of the parameter
% DefaultVal: default value for the parameter
%
%
% Outputs:
%
% Var: if the parameter already existed, the output matches its original value, otherwise the
% output takes on the specified default value
%
% Example:
%
% clearvars
% ExistingVar = 42;
% ExistingVar = LFDefaultVal( 'ExistingVar', 3 )
% OtherVar = LFDefaultVal( 'OtherVar', 3 )
%
% Results in :
% ExistingVar =
% 42
% OtherVar =
% 3
%
% Usage for setting up default function arguments is demonstrated in most of the LF Toolbox
% functions.
%
% See also: LFDefaultField
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function Var = LFDefaultVal( Var, DefaultVal )
CheckIfExists = sprintf('exist(''%s'', ''var'') && ~isempty(%s)', Var, Var);
VarExists = evalin( 'caller', CheckIfExists );
if( ~VarExists )
Var = DefaultVal;
else
Var = evalin( 'caller', Var );
end
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFDispSetup.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFDispSetup.m
| 2,717 |
utf_8
|
018642a726ed8feb41058f29f9ffeb14
|
% LFDispSetup - helper function used to set up a light field display
%
% Usage:
%
% [ImageHandle, FigureHandle] = LFDispSetup( InitialFrame )
% [ImageHandle, FigureHandle] = LFDispSetup( InitialFrame, ScaleFactor )
%
%
% This sets up a figure for LFDispMousePan and LFDispVidCirc. The figure is configured for
% high-performance display, and subsequent calls will reuse the same figure, rather than creating a
% new window on each call. The function should handle both mono and colour images.
%
%
% Inputs:
%
% InitialFrame : a 2D image with which to start the display
%
% Optional Inputs:
%
% ScaleFactor : Adjusts the size of the display -- 1 means no change, 2 means twice as big, etc.
% Integer values are recommended to avoid scaling artifacts. Note that the scale
% factor is only applied the first time a figure is created -- i.e. the figure
% must be closed to make a change to scale.
%
% Outputs:
%
% FigureHandle, ImageHandle : handles of the created objects
%
%
% See also: LFDispVidCirc, LFDispMousePan
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [ImageHandle, FigureHandle] = LFDispSetup( InitialFrame, ScaleFactor )
FigureHandle = findobj('tag','LFDisplay');
if( isempty(FigureHandle) )
% Get screen size
set( 0, 'units','pixels' );
ScreenSize = get( 0, 'screensize' );
ScreenSize = ScreenSize(3:4);
% Get LF display size
FrameSize = [size(InitialFrame,2),size(InitialFrame,1)];
% Create the figure
FigureHandle = figure(...
'doublebuffer','on',...
'backingstore','off',...
...%'menubar','none',...
...%'toolbar','none',...
'tag','LFDisplay');
% Set the window's position and size
WindowPos = get( FigureHandle, 'Position' );
WindowPos(3:4) = FrameSize;
WindowPos(1:2) = floor( (ScreenSize - FrameSize)./2 );
set( FigureHandle, 'Position', WindowPos );
% Set the axis position and size within the figure
AxesPos = [0,0,size(InitialFrame,2),size(InitialFrame,1)];
axes('units','pixels',...
'Position', AxesPos,...
'xlimmode','manual',...
'ylimmode','manual',...
'zlimmode','manual',...
'climmode','manual',...
'alimmode','manual',...
'layer','bottom');
ImageHandle = imshow(InitialFrame);
% If a scaling factor is requested, apply it
if( exist('ScaleFactor','var') )
truesize(floor(ScaleFactor*size(InitialFrame(:,:,1))));
end
else
ImageHandle = findobj(FigureHandle,'type','image');
set(ImageHandle,'cdata', InitialFrame);
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFGatherCamInfo.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFGatherCamInfo.m
| 2,778 |
utf_8
|
c0acfa7e282c05682ab4f98ab740a59c
|
% LFGatherCamInfo - collect metadata from a folder of processed white images or calibrations
%
% Usage:
%
% CamInfo = LFGatherCamInfo( FilePath, FilenamePattern )
%
%
% This function is designed to work with one of two sources of information: a folder of Lytro white
% images, as extracted from the calibration data using an LFP tool; or a folder of calibrations, as
% generated by LFUtilCalLensletCam.
%
% Inputs:
%
% FilePath is a path to the folder containing either the white images or the calibration files.
%
% FilenamePattern is a pattern, with wildcards, identifying the metadata files to process. Typical
% values are 'CalInfo*.json' for calibration info, and '*T1CALIB__MOD_*.TXT' for white images.
%
% Outputs:
%
% CamInfo is a struct array containing zoom, focus and filename info for each file. Exposure info
% is also included for white images.
%
% See LFUtilProcessCalibrations and LFUtilProcessWhiteImages for example usage.
%
% See also: LFUtilProcessWhiteImages, LFUtilProcessCalibrations
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function CamInfo = LFGatherCamInfo( FilePath, FilenamePattern )
%---Locate all input files---
[FileNames, BasePath] = LFFindFilesRecursive( FilePath, FilenamePattern );
if( isempty(FileNames) )
error('No files found');
end
fprintf('Found :\n');
disp(FileNames)
%---Process each---
fprintf('Filename, Camera Model / Serial, ZoomStep, FocusStep\n');
for( iFile = 1:length(FileNames) )
CurFname = FileNames{iFile};
CurFileInfo = LFReadMetadata( fullfile(BasePath, CurFname) );
CurCamInfo = [];
if( isfield( CurFileInfo, 'CamInfo' ) )
%---Calibration file---
CurCamInfo = CurFileInfo.CamInfo;
elseif( isfield( CurFileInfo, 'master' ) )
%---Lytro TXT metadata file associated with white image---
CurCamInfo.ZoomStep = CurFileInfo.master.picture.frameArray.frame.metadata.devices.lens.zoomStep;
CurCamInfo.FocusStep = CurFileInfo.master.picture.frameArray.frame.metadata.devices.lens.focusStep;
CurCamInfo.ExposureDuration = CurFileInfo.master.picture.frameArray.frame.metadata.devices.shutter.frameExposureDuration;
CurCamInfo.CamSerial = CurFileInfo.master.picture.frameArray.frame.privateMetadata.camera.serialNumber;
CurCamInfo.CamModel = CurFileInfo.master.picture.frameArray.frame.metadata.camera.model;
else
error('Unrecognized file format reading metadata\n');
end
fprintf(' %s :\t%s / %s, %d, %d\n', CurFname, CurCamInfo.CamModel, CurCamInfo.CamSerial, CurCamInfo.ZoomStep, CurCamInfo.FocusStep);
CurCamInfo.Fname = CurFname;
CamInfo(iFile) = CurCamInfo;
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFToolboxVersion.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFToolboxVersion.m
| 252 |
utf_8
|
d37c67edd0424685c2530c25195c3826
|
% LFToolboxVersion - returns a string describing the current toolbox version
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function VersionStr = LFToolboxVersion
VersionStr = 'v0.4 released 12-Feb-2015';
|
github
|
Vincentqyw/light-field-TB-master
|
LFStruct2Var.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFStruct2Var.m
| 871 |
utf_8
|
bd1821a5700012dfce0f79c4d5dd8ab0
|
% LFStruct2Var - Convenience function to break a subset of variables out of a struct
%
% Usage:
% [var1, var2, ...] = LFStruct2Var( StructIn, 'var1', 'var2', ... )
%
% This would ideally exclude the named variables in the argument list, but there was no elegant way
% to do this given the absence of an `outputname' function to match Matlab's `inputname'.
%
% Example:
% FruitCount = struct('Apples', 3, 'Bacon', 42, 'Oranges', 4);
% [Apples, Oranges] = LFStruct2Var( FruitCount, 'Apples', 'Oranges' )
%
% Results in
% Apples =
% 3
% Oranges =
% 4
%
% See also: LFStruct2Var
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function varargout = LFStruct2Var( StructIn, varargin )
for( i=1:length(varargin) )
varargout{i} = StructIn.(varargin{i});
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.