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
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
seperate_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/LPP_TSVM/seperate_eval.m
| 4,612 |
utf_8
|
cdf6ca65b7064dec5676eb185cf0d937
|
function [test_acc] = seperate_eval(name)
addpath([pwd '\lppTSVM']);
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
train = load ([datapath name '\' name '_train_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
test_eval = load ([datapath name '\' name '_test_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% To Evaluate
test_data = test_eval(:,2:end-1);
test_label = test_eval(:,end);
test_lab = test_label; %%% Just replica for further modifying the class label
%%% To Tune
dataX=train(:,2:end-1);
dataY=train(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%% Normalize the evaluation data
norm_ev = repmat(norm_eval,size(test_data,1),1);
test_data=test_data./norm_ev;
%%%% End of normalization of evaluation data
%%%% End of Normalization %%%%
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
%%% For valuation on test data
test_label(test_lab==unique_classes(1),:)=1;
test_label(test_lab==unique_classes(2),:)=-1;
end
try
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
c=c1(i);
kern_para = c5(m);
Predict_Y =lpp_TSVM(DataTrain,test,kern_para,c);
test_accuracy=length(find(Predict_Y==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c=c;
OptPara.kernPara = kern_para;
OptPara.kerntype = 'rbf';
end
% %%% Save all results
% currResult=[FunPara.c1 FunPara.c2 FunPara.c3 FunPara.c4 FunPara.kerfPara.pars test_accuracy];
% Resultall = [Resultall; currResult];
clear Predict_Y;
end
end
%%%% Training and valuation with optimal parameter value
clear DataTrain test;
% DataTrain.A = dataX(dataY==1,:);
% DataTrain.B = dataX(dataY==-1,:);
DataTrain = [dataX dataY];
test = [test_data test_label];
Predict_Y =lpp_TSVM(DataTrain,test,OptPara.kernPara,OptPara.c);
test_acc = length(find(Predict_Y==test_label))/numel(test_label)
OptPara.test_acc = test_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
catch
disp('error in the code');
keyboard
end
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
lpp_TSVM.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/LPP_TSVM/lppTSVM/lpp_TSVM.m
| 6,608 |
utf_8
|
1c7b0a1631142a93c62f585405c02249
|
% ___________________________________________________________________
%
% This is twin SVM Linear programming problem method for nonlinear case.
% The twin SVM formulation is considered and
% its penalty form in its dual is formulated in 1-norm and solved
% using Newton method
% date : Dec 20, 2011
%_____________________________________________________________________
% The formulation is very sensitive to the parameter values. For sinc
% function the following values of the parameters, in general, give
% better results when 200 samples for traiing and 800 samples for testing
% are considered.
function [classifier err] = lpp_TSVM(C,test_data,mew,nu)
[no_input,no_col] = size(C);
% x1 = train(:,1:no_col-1);
obs = C(:,no_col); %Observed values
A = zeros(1,no_col-1);
B = zeros(1,no_col-1);
for i = 1:no_input
if(obs(i) == 1)
A = [A;C(i,1:no_col-1)];
else
B = [B;C(i,1:no_col-1)];
end;
end;
[rowA,n] = size(A);
A = A(2:rowA,:);
[rowB,n] = size(B);
B = B(2:rowB,:) ;
alpha = 1.0; % It works when alpha = 1.0 %
neta = 10^-5;
ep = 0.1; % penality parameter %
tol = 0.01;
itmax = 100;
beta = 10^-3;
% m = no_input
% n = no_col -1
% m2 = 2 * m
[m1,n] = size(A);
e1 = ones(m1,1);
[m2,n] = size(B);
e2 = ones(m2,1);
m= m1 + m2;
I = speye(m);
C = [A ; B];
% [m,n] = size(C);
% C = C(:,1:no_col-1);
K=zeros(m1,m);
for i=1:m1
for j=1:m
nom = norm( A(i,:) - C(j,:) );
K(i,j) = exp( -mew * nom * nom );
end
end
G = [K e1];
size(G);
GT = G';
K=zeros(m2,m);
for i=1:m2
for j=1:m
nom = norm( B(i,:) - C(j,:) );
K(i,j) = exp( -mew * nom * nom );
end
end
H = [K e2];
size(H);
HT = H';
% y = y1;
em1 = m+1;
e = ones(em1,1);
iter = 0;
u1 = ones(m2,1);
v1 = ones(m1,1);
delphi= 1;
% delphi_2 = ones(m,1);
% delta = zeros(m,1);
% i = 0;
while( iter < itmax && norm (delphi) > tol )
iter = iter + 1;
del11 = max( -HT * u1 + GT * v1 - neta * e, 0 );
del12 = max( HT * u1 - GT * v1 - neta * e, 0 );
del13 = max( -v1 - e1, 0 );
del14 = max( v1 - e1, 0 );
del15 = max( u1 - nu * e2, 0 );
delu1 = max( -u1, 0 );
initial_train_time=tic;
delphi_1 = -ep * e2 + H * ( - del11 + del12 ) + del15 - alpha * delu1;
delphi_2 = - del13 + del14 + G * ( del11 - del12 );
xx = diag(sign(del11)) + diag(sign(del12));
H12 = - H * ( xx ) * GT ;
H21 = - G * ( xx ) * HT;
H11 = H * xx * HT + diag(sign(del15)) + alpha * diag(sign(delu1));
H22 = G * xx * GT + diag(sign(del13)) + diag(sign(del14)) ;
hessian = [ [H11 H12]; [H21 H22] ];
delphi = [delphi_1;delphi_2] ;
delta = ( hessian + beta * I ) \ delphi ;
u1 = u1 - delta(1:m2);
v1 = v1 - delta (m2+1:m);
norm(delta);
norm(delphi);
end
iter;
del11 = max( -HT * u1 + GT * v1 - neta * e, 0 );
del12 = max( HT * u1 - GT * v1 - neta * e, 0 );
w1 = ( del11 - del12 );
% _______________________________________________________________________
iter = 0;
u2 = ones(m1,1);
v2 = ones(m2,1);
delphi= 1;
% delphi_2 = ones(m,1);
% delta = zeros(m2,1);
% i = 0;
while( iter < itmax && norm (delphi) > tol )
iter = iter + 1;
del11 = max( GT * u2 + HT * v2- neta * e, 0 );
del12 = max( - GT * u2 - HT * v2 - neta * e, 0 );
del13 = max( - v2 - e2, 0 );
del14 = max( v2 - e2, 0 );
del15 = max( u2 - nu * e1, 0 );
delu2 = max( -u2, 0 );
delphi_1 = - ep * e1 + G * (del11 - del12) + del15 - alpha * delu2;
delphi_2 = - del13 + del14 + H * ( del11 - del12 );
xx = diag(sign(del11)) + diag(sign(del12));
H12 = G * (xx) * HT ;
H21 = H * (xx) * GT;
H11 = G * xx * GT + diag(sign(del15)) + alpha * diag(sign(delu2));
H22 = diag(sign(del13)) + diag(sign(del14)) + H * xx * HT ;
hessian = [ [H11 H12]; [H21 H22] ];
delphi = [delphi_1;delphi_2] ;
delta = ( hessian + beta * I ) \ delphi ;
u2 = u2 - delta(1:m1);
v2 = v2 - delta (m1+1:m);
norm(delta);
norm(delphi);
end
iter;
del11 = max( GT * u2 + HT *v2 - neta * e, 0 );
del12 = max( - GT * u2 - HT * v2 - neta * e, 0 );
w2 = ( del11 - del12 );
time = toc(initial_train_time);
%% ------------------ Testing Part ------------- %%
[no_test,no_col] = size(test_data);
Ker_row =zeros(no_test,no_input);
for i=1:no_test
for j=1:no_input
nom = norm( test_data(i,1:no_col-1) - C(j,:) );
Ker_row(i,j) = exp( -mew * nom * nom );
end
end
K = [Ker_row ones(no_test,1)];
size(K);
y1 = K * w1 / norm(w1);
y2 = K * w2 / norm(w2);
for i = 1 : no_test
if abs(y1(i)) < abs(y2(i))
classifier(i) = 1;
else
classifier(i) = -1;
end;
end;
x1 =[]; x2 =[];
for i=1:no_test
if classifier(i) == 1
x1 = [x1; test_data(i,1:no_col-1)];
else
x2 = [x2; test_data(i,1:no_col-1)];
end
end
%-----------------------------
err = 0.;
classifier = classifier';
obs = test_data(:,no_col);
%[test_size,n] = size(classifier);
for i = 1:no_test
if(classifier(i) ~= obs(i))
err = err+1;
end
end
test_data1 =[];
test_data2 =[];
for i=1:no_test
if obs(i)== 1
test_data1 = [test_data1; test_data(i,1:no_col-1)];
else
test_data2 = [test_data2; test_data(i,1:no_col-1)];
end
end
%% To check the sparseness
count=0;
index=0;
for i= 1:size(w1,1)
if(w1(i)>10^-2 && w2(i)>10^-2)
count=count+1;
index(count)=i;
end
end
% count = 0;
% for i=1:size(w1,1)
% if w1(i) ~=0 & w2(i) ~=0
% count = count+1
% end
% end
% count
%
% count1 = 0;
% for i=1:size(w1,1)
% if w1(i) ~=0
% count1 = count1+1;
% end
% end
%
% count2 = 0;
% for i=1:size(w2,1)
% if w2(i) ~=0
% count2 = count2+1;
% end
% end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
normalize.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/LPP_TSVM/lppTSVM/normalize.m
| 620 |
utf_8
|
b69935e172ec81c7e859090cf1994fed
|
% -----------------------------------------------------------------------
% Time series problem whose input series is given as A matrix, with N
% attributes i.e. A(M:N). Here we normalize the data column-wise so that
% the mean of the series is zero with standard deviation equals to one.
% Input is the two-demensional matrix A(.) and the output is the
% two-dimensional matrix c(.)
% -----------------------------------------------------------------------
function c = normalize(A)
[m,n] = size(A);
e = ones(m,1);
sd = std(A);
c = A - e*mean(A);
c =imdivide(c,e*sd);
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
kfold_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/Improved_LSTWSVM/kfold_eval.m
| 5,220 |
utf_8
|
b5c083945e6ab761c2c080813b9ea530
|
function [mean_acc] = seperate_eval(name)
addpath([pwd '\improved_LSTWSVM'])
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
tot_data = load([datapath name '\' name '_R.dat']);
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% Removing first i.e. indexing column and seperate data and classes
data=tot_data(:,2:end);
dataX=data(:,1:end-1);
dataY=data(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%%%% End of Normalization
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c3 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps1
c4 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps2
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for k=1:length(c3)
% for l=1:length(c4)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.c3=c3(k);
% FunPara.c4=c4(l);
FunPara.c4=c3(k);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =Improved_LSTWSVM(test,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y'==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2; OptPara.c3=FunPara.c3; OptPara.c4=FunPara.c4;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
clear Predict_Y;
end
% end
end
% end
end
%%%% Training and evaluation with optimal parameter value
clear DataTrain trainX trainY testX testY test;
%%%for datasets where training-testing partition is not available, performance vealuation is based on cross-validation.
fold_index = importdata([datapath name '\conxuntos_kfold.dat']);
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(fold_index == 0))>0
fold_index = fold_index + 1;
end
for k=1:size(fold_index,1)
index{k,1}=fold_index(k,~isnan(fold_index(k,:)));
end
for f=1:4
trainX=dataX(index{2*f-1},:);
trainY=dataY(index{2*f-1},:);
testX=dataX(index{2*f},:);
testY=dataY(index{2*f},:);
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
Predict_Y =Improved_LSTWSVM(test,DataTrain,OptPara);
test_acc(f)=length(find(Predict_Y'==testY))/numel(testY);
clear Predict_Y DataTrain trainX trainY testX testY;
end
mean_acc = mean(test_acc)
OptPara.test_acc = mean_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
end
|
github
|
Chandan-IITI/Analysis-of-Twin-SVM-on-44-binary-datasets-master
|
seperate_eval.m
|
.m
|
Analysis-of-Twin-SVM-on-44-binary-datasets-master/Improved_LSTWSVM/seperate_eval.m
| 5,149 |
utf_8
|
a244531f9bbb7bfef82856e1b20c71eb
|
function [test_acc] = seperate_eval(name)
addpath([pwd '\improved_LSTWSVM'])
%%% datasets can be downloaded from "http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz"
datapath = 'provide the path of your dataset';
train = load ([datapath name '\' name '_train_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
index_tune = importdata ([datapath name '\conxuntos.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
test_eval = load ([datapath name '\' name '_test_R.dat']);% for datasets where training-testing partition is available, paramter tuning is based on this file.
%%% Checking whether any index valu is zero or not if zero then increase all index by 1
if length(find(index_tune == 0))>0
index_tune = index_tune + 1;
end
%%% Remove NaN and store in cell
for k=1:size(index_tune,1)
index_sep{k}=index_tune(k,~isnan(index_tune(k,:)));
end
%%% To Evaluate
test_data = test_eval(:,2:end-1);
test_label = test_eval(:,end);
test_lab = test_label; %%% Just replica for further modifying the class label
%%% To Tune
dataX=train(:,2:end-1);
dataY=train(:,end);
dataYY = dataY; %%% Just replica for further modifying the class label
%%%%%% Normalization start
% do normalization for each feature
mean_X=mean(dataX,1);
dataX=dataX-repmat(mean_X,size(dataX,1),1);
norm_X=sum(dataX.^2,1);
norm_X=sqrt(norm_X);
norm_eval = norm_X; %%% Just save fornormalizing the evaluation data
norm_X=repmat(norm_X,size(dataX,1),1);
dataX=dataX./norm_X;
%%%% Normalize the evaluation data
norm_ev = repmat(norm_eval,size(test_data,1),1);
test_data=test_data./norm_ev;
%%%% End of normalization of evaluation data
%%%% End of Normalization %%%%
%%%% Modifying the class label as per TBSVM and chcking whether binaryvclass data or not
unique_classes = unique(dataYY);
if (numel(unique(unique_classes))>2)
error('Data belongs to multi-class, please provide binary class data');
else
dataY(dataYY==unique_classes(1),:)=1;
dataY(dataYY==unique_classes(2),:)=-1;
%%% For valuation on test data
test_label(test_lab==unique_classes(1),:)=1;
test_label(test_lab==unique_classes(2),:)=-1;
end
%%% Seperation of data
%%% To Tune
trainX=dataX(index_sep{1},:);
trainY=dataY(index_sep{1},:);
testX=dataX(index_sep{2},:);
testY=dataY(index_sep{2},:);
%%% If dataset needs in TWSVM/TBSVM format
% DataTrain.A = trainX(trainY==1,:);
% DataTrain.B = trainX(trainY==-1,:);
DataTrain = [trainX trainY];
test = [testX testY];
c1 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c2 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5];
c3 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps1
c4 = [2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5]; %%% Eps2
% c5 = scale_range_rbf(dataX);
c5 = [2^-10,2^-9,2^-8,2^-7,2^-6,2^-5,2^-4,2^-3,2^-2,2^-1,2^0,2^1,2^2,2^3,2^4,2^5,2^6,2^7,2^8,2^9,2^10];
MAX_acc = 0; Resultall = []; count = 0;
for i=1:length(c1)
% for j=1:length(c2)
for k=1:length(c3)
% for l=1:length(c4)
for m=1:length(c5)
count = count +1 %%%% Just displaying the number of iteration
FunPara.c1=c1(i);
% FunPara.c2=c2(j);
FunPara.c2=c1(i);
FunPara.c3=c3(k);
% FunPara.c4=c4(l);
FunPara.c4=c3(k);
FunPara.kerfPara.type = 'rbf';
FunPara.kerfPara.pars = c5(m);
Predict_Y =Improved_LSTWSVM(test,DataTrain,FunPara);
test_accuracy=length(find(Predict_Y'==testY))/numel(testY);
%%%% Save only optimal parameter with testing accuracy
if test_accuracy>MAX_acc; % paramater tuning: we prefer the parameter which lead to better accuracy on the test data.
MAX_acc=test_accuracy;
OptPara.c1=FunPara.c1; OptPara.c2=FunPara.c2; OptPara.c3=FunPara.c3; OptPara.c4=FunPara.c4;
OptPara.kerfPara.type = FunPara.kerfPara.type; OptPara.kerfPara.pars = FunPara.kerfPara.pars;
end
clear Predict_Y;
end
% end
end
% end
end
%%%% Training and valuation with optimal parameter value
clear DataTrain test;
% DataTrain.A = dataX(dataY==1,:);
% DataTrain.B = dataX(dataY==-1,:);
DataTrain = [dataX dataY];
test = [test_data test_label];
Predict_Y =Improved_LSTWSVM(test,DataTrain,OptPara);
test_acc = length(find(Predict_Y'==test_label))/numel(test_label)
OptPara.test_acc = test_acc*100;
filename = ['Res_' name '.mat'];
save (filename, 'OptPara');
end
|
github
|
MouradGridach/Machine-Learning-Stanford-master
|
submit.m
|
.m
|
Machine-Learning-Stanford-master/ex4/submit.m
| 17,129 |
utf_8
|
7e97c75d2b70d978e93fbdb7dfa9d95b
|
function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '4';
end
function [partNames] = validParts()
partNames = { 'Feedforward and Cost Function', ...
'Regularized Cost Function', ...
'Sigmoid Gradient', ...
'Neural Network Gradient (Backpropagation)' ...
'Regularized Gradient' ...
};
end
function srcs = sources()
% Separated by part
srcs = { { 'nnCostFunction.m' }, ...
{ 'nnCostFunction.m' }, ...
{ 'sigmoidGradient.m' }, ...
{ 'nnCostFunction.m' }, ...
{ 'nnCostFunction.m' } };
end
function out = output(partId, auxstring)
% Random Test Cases
X = reshape(3 * sin(1:1:30), 3, 10);
Xm = reshape(sin(1:32), 16, 2) / 5;
ym = 1 + mod(1:16,4)';
t1 = sin(reshape(1:2:24, 4, 3));
t2 = cos(reshape(1:2:40, 4, 5));
t = [t1(:) ; t2(:)];
if partId == 1
[J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0);
out = sprintf('%0.5f ', J);
elseif partId == 2
[J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5);
out = sprintf('%0.5f ', J);
elseif partId == 3
out = sprintf('%0.5f ', sigmoidGradient(X));
elseif partId == 4
[J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0);
out = sprintf('%0.5f ', J);
out = [out sprintf('%0.5f ', grad)];
elseif partId == 5
[J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5);
out = sprintf('%0.5f ', J);
out = [out sprintf('%0.5f ', grad)];
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-003';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github
|
MouradGridach/Machine-Learning-Stanford-master
|
submitWeb.m
|
.m
|
Machine-Learning-Stanford-master/ex4/submitWeb.m
| 827 |
utf_8
|
bfb2fa08cac9d8d797e3071d3fdd7ca1
|
% submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github
|
MouradGridach/Machine-Learning-Stanford-master
|
submit.m
|
.m
|
Machine-Learning-Stanford-master/ex3/Logistic Regression/submit.m
| 17,041 |
utf_8
|
f68fe1ee499ec01df18037b089673b0c
|
function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '3';
end
function [partNames] = validParts()
partNames = { 'Vectorized Logistic Regression ', ...
'One-vs-all classifier training', ...
'One-vs-all classifier prediction', ...
'Neural network prediction function' ...
};
end
function srcs = sources()
% Separated by part
srcs = { { 'lrCostFunction.m' }, ...
{ 'oneVsAll.m' }, ...
{ 'predictOneVsAll.m' }, ...
{ 'predict.m' } };
end
function out = output(partId, auxdata)
% Random Test Cases
X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];
y = sin(X(:,1) + X(:,2)) > 0;
Xm = [ -1 -1 ; -1 -2 ; -2 -1 ; -2 -2 ; ...
1 1 ; 1 2 ; 2 1 ; 2 2 ; ...
-1 1 ; -1 2 ; -2 1 ; -2 2 ; ...
1 -1 ; 1 -2 ; -2 -1 ; -2 -2 ];
ym = [ 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 ]';
t1 = sin(reshape(1:2:24, 4, 3));
t2 = cos(reshape(1:2:40, 4, 5));
if partId == 1
[J, grad] = lrCostFunction([0.25 0.5 -0.5]', X, y, 0.1);
out = sprintf('%0.5f ', J);
out = [out sprintf('%0.5f ', grad)];
elseif partId == 2
out = sprintf('%0.5f ', oneVsAll(Xm, ym, 4, 0.1));
elseif partId == 3
out = sprintf('%0.5f ', predictOneVsAll(t1, Xm));
elseif partId == 4
out = sprintf('%0.5f ', predict(t1, t2, Xm));
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-003';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github
|
MouradGridach/Machine-Learning-Stanford-master
|
submitWeb.m
|
.m
|
Machine-Learning-Stanford-master/ex3/Logistic Regression/submitWeb.m
| 827 |
utf_8
|
bfb2fa08cac9d8d797e3071d3fdd7ca1
|
% submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github
|
MouradGridach/Machine-Learning-Stanford-master
|
submit.m
|
.m
|
Machine-Learning-Stanford-master/ex1/submit.m
| 17,317 |
utf_8
|
d91bc52d795ebec0d8a1667cd9810fea
|
function submit(partId, webSubmit)
%SUBMIT Submit your code and output to the ml-class servers
% SUBMIT() will connect to the ml-class server and submit your solution
fprintf('==\n== [ml-class] Submitting Solutions | Programming Exercise %s\n==\n', ...
homework_id());
if ~exist('partId', 'var') || isempty(partId)
partId = promptPart();
end
if ~exist('webSubmit', 'var') || isempty(webSubmit)
webSubmit = 0; % submit directly by default
end
% Check valid partId
partNames = validParts();
if ~isValidPartId(partId)
fprintf('!! Invalid homework part selected.\n');
fprintf('!! Expected an integer from 1 to %d.\n', numel(partNames) + 1);
fprintf('!! Submission Cancelled\n');
return
end
if ~exist('ml_login_data.mat','file')
[login password] = loginPrompt();
save('ml_login_data.mat','login','password');
else
load('ml_login_data.mat');
[login password] = quickLogin(login, password);
save('ml_login_data.mat','login','password');
end
if isempty(login)
fprintf('!! Submission Cancelled\n');
return
end
fprintf('\n== Connecting to ml-class ... ');
if exist('OCTAVE_VERSION')
fflush(stdout);
end
% Setup submit list
if partId == numel(partNames) + 1
submitParts = 1:numel(partNames);
else
submitParts = [partId];
end
for s = 1:numel(submitParts)
thisPartId = submitParts(s);
if (~webSubmit) % submit directly to server
[login, ch, signature, auxstring] = getChallenge(login, thisPartId);
if isempty(login) || isempty(ch) || isempty(signature)
% Some error occured, error string in first return element.
fprintf('\n!! Error: %s\n\n', login);
return
end
% Attempt Submission with Challenge
ch_resp = challengeResponse(login, password, ch);
[result, str] = submitSolution(login, ch_resp, thisPartId, ...
output(thisPartId, auxstring), source(thisPartId), signature);
partName = partNames{thisPartId};
fprintf('\n== [ml-class] Submitted Assignment %s - Part %d - %s\n', ...
homework_id(), thisPartId, partName);
fprintf('== %s\n', strtrim(str));
if exist('OCTAVE_VERSION')
fflush(stdout);
end
else
[result] = submitSolutionWeb(login, thisPartId, output(thisPartId), ...
source(thisPartId));
result = base64encode(result);
fprintf('\nSave as submission file [submit_ex%s_part%d.txt (enter to accept default)]:', ...
homework_id(), thisPartId);
saveAsFile = input('', 's');
if (isempty(saveAsFile))
saveAsFile = sprintf('submit_ex%s_part%d.txt', homework_id(), thisPartId);
end
fid = fopen(saveAsFile, 'w');
if (fid)
fwrite(fid, result);
fclose(fid);
fprintf('\nSaved your solutions to %s.\n\n', saveAsFile);
fprintf(['You can now submit your solutions through the web \n' ...
'form in the programming exercises. Select the corresponding \n' ...
'programming exercise to access the form.\n']);
else
fprintf('Unable to save to %s\n\n', saveAsFile);
fprintf(['You can create a submission file by saving the \n' ...
'following text in a file: (press enter to continue)\n\n']);
pause;
fprintf(result);
end
end
end
end
% ================== CONFIGURABLES FOR EACH HOMEWORK ==================
function id = homework_id()
id = '1';
end
function [partNames] = validParts()
partNames = { 'Warm up exercise ', ...
'Computing Cost (for one variable)', ...
'Gradient Descent (for one variable)', ...
'Feature Normalization', ...
'Computing Cost (for multiple variables)', ...
'Gradient Descent (for multiple variables)', ...
'Normal Equations'};
end
function srcs = sources()
% Separated by part
srcs = { { 'warmUpExercise.m' }, ...
{ 'computeCost.m' }, ...
{ 'gradientDescent.m' }, ...
{ 'featureNormalize.m' }, ...
{ 'computeCostMulti.m' }, ...
{ 'gradientDescentMulti.m' }, ...
{ 'normalEqn.m' }, ...
};
end
function out = output(partId, auxstring)
% Random Test Cases
X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))'];
Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2));
X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25];
Y2 = Y1.^0.5 + Y1;
if partId == 1
out = sprintf('%0.5f ', warmUpExercise());
elseif partId == 2
out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]'));
elseif partId == 3
out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10));
elseif partId == 4
out = sprintf('%0.5f ', featureNormalize(X2(:,2:4)));
elseif partId == 5
out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]'));
elseif partId == 6
out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10));
elseif partId == 7
out = sprintf('%0.5f ', normalEqn(X2, Y2));
end
end
% ====================== SERVER CONFIGURATION ===========================
% ***************** REMOVE -staging WHEN YOU DEPLOY *********************
function url = site_url()
url = 'http://class.coursera.org/ml-006';
end
function url = challenge_url()
url = [site_url() '/assignment/challenge'];
end
function url = submit_url()
url = [site_url() '/assignment/submit'];
end
% ========================= CHALLENGE HELPERS =========================
function src = source(partId)
src = '';
src_files = sources();
if partId <= numel(src_files)
flist = src_files{partId};
for i = 1:numel(flist)
fid = fopen(flist{i});
if (fid == -1)
error('Error opening %s (is it missing?)', flist{i});
end
line = fgets(fid);
while ischar(line)
src = [src line];
line = fgets(fid);
end
fclose(fid);
src = [src '||||||||'];
end
end
end
function ret = isValidPartId(partId)
partNames = validParts();
ret = (~isempty(partId)) && (partId >= 1) && (partId <= numel(partNames) + 1);
end
function partId = promptPart()
fprintf('== Select which part(s) to submit:\n');
partNames = validParts();
srcFiles = sources();
for i = 1:numel(partNames)
fprintf('== %d) %s [', i, partNames{i});
fprintf(' %s ', srcFiles{i}{:});
fprintf(']\n');
end
fprintf('== %d) All of the above \n==\nEnter your choice [1-%d]: ', ...
numel(partNames) + 1, numel(partNames) + 1);
selPart = input('', 's');
partId = str2num(selPart);
if ~isValidPartId(partId)
partId = -1;
end
end
function [email,ch,signature,auxstring] = getChallenge(email, part)
str = urlread(challenge_url(), 'post', {'email_address', email, 'assignment_part_sid', [homework_id() '-' num2str(part)], 'response_encoding', 'delim'});
str = strtrim(str);
r = struct;
while(numel(str) > 0)
[f, str] = strtok (str, '|');
[v, str] = strtok (str, '|');
r = setfield(r, f, v);
end
email = getfield(r, 'email_address');
ch = getfield(r, 'challenge_key');
signature = getfield(r, 'state');
auxstring = getfield(r, 'challenge_aux_data');
end
function [result, str] = submitSolutionWeb(email, part, output, source)
result = ['{"assignment_part_sid":"' base64encode([homework_id() '-' num2str(part)], '') '",' ...
'"email_address":"' base64encode(email, '') '",' ...
'"submission":"' base64encode(output, '') '",' ...
'"submission_aux":"' base64encode(source, '') '"' ...
'}'];
str = 'Web-submission';
end
function [result, str] = submitSolution(email, ch_resp, part, output, ...
source, signature)
params = {'assignment_part_sid', [homework_id() '-' num2str(part)], ...
'email_address', email, ...
'submission', base64encode(output, ''), ...
'submission_aux', base64encode(source, ''), ...
'challenge_response', ch_resp, ...
'state', signature};
str = urlread(submit_url(), 'post', params);
% Parse str to read for success / failure
result = 0;
end
% =========================== LOGIN HELPERS ===========================
function [login password] = loginPrompt()
% Prompt for password
[login password] = basicPrompt();
if isempty(login) || isempty(password)
login = []; password = [];
end
end
function [login password] = basicPrompt()
login = input('Login (Email address): ', 's');
password = input('Password: ', 's');
end
function [login password] = quickLogin(login,password)
disp(['You are currently logged in as ' login '.']);
cont_token = input('Is this you? (y/n - type n to reenter password)','s');
if(isempty(cont_token) || cont_token(1)=='Y'||cont_token(1)=='y')
return;
else
[login password] = loginPrompt();
end
end
function [str] = challengeResponse(email, passwd, challenge)
str = sha1([challenge passwd]);
end
% =============================== SHA-1 ================================
function hash = sha1(str)
% Initialize variables
h0 = uint32(1732584193);
h1 = uint32(4023233417);
h2 = uint32(2562383102);
h3 = uint32(271733878);
h4 = uint32(3285377520);
% Convert to word array
strlen = numel(str);
% Break string into chars and append the bit 1 to the message
mC = [double(str) 128];
mC = [mC zeros(1, 4-mod(numel(mC), 4), 'uint8')];
numB = strlen * 8;
if exist('idivide')
numC = idivide(uint32(numB + 65), 512, 'ceil');
else
numC = ceil(double(numB + 65)/512);
end
numW = numC * 16;
mW = zeros(numW, 1, 'uint32');
idx = 1;
for i = 1:4:strlen + 1
mW(idx) = bitor(bitor(bitor( ...
bitshift(uint32(mC(i)), 24), ...
bitshift(uint32(mC(i+1)), 16)), ...
bitshift(uint32(mC(i+2)), 8)), ...
uint32(mC(i+3)));
idx = idx + 1;
end
% Append length of message
mW(numW - 1) = uint32(bitshift(uint64(numB), -32));
mW(numW) = uint32(bitshift(bitshift(uint64(numB), 32), -32));
% Process the message in successive 512-bit chs
for cId = 1 : double(numC)
cSt = (cId - 1) * 16 + 1;
cEnd = cId * 16;
ch = mW(cSt : cEnd);
% Extend the sixteen 32-bit words into eighty 32-bit words
for j = 17 : 80
ch(j) = ch(j - 3);
ch(j) = bitxor(ch(j), ch(j - 8));
ch(j) = bitxor(ch(j), ch(j - 14));
ch(j) = bitxor(ch(j), ch(j - 16));
ch(j) = bitrotate(ch(j), 1);
end
% Initialize hash value for this ch
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
% Main loop
for i = 1 : 80
if(i >= 1 && i <= 20)
f = bitor(bitand(b, c), bitand(bitcmp(b), d));
k = uint32(1518500249);
elseif(i >= 21 && i <= 40)
f = bitxor(bitxor(b, c), d);
k = uint32(1859775393);
elseif(i >= 41 && i <= 60)
f = bitor(bitor(bitand(b, c), bitand(b, d)), bitand(c, d));
k = uint32(2400959708);
elseif(i >= 61 && i <= 80)
f = bitxor(bitxor(b, c), d);
k = uint32(3395469782);
end
t = bitrotate(a, 5);
t = bitadd(t, f);
t = bitadd(t, e);
t = bitadd(t, k);
t = bitadd(t, ch(i));
e = d;
d = c;
c = bitrotate(b, 30);
b = a;
a = t;
end
h0 = bitadd(h0, a);
h1 = bitadd(h1, b);
h2 = bitadd(h2, c);
h3 = bitadd(h3, d);
h4 = bitadd(h4, e);
end
hash = reshape(dec2hex(double([h0 h1 h2 h3 h4]), 8)', [1 40]);
hash = lower(hash);
end
function ret = bitadd(iA, iB)
ret = double(iA) + double(iB);
ret = bitset(ret, 33, 0);
ret = uint32(ret);
end
function ret = bitrotate(iA, places)
t = bitshift(iA, places - 32);
ret = bitshift(iA, places);
ret = bitor(ret, t);
end
% =========================== Base64 Encoder ============================
% Thanks to Peter John Acklam
%
function y = base64encode(x, eol)
%BASE64ENCODE Perform base64 encoding on a string.
%
% BASE64ENCODE(STR, EOL) encode the given string STR. EOL is the line ending
% sequence to use; it is optional and defaults to '\n' (ASCII decimal 10).
% The returned encoded string is broken into lines of no more than 76
% characters each, and each line will end with EOL unless it is empty. Let
% EOL be empty if you do not want the encoded string broken into lines.
%
% STR and EOL don't have to be strings (i.e., char arrays). The only
% requirement is that they are vectors containing values in the range 0-255.
%
% This function may be used to encode strings into the Base64 encoding
% specified in RFC 2045 - MIME (Multipurpose Internet Mail Extensions). The
% Base64 encoding is designed to represent arbitrary sequences of octets in a
% form that need not be humanly readable. A 65-character subset
% ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per
% printable character.
%
% Examples
% --------
%
% If you want to encode a large file, you should encode it in chunks that are
% a multiple of 57 bytes. This ensures that the base64 lines line up and
% that you do not end up with padding in the middle. 57 bytes of data fills
% one complete base64 line (76 == 57*4/3):
%
% If ifid and ofid are two file identifiers opened for reading and writing,
% respectively, then you can base64 encode the data with
%
% while ~feof(ifid)
% fwrite(ofid, base64encode(fread(ifid, 60*57)));
% end
%
% or, if you have enough memory,
%
% fwrite(ofid, base64encode(fread(ifid)));
%
% See also BASE64DECODE.
% Author: Peter John Acklam
% Time-stamp: 2004-02-03 21:36:56 +0100
% E-mail: [email protected]
% URL: http://home.online.no/~pjacklam
if isnumeric(x)
x = num2str(x);
end
% make sure we have the EOL value
if nargin < 2
eol = sprintf('\n');
else
if sum(size(eol) > 1) > 1
error('EOL must be a vector.');
end
if any(eol(:) > 255)
error('EOL can not contain values larger than 255.');
end
end
if sum(size(x) > 1) > 1
error('STR must be a vector.');
end
x = uint8(x);
eol = uint8(eol);
ndbytes = length(x); % number of decoded bytes
nchunks = ceil(ndbytes / 3); % number of chunks/groups
nebytes = 4 * nchunks; % number of encoded bytes
% add padding if necessary, to make the length of x a multiple of 3
if rem(ndbytes, 3)
x(end+1 : 3*nchunks) = 0;
end
x = reshape(x, [3, nchunks]); % reshape the data
y = repmat(uint8(0), 4, nchunks); % for the encoded data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Split up every 3 bytes into 4 pieces
%
% aaaaaabb bbbbcccc ccdddddd
%
% to form
%
% 00aaaaaa 00bbbbbb 00cccccc 00dddddd
%
y(1,:) = bitshift(x(1,:), -2); % 6 highest bits of x(1,:)
y(2,:) = bitshift(bitand(x(1,:), 3), 4); % 2 lowest bits of x(1,:)
y(2,:) = bitor(y(2,:), bitshift(x(2,:), -4)); % 4 highest bits of x(2,:)
y(3,:) = bitshift(bitand(x(2,:), 15), 2); % 4 lowest bits of x(2,:)
y(3,:) = bitor(y(3,:), bitshift(x(3,:), -6)); % 2 highest bits of x(3,:)
y(4,:) = bitand(x(3,:), 63); % 6 lowest bits of x(3,:)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now perform the following mapping
%
% 0 - 25 -> A-Z
% 26 - 51 -> a-z
% 52 - 61 -> 0-9
% 62 -> +
% 63 -> /
%
% We could use a mapping vector like
%
% ['A':'Z', 'a':'z', '0':'9', '+/']
%
% but that would require an index vector of class double.
%
z = repmat(uint8(0), size(y));
i = y <= 25; z(i) = 'A' + double(y(i));
i = 26 <= y & y <= 51; z(i) = 'a' - 26 + double(y(i));
i = 52 <= y & y <= 61; z(i) = '0' - 52 + double(y(i));
i = y == 62; z(i) = '+';
i = y == 63; z(i) = '/';
y = z;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add padding if necessary.
%
npbytes = 3 * nchunks - ndbytes; % number of padding bytes
if npbytes
y(end-npbytes+1 : end) = '='; % '=' is used for padding
end
if isempty(eol)
% reshape to a row vector
y = reshape(y, [1, nebytes]);
else
nlines = ceil(nebytes / 76); % number of lines
neolbytes = length(eol); % number of bytes in eol string
% pad data so it becomes a multiple of 76 elements
y = [y(:) ; zeros(76 * nlines - numel(y), 1)];
y(nebytes + 1 : 76 * nlines) = 0;
y = reshape(y, 76, nlines);
% insert eol strings
eol = eol(:);
y(end + 1 : end + neolbytes, :) = eol(:, ones(1, nlines));
% remove padding, but keep the last eol string
m = nebytes + neolbytes * (nlines - 1);
n = (76+neolbytes)*nlines - neolbytes;
y(m+1 : n) = '';
% extract and reshape to row vector
y = reshape(y, 1, m+neolbytes);
end
% output is a character array
y = char(y);
end
|
github
|
MouradGridach/Machine-Learning-Stanford-master
|
submitWeb.m
|
.m
|
Machine-Learning-Stanford-master/ex1/submitWeb.m
| 827 |
utf_8
|
bfb2fa08cac9d8d797e3071d3fdd7ca1
|
% submitWeb Creates files from your code and output for web submission.
%
% If the submit function does not work for you, use the web-submission mechanism.
% Call this function to produce a file for the part you wish to submit. Then,
% submit the file to the class servers using the "Web Submission" button on the
% Programming Exercises page on the course website.
%
% You should call this function without arguments (submitWeb), to receive
% an interactive prompt for submission; optionally you can call it with the partID
% if you so wish. Make sure your working directory is set to the directory
% containing the submitWeb.m file and your assignment files.
function submitWeb(partId)
if ~exist('partId', 'var') || isempty(partId)
partId = [];
end
submit(partId, 1);
end
|
github
|
xiaohuige1/udn_extend-master
|
fast_rcnn_get_minibatch.m
|
.m
|
udn_extend-master/functions/fast_rcnn/fast_rcnn_get_minibatch.m
| 6,754 |
utf_8
|
78226ab5c4a79dab0d13aac70792d9b6
|
function [im_blob, rois_blob, labels_blob, bbox_targets_blob, bbox_loss_blob] = fast_rcnn_get_minibatch(conf, image_roidb)
% [im_blob, rois_blob, labels_blob, bbox_targets_blob, bbox_loss_blob] ...
% = fast_rcnn_get_minibatch(conf, image_roidb)
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
num_images = length(image_roidb);
% Infer number of classes from the number of columns in gt_overlaps
num_classes = size(image_roidb(1).overlap, 2);
% Sample random scales to use for each image in this batch
random_scale_inds = randi(length(conf.scales), num_images, 1);
assert(mod(conf.batch_size, num_images) == 0, ...
sprintf('num_images %d must divide BATCH_SIZE %d', num_images, conf.batch_size));
rois_per_image = conf.batch_size / num_images;
fg_rois_per_image = round(rois_per_image * conf.fg_fraction);
% Get the input image blob
[im_blob, im_scales] = get_image_blob(conf, image_roidb, random_scale_inds);
% build the region of interest and label blobs
rois_blob = zeros(0, 5, 'single');
labels_blob = zeros(0, 1, 'single');
bbox_targets_blob = zeros(0, 4 * (num_classes+1), 'single');
bbox_loss_blob = zeros(size(bbox_targets_blob), 'single');
for i = 1:num_images
[labels, ~, im_rois, bbox_targets, bbox_loss] = ...
sample_rois(conf, image_roidb(i), fg_rois_per_image, rois_per_image);
% Add to ROIs blob
feat_rois = fast_rcnn_map_im_rois_to_feat_rois(conf, im_rois, im_scales(i));
batch_ind = i * ones(size(feat_rois, 1), 1);
rois_blob_this_image = [batch_ind, feat_rois];
rois_blob = [rois_blob; rois_blob_this_image];
% Add to labels, bbox targets, and bbox loss blobs
labels_blob = [labels_blob; labels];
bbox_targets_blob = [bbox_targets_blob; bbox_targets];
bbox_loss_blob = [bbox_loss_blob; bbox_loss];
end
% permute data into caffe c++ memory, thus [num, channels, height, width]
im_blob = im_blob(:, :, [3, 2, 1], :); % from rgb to brg
im_blob = single(permute(im_blob, [2, 1, 3, 4]));
rois_blob = rois_blob - 1; % to c's index (start from 0)
rois_blob = single(permute(rois_blob, [3, 4, 2, 1]));
labels_blob = single(permute(labels_blob, [3, 4, 2, 1]));
bbox_targets_blob = single(permute(bbox_targets_blob, [3, 4, 2, 1]));
bbox_loss_blob = single(permute(bbox_loss_blob, [3, 4, 2, 1]));
assert(~isempty(im_blob));
assert(~isempty(rois_blob));
assert(~isempty(labels_blob));
assert(~isempty(bbox_targets_blob));
assert(~isempty(bbox_loss_blob));
end
%% Build an input blob from the images in the roidb at the specified scales.
function [im_blob, im_scales] = get_image_blob(conf, images, random_scale_inds)
num_images = length(images);
processed_ims = cell(num_images, 1);
im_scales = nan(num_images, 1);
for i = 1:num_images
im = imread(images(i).image_path);
target_size = conf.scales(random_scale_inds(i));
[im, im_scale] = prep_im_for_blob(im, conf.image_means, target_size, conf.max_size);
im_scales(i) = im_scale;
processed_ims{i} = im;
end
im_blob = im_list_to_blob(processed_ims);
end
%% Generate a random sample of ROIs comprising foreground and background examples.
function [labels, overlaps, rois, bbox_targets, bbox_loss_weights] = ...
sample_rois(conf, image_roidb, fg_rois_per_image, rois_per_image)
[overlaps, labels] = max(image_roidb(1).overlap, [], 2);
gt_ignores = image_roidb.ignores;
labels(find(gt_ignores==1)) = 0;
overlaps(find(gt_ignores==1)) = -1;
% labels = image_roidb(1).max_classes;
% overlaps = image_roidb(1).max_overlaps;
rois = image_roidb(1).boxes;
% Select foreground ROIs as those with >= FG_THRESH overlap
fg_inds = find(overlaps >= conf.fg_thresh);
% Guard against the case when an image has fewer than fg_rois_per_image
% foreground ROIs
fg_rois_per_this_image = min(fg_rois_per_image, length(fg_inds));
% Sample foreground regions without replacement
if ~isempty(fg_inds)
fg_inds = fg_inds(randperm(length(fg_inds), fg_rois_per_this_image));
end
% Select background ROIs as those within [BG_THRESH_LO, BG_THRESH_HI)
bg_inds = find(overlaps < conf.bg_thresh_hi & overlaps >= conf.bg_thresh_lo);
% Compute number of background ROIs to take from this image (guarding
% against there being fewer than desired)
bg_rois_per_this_image = rois_per_image - fg_rois_per_this_image;
bg_rois_per_this_image = min(bg_rois_per_this_image, length(bg_inds));
% Sample foreground regions without replacement
if ~isempty(bg_inds)
bg_inds = bg_inds(randperm(length(bg_inds), bg_rois_per_this_image));
end
% The indices that we're selecting (both fg and bg)
keep_inds = [fg_inds; bg_inds];
% Select sampled values from various arrays
labels = labels(keep_inds);
% Clamp labels for the background ROIs to 0
labels((fg_rois_per_this_image+1):end) = 0;
overlaps = overlaps(keep_inds);
rois = rois(keep_inds, :);
assert(all(labels == image_roidb.bbox_targets(keep_inds, 1)));
% Infer number of classes from the number of columns in gt_overlaps
num_classes = size(image_roidb(1).overlap, 2);
[bbox_targets, bbox_loss_weights] = get_bbox_regression_labels(conf, ...
image_roidb.bbox_targets(keep_inds, :), num_classes);
end
function [bbox_targets, bbox_loss_weights] = get_bbox_regression_labels(conf, bbox_target_data, num_classes)
%% Bounding-box regression targets are stored in a compact form in the roidb.
% This function expands those targets into the 4-of-4*(num_classes+1) representation used
% by the network (i.e. only one class has non-zero targets).
% The loss weights are similarly expanded.
% Return (N, (num_classes+1) * 4, 1, 1) blob of regression targets
% Return (N, (num_classes+1 * 4, 1, 1) blob of loss weights
clss = bbox_target_data(:, 1);
bbox_targets = zeros(length(clss), 4 * (num_classes+1), 'single');
bbox_loss_weights = zeros(size(bbox_targets), 'single');
inds = find(clss > 0);
for i = 1:length(inds)
ind = inds(i);
cls = clss(ind);
targets_inds = (1+cls*4):((cls+1)*4);
bbox_targets(ind, targets_inds) = bbox_target_data(ind, 2:end);
bbox_loss_weights(ind, targets_inds) = 1;
end
end
|
github
|
xiaohuige1/udn_extend-master
|
fast_rcnn_conv_feat_detect.m
|
.m
|
udn_extend-master/functions/fast_rcnn/fast_rcnn_conv_feat_detect.m
| 4,211 |
utf_8
|
7757435a0286baaedd67b1aa30c1f523
|
function [pred_boxes, scores] = fast_rcnn_conv_feat_detect(conf, caffe_net, im, conv_feat_blob, boxes, max_rois_num_in_gpu)
% [pred_boxes, scores] = fast_rcnn_conv_feat_detect(conf, caffe_net, im, conv_feat_blob, boxes, max_rois_num_in_gpu)
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
[rois_blob, ~] = get_blobs(conf, im, boxes);
% permute data into caffe c++ memory, thus [num, channels, height, width]
rois_blob = rois_blob - 1; % to c's index (start from 0)
rois_blob = permute(rois_blob, [3, 4, 2, 1]);
rois_blob = single(rois_blob);
% set conv feature map as 'data'
caffe_net.blobs('data').copy_data_from(conv_feat_blob);
total_rois = size(rois_blob, 4);
total_scores = cell(ceil(total_rois / max_rois_num_in_gpu), 1);
total_box_deltas = cell(ceil(total_rois / max_rois_num_in_gpu), 1);
for i = 1:ceil(total_rois / max_rois_num_in_gpu)
sub_ind_start = 1 + (i-1) * max_rois_num_in_gpu;
sub_ind_end = min(total_rois, i * max_rois_num_in_gpu);
sub_rois_blob = rois_blob(:, :, :, sub_ind_start:sub_ind_end);
% only set rois blob here
net_inputs = {[], sub_rois_blob};
% Reshape net's input blobs
caffe_net.reshape_as_input(net_inputs);
output_blobs = caffe_net.forward(net_inputs);
if conf.test_binary
% simulate binary logistic regression
scores = caffe_net.blobs('cls_score').get_data();
scores = squeeze(scores)';
% Return scores as fg - bg
scores = bsxfun(@minus, scores, scores(:, 1));
else
% use softmax estimated probabilities
scores = output_blobs{2};
scores = squeeze(scores)';
end
% Apply bounding-box regression deltas
box_deltas = output_blobs{1};
box_deltas = squeeze(box_deltas)';
total_scores{i} = scores;
total_box_deltas{i} = box_deltas;
end
scores = cell2mat(total_scores);
box_deltas = cell2mat(total_box_deltas);
pred_boxes = fast_rcnn_bbox_transform_inv(boxes, box_deltas);
pred_boxes = clip_boxes(pred_boxes, size(im, 2), size(im, 1));
% remove scores and boxes for back-ground
pred_boxes = pred_boxes(:, 5:end);
scores = scores(:, 2:end);
end
function [rois_blob, im_scale_factors] = get_blobs(conf, im, rois)
im_scale_factors = get_image_blob_scales(conf, im);
rois_blob = get_rois_blob(conf, rois, im_scale_factors);
end
function im_scales = get_image_blob_scales(conf, im)
im_scales = arrayfun(@(x) prep_im_for_blob_size(size(im), x, conf.test_max_size), conf.test_scales, 'UniformOutput', false);
im_scales = cell2mat(im_scales);
end
function [rois_blob] = get_rois_blob(conf, im_rois, im_scale_factors)
[feat_rois, levels] = map_im_rois_to_feat_rois(conf, im_rois, im_scale_factors);
rois_blob = single([levels, feat_rois]);
end
function [feat_rois, levels] = map_im_rois_to_feat_rois(conf, im_rois, scales)
im_rois = single(im_rois);
if length(scales) > 1
widths = im_rois(:, 3) - im_rois(:, 1) + 1;
heights = im_rois(:, 4) - im_rois(:, 2) + 1;
areas = widths .* heights;
scaled_areas = bsxfun(@times, areas(:), scales(:)'.^2);
levels = max(abs(scaled_areas - 224.^2), 2);
else
levels = ones(size(im_rois, 1), 1);
end
feat_rois = round(bsxfun(@times, im_rois-1, scales(levels))) + 1;
end
function boxes = clip_boxes(boxes, im_width, im_height)
% x1 >= 1 & <= im_width
boxes(:, 1:4:end) = max(min(boxes(:, 1:4:end), im_width), 1);
% y1 >= 1 & <= im_height
boxes(:, 2:4:end) = max(min(boxes(:, 2:4:end), im_height), 1);
% x2 >= 1 & <= im_width
boxes(:, 3:4:end) = max(min(boxes(:, 3:4:end), im_width), 1);
% y2 >= 1 & <= im_height
boxes(:, 4:4:end) = max(min(boxes(:, 4:4:end), im_height), 1);
end
|
github
|
xiaohuige1/udn_extend-master
|
fast_rcnn_im_detect_our.m
|
.m
|
udn_extend-master/functions/fast_rcnn/fast_rcnn_im_detect_our.m
| 4,807 |
utf_8
|
dcac6458c08d769832bb3ca5be673b93
|
function [pred_boxes, scores] = fast_rcnn_im_detect_our(conf, caffe_net, im, boxes, max_rois_num_in_gpu)
% [pred_boxes, scores] = fast_rcnn_im_detect(conf, caffe_net, im, boxes, max_rois_num_in_gpu)
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
[im_blob, rois_blob, ~] = get_blobs(conf, im, boxes);
% When mapping from image ROIs to feature map ROIs, there's some aliasing
% (some distinct image ROIs get mapped to the same feature ROI).
% Here, we identify duplicate feature ROIs, so we only compute features
% on the unique subset.
[~, index, inv_index] = unique(rois_blob, 'rows');
rois_blob = rois_blob(index, :);
boxes = boxes(index, :);
% permute data into caffe c++ memory, thus [num, channels, height, width]
im_blob = im_blob(:, :, [3, 2, 1], :); % from rgb to brg
im_blob = permute(im_blob, [2, 1, 3, 4]);
im_blob = single(im_blob);
rois_blob = rois_blob - 1; % to c's index (start from 0)
rois_blob = permute(rois_blob, [3, 4, 2, 1]);
rois_blob = single(rois_blob);
total_rois = size(rois_blob, 4);
total_scores = cell(ceil(total_rois / max_rois_num_in_gpu), 1);
total_box_deltas = cell(ceil(total_rois / max_rois_num_in_gpu), 1);
for i = 1:ceil(total_rois / max_rois_num_in_gpu)
sub_ind_start = 1 + (i-1) * max_rois_num_in_gpu;
sub_ind_end = min(total_rois, i * max_rois_num_in_gpu);
sub_rois_blob = rois_blob(:, :, :, sub_ind_start:sub_ind_end);
net_inputs = {im_blob, sub_rois_blob};
% Reshape net's input blobs
caffe_net.reshape_as_input(net_inputs);
output_blobs = caffe_net.forward(net_inputs);
if conf.test_binary
% simulate binary logistic regression
scores = caffe_net.blobs('cls_score').get_data();
scores = squeeze(scores)';
% Return scores as fg - bg
scores = bsxfun(@minus, scores, scores(:, 1));
else
% use softmax estimated probabilities
scores = output_blobs{1};
scores = squeeze(scores)';
end
% Apply bounding-box regression deltas
% box_deltas = output_blobs{1};
% box_deltas = squeeze(box_deltas)';
total_scores{i} = scores;
% total_box_deltas{i} = box_deltas;
end
scores = cell2mat(total_scores);
% box_deltas = cell2mat(total_box_deltas);
%
pred_boxes = boxes; %fast_rcnn_bbox_transform_inv(boxes, box_deltas);
% pred_boxes = clip_boxes(pred_boxes, size(im, 2), size(im, 1));
% Map scores and predictions back to the original set of boxes
scores = scores(inv_index, :);
pred_boxes = pred_boxes(inv_index, :);
% remove scores and boxes for back-ground
% pred_boxes = pred_boxes(:, 5:end);
scores = scores(:, 2:end);
end
function [data_blob, rois_blob, im_scale_factors] = get_blobs(conf, im, rois)
[data_blob, im_scale_factors] = get_image_blob(conf, im);
rois_blob = get_rois_blob(conf, rois, im_scale_factors);
end
function [blob, im_scales] = get_image_blob(conf, im)
[ims, im_scales] = arrayfun(@(x) prep_im_for_blob(im, conf.image_means, x, conf.test_max_size), conf.test_scales, 'UniformOutput', false);
im_scales = cell2mat(im_scales);
blob = im_list_to_blob(ims);
end
function [rois_blob] = get_rois_blob(conf, im_rois, im_scale_factors)
[feat_rois, levels] = map_im_rois_to_feat_rois(conf, im_rois, im_scale_factors);
rois_blob = single([levels, feat_rois]);
end
function [feat_rois, levels] = map_im_rois_to_feat_rois(conf, im_rois, scales)
im_rois = single(im_rois);
if length(scales) > 1
widths = im_rois(:, 3) - im_rois(:, 1) + 1;
heights = im_rois(:, 4) - im_rois(:, 2) + 1;
areas = widths .* heights;
scaled_areas = bsxfun(@times, areas(:), scales(:)'.^2);
[~, levels] = min(abs(scaled_areas - 224.^2), [], 2);
else
levels = ones(size(im_rois, 1), 1);
end
feat_rois = round(bsxfun(@times, im_rois-1, scales(levels))) + 1;
end
function boxes = clip_boxes(boxes, im_width, im_height)
% x1 >= 1 & <= im_width
boxes(:, 1:4:end) = max(min(boxes(:, 1:4:end), im_width), 1);
% y1 >= 1 & <= im_height
boxes(:, 2:4:end) = max(min(boxes(:, 2:4:end), im_height), 1);
% x2 >= 1 & <= im_width
boxes(:, 3:4:end) = max(min(boxes(:, 3:4:end), im_width), 1);
% y2 >= 1 & <= im_height
boxes(:, 4:4:end) = max(min(boxes(:, 4:4:end), im_height), 1);
end
|
github
|
xiaohuige1/udn_extend-master
|
fast_rcnn_train.m
|
.m
|
udn_extend-master/functions/fast_rcnn/fast_rcnn_train.m
| 9,725 |
utf_8
|
c003ebd57a0c1417b4bbd979092a88b2
|
function save_model_path = fast_rcnn_train(conf, imdb_train, roidb_train, varargin)
% save_model_path = fast_rcnn_train(conf, imdb_train, roidb_train, varargin)
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
%% inputs
ip = inputParser;
ip.addRequired('conf', @isstruct);
ip.addRequired('imdb_train', @iscell);
ip.addRequired('roidb_train', @iscell);
ip.addParamValue('do_val', false, @isscalar);
ip.addParamValue('imdb_val', struct(), @isstruct);
ip.addParamValue('roidb_val', struct(), @isstruct);
ip.addParamValue('val_iters', 500, @isscalar);
ip.addParamValue('val_interval', 2000, @isscalar);
ip.addParamValue('snapshot_interval',...
10000, @isscalar);
ip.addParamValue('solver_def_file', fullfile(pwd, 'models', 'Zeiler_conv5', 'solver.prototxt'), ...
@isstr);
ip.addParamValue('net_file', fullfile(pwd, 'models', 'Zeiler_conv5', 'Zeiler_conv5'), ...
@isstr);
ip.addParamValue('cache_name', 'Zeiler_conv5', ...
@isstr);
ip.parse(conf, imdb_train, roidb_train, varargin{:});
opts = ip.Results;
%% try to find trained model
imdbs_name = cell2mat(cellfun(@(x) x.name, imdb_train, 'UniformOutput', false));
cache_dir = fullfile(pwd, 'output', 'fast_rcnn_cachedir', opts.cache_name, imdbs_name);
save_model_path = fullfile(cache_dir, 'final');
if exist(save_model_path, 'file')
return;
end
%% init
% init caffe solver
mkdir_if_missing(cache_dir);
caffe_log_file_base = fullfile(cache_dir, 'caffe_log');
caffe.init_log(caffe_log_file_base);
caffe_solver = caffe.Solver(opts.solver_def_file);
caffe_solver.net.copy_from(opts.net_file);
% init log
timestamp = datestr(datevec(now()), 'yyyymmdd_HHMMSS');
mkdir_if_missing(fullfile(cache_dir, 'log'));
log_file = fullfile(cache_dir, 'log', ['train_', timestamp, '.txt']);
diary(log_file);
% set random seed
prev_rng = seed_rand(conf.rng_seed);
caffe.set_random_seed(conf.rng_seed);
% set gpu/cpu
if conf.use_gpu
caffe.set_mode_gpu();
else
caffe.set_mode_cpu();
end
disp('conf:');
disp(conf);
disp('opts:');
disp(opts);
%% making tran/val data
fprintf('Preparing training data...');
[image_roidb_train, bbox_means, bbox_stds]...
= fast_rcnn_prepare_image_roidb(conf, opts.imdb_train, opts.roidb_train);
fprintf('Done.\n');
%% try to train/val with images which have maximum size potentially, to validate whether the gpu memory is enough
% num_classes = size(image_roidb_train(1).overlap, 2);
% check_gpu_memory(conf, caffe_solver, num_classes, opts.do_val);
%% training
shuffled_inds = [];
train_results = [];
val_results = [];
iter_ = caffe_solver.iter();
max_iter = caffe_solver.max_iter();
while (iter_ < max_iter)
caffe_solver.net.set_phase('train');
% generate minibatch training data
[shuffled_inds, sub_db_inds] = generate_random_minibatch(shuffled_inds, image_roidb_train, conf.ims_per_batch);
[im_blob, rois_blob, labels_blob, bbox_targets_blob, bbox_loss_weights_blob] = ...
fast_rcnn_get_minibatch(conf, image_roidb_train(sub_db_inds));
net_inputs = {im_blob, rois_blob, labels_blob, bbox_targets_blob, bbox_loss_weights_blob};
caffe_solver.net.reshape_as_input(net_inputs);
% one iter SGD update
caffe_solver.net.set_input_data(net_inputs);
caffe_solver.step(1);
rst = caffe_solver.net.get_output();
train_results = parse_rst(train_results, rst);
% do valdiation per val_interval iterations
if ~mod(iter_, opts.val_interval)
show_state(iter_, train_results, val_results);
train_results = [];
val_results = [];
diary; diary; % flush diary
end
% snapshot
if ~mod(iter_, opts.snapshot_interval)
snapshot(caffe_solver, bbox_means, bbox_stds, cache_dir, sprintf('iter_%d', iter_));
end
iter_ = caffe_solver.iter();
end
% final snapshot
snapshot(caffe_solver, bbox_means, bbox_stds, cache_dir, sprintf('iter_%d', iter_));
save_model_path = snapshot(caffe_solver, bbox_means, bbox_stds, cache_dir, 'final');
diary off;
caffe.reset_all();
rng(prev_rng);
end
function [shuffled_inds, sub_inds] = generate_random_minibatch(shuffled_inds, image_roidb_train, ims_per_batch)
% shuffle training data per batch
if isempty(shuffled_inds)
% make sure each minibatch, only has horizontal images or vertical
% images, to save gpu memory
hori_image_inds = arrayfun(@(x) x.im_size(2) >= x.im_size(1), image_roidb_train, 'UniformOutput', true);
vert_image_inds = ~hori_image_inds;
hori_image_inds = find(hori_image_inds);
vert_image_inds = find(vert_image_inds);
% random perm
lim = floor(length(hori_image_inds) / ims_per_batch) * ims_per_batch;
hori_image_inds = hori_image_inds(randperm(length(hori_image_inds), lim));
lim = floor(length(vert_image_inds) / ims_per_batch) * ims_per_batch;
vert_image_inds = vert_image_inds(randperm(length(vert_image_inds), lim));
% combine sample for each ims_per_batch
hori_image_inds = reshape(hori_image_inds, ims_per_batch, []);
vert_image_inds = reshape(vert_image_inds, ims_per_batch, []);
shuffled_inds = [hori_image_inds, vert_image_inds];
shuffled_inds = shuffled_inds(:, randperm(size(shuffled_inds, 2)));
shuffled_inds = num2cell(shuffled_inds, 1);
end
if nargout > 1
% generate minibatch training data
sub_inds = shuffled_inds{1};
assert(length(sub_inds) == ims_per_batch);
shuffled_inds(1) = [];
end
end
function check_gpu_memory(conf, caffe_solver, num_classes, do_val)
%% try to train/val with images which have maximum size potentially, to validate whether the gpu memory is enough
% generate pseudo training data with max size
im_blob = single(zeros(max(conf.scales), conf.max_size, 3, conf.ims_per_batch));
rois_blob = single(repmat([0; 0; 0; max(conf.scales)-1; conf.max_size-1], 1, conf.batch_size));
rois_blob = permute(rois_blob, [3, 4, 1, 2]);
labels_blob = single(ones(conf.batch_size, 1));
labels_blob = permute(labels_blob, [3, 4, 2, 1]);
bbox_targets_blob = zeros(4 * (num_classes+1), conf.batch_size, 'single');
bbox_targets_blob = single(permute(bbox_targets_blob, [3, 4, 1, 2]));
bbox_loss_weights_blob = bbox_targets_blob;
net_inputs = {im_blob, rois_blob, labels_blob, bbox_targets_blob, bbox_loss_weights_blob};
% Reshape net's input blobs
caffe_solver.net.reshape_as_input(net_inputs);
% one iter SGD update
caffe_solver.net.set_input_data(net_inputs);
caffe_solver.step(1);
if do_val
% use the same net with train to save memory
caffe_solver.net.set_phase('test');
caffe_solver.net.forward(net_inputs);
caffe_solver.net.set_phase('train');
end
end
function model_path = snapshot(caffe_solver, bbox_means, bbox_stds, cache_dir, file_name)
bbox_stds_flatten = reshape(bbox_stds', [], 1);
bbox_means_flatten = reshape(bbox_means', [], 1);
% merge bbox_means, bbox_stds into the model
bbox_pred_layer_name = 'bbox_pred';
weights = caffe_solver.net.params(bbox_pred_layer_name, 1).get_data();
biase = caffe_solver.net.params(bbox_pred_layer_name, 2).get_data();
weights_back = weights;
biase_back = biase;
weights = ...
bsxfun(@times, weights, bbox_stds_flatten'); % weights = weights * stds;
biase = ...
biase .* bbox_stds_flatten + bbox_means_flatten; % bias = bias * stds + means;
caffe_solver.net.set_params_data(bbox_pred_layer_name, 1, weights);
caffe_solver.net.set_params_data(bbox_pred_layer_name, 2, biase);
model_path = fullfile(cache_dir, file_name);
caffe_solver.net.save(model_path);
fprintf('Saved as %s\n', model_path);
% restore net to original state
caffe_solver.net.set_params_data(bbox_pred_layer_name, 1, weights_back);
caffe_solver.net.set_params_data(bbox_pred_layer_name, 2, biase_back);
end
function show_state(iter, train_results, val_results)
fprintf('\n------------------------- Iteration %d -------------------------\n', iter);
fprintf('Training : error %.3g, loss (cls %.3g, reg %.3g)\n', ...
1 - mean(train_results.accuarcy.data), ...
mean(train_results.loss_cls.data), ...
mean(train_results.loss_bbox.data));
if exist('val_results', 'var') && ~isempty(val_results)
fprintf('Testing : error %.3g, loss (cls %.3g, reg %.3g)\n', ...
1 - mean(val_results.accuarcy.data), ...
mean(val_results.loss_cls.data), ...
mean(val_results.loss_bbox.data));
end
end
|
github
|
xiaohuige1/udn_extend-master
|
fast_rcnn_im_detect.m
|
.m
|
udn_extend-master/functions/fast_rcnn/fast_rcnn_im_detect.m
| 4,781 |
utf_8
|
76b56954f7f1f2d32f89b7d0a00e8338
|
function [pred_boxes, scores] = fast_rcnn_im_detect(conf, caffe_net, im, boxes, max_rois_num_in_gpu)
% [pred_boxes, scores] = fast_rcnn_im_detect(conf, caffe_net, im, boxes, max_rois_num_in_gpu)
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
[im_blob, rois_blob, ~] = get_blobs(conf, im, boxes);
% When mapping from image ROIs to feature map ROIs, there's some aliasing
% (some distinct image ROIs get mapped to the same feature ROI).
% Here, we identify duplicate feature ROIs, so we only compute features
% on the unique subset.
[~, index, inv_index] = unique(rois_blob, 'rows');
rois_blob = rois_blob(index, :);
boxes = boxes(index, :);
% permute data into caffe c++ memory, thus [num, channels, height, width]
im_blob = im_blob(:, :, [3, 2, 1], :); % from rgb to brg
im_blob = permute(im_blob, [2, 1, 3, 4]);
im_blob = single(im_blob);
rois_blob = rois_blob - 1; % to c's index (start from 0)
rois_blob = permute(rois_blob, [3, 4, 2, 1]);
rois_blob = single(rois_blob);
total_rois = size(rois_blob, 4);
total_scores = cell(ceil(total_rois / max_rois_num_in_gpu), 1);
total_box_deltas = cell(ceil(total_rois / max_rois_num_in_gpu), 1);
for i = 1:ceil(total_rois / max_rois_num_in_gpu)
sub_ind_start = 1 + (i-1) * max_rois_num_in_gpu;
sub_ind_end = min(total_rois, i * max_rois_num_in_gpu);
sub_rois_blob = rois_blob(:, :, :, sub_ind_start:sub_ind_end);
net_inputs = {im_blob, sub_rois_blob};
% Reshape net's input blobs
caffe_net.reshape_as_input(net_inputs);
output_blobs = caffe_net.forward(net_inputs);
if conf.test_binary
% simulate binary logistic regression
scores = caffe_net.blobs('cls_score').get_data();
scores = squeeze(scores)';
% Return scores as fg - bg
scores = bsxfun(@minus, scores, scores(:, 1));
else
% use softmax estimated probabilities
scores = output_blobs{2};
scores = squeeze(scores)';
end
% Apply bounding-box regression deltas
box_deltas = output_blobs{1};
box_deltas = squeeze(box_deltas)';
total_scores{i} = scores;
total_box_deltas{i} = box_deltas;
end
scores = cell2mat(total_scores);
box_deltas = cell2mat(total_box_deltas);
pred_boxes = fast_rcnn_bbox_transform_inv(boxes, box_deltas);
pred_boxes = clip_boxes(pred_boxes, size(im, 2), size(im, 1));
% Map scores and predictions back to the original set of boxes
scores = scores(inv_index, :);
pred_boxes = pred_boxes(inv_index, :);
% remove scores and boxes for back-ground
pred_boxes = pred_boxes(:, 5:end);
scores = scores(:, 2:end);
end
function [data_blob, rois_blob, im_scale_factors] = get_blobs(conf, im, rois)
[data_blob, im_scale_factors] = get_image_blob(conf, im);
rois_blob = get_rois_blob(conf, rois, im_scale_factors);
end
function [blob, im_scales] = get_image_blob(conf, im)
[ims, im_scales] = arrayfun(@(x) prep_im_for_blob(im, conf.image_means, x, conf.test_max_size), conf.test_scales, 'UniformOutput', false);
im_scales = cell2mat(im_scales);
blob = im_list_to_blob(ims);
end
function [rois_blob] = get_rois_blob(conf, im_rois, im_scale_factors)
[feat_rois, levels] = map_im_rois_to_feat_rois(conf, im_rois, im_scale_factors);
rois_blob = single([levels, feat_rois]);
end
function [feat_rois, levels] = map_im_rois_to_feat_rois(conf, im_rois, scales)
im_rois = single(im_rois);
if length(scales) > 1
widths = im_rois(:, 3) - im_rois(:, 1) + 1;
heights = im_rois(:, 4) - im_rois(:, 2) + 1;
areas = widths .* heights;
scaled_areas = bsxfun(@times, areas(:), scales(:)'.^2);
[~, levels] = min(abs(scaled_areas - 224.^2), [], 2);
else
levels = ones(size(im_rois, 1), 1);
end
feat_rois = round(bsxfun(@times, im_rois-1, scales(levels))) + 1;
end
function boxes = clip_boxes(boxes, im_width, im_height)
% x1 >= 1 & <= im_width
boxes(:, 1:4:end) = max(min(boxes(:, 1:4:end), im_width), 1);
% y1 >= 1 & <= im_height
boxes(:, 2:4:end) = max(min(boxes(:, 2:4:end), im_height), 1);
% x2 >= 1 & <= im_width
boxes(:, 3:4:end) = max(min(boxes(:, 3:4:end), im_width), 1);
% y2 >= 1 & <= im_height
boxes(:, 4:4:end) = max(min(boxes(:, 4:4:end), im_height), 1);
end
|
github
|
xiaohuige1/udn_extend-master
|
fast_rcnn_test.m
|
.m
|
udn_extend-master/functions/fast_rcnn/fast_rcnn_test.m
| 8,455 |
utf_8
|
1b4a7dc5b5a0d67d5458497cdc47242d
|
function mAP = fast_rcnn_test(conf, imdb, roidb, varargin)
% mAP = fast_rcnn_test(conf, imdb, roidb, varargin)
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
%% inputs
ip = inputParser;
ip.addRequired('conf', @isstruct);
ip.addRequired('imdb', @isstruct);
ip.addRequired('roidb', @isstruct);
ip.addParamValue('net_def_file', '', @isstr);
ip.addParamValue('net_file', '', @isstr);
ip.addParamValue('cache_name', '', @isstr);
ip.addParamValue('suffix', '', @isstr);
ip.addParamValue('ignore_cache', false, @islogical);
ip.parse(conf, imdb, roidb, varargin{:});
opts = ip.Results;
%% set cache dir
cache_dir = fullfile(pwd, 'output', 'fast_rcnn_cachedir', opts.cache_name, imdb.name);
mkdir_if_missing(cache_dir);
%% init log
timestamp = datestr(datevec(now()), 'yyyymmdd_HHMMSS');
mkdir_if_missing(fullfile(cache_dir, 'log'));
log_file = fullfile(cache_dir, 'log', ['test_', timestamp, '.txt']);
diary(log_file);
num_images = length(imdb.image_ids);
num_classes = imdb.num_classes;
try
aboxes = cell(num_classes, 1);
if opts.ignore_cache
throw('');
end
for i = 1:num_classes
load(fullfile(cache_dir, [imdb.classes{i} '_boxes_' imdb.name opts.suffix]));
aboxes{i} = boxes;
end
catch
%% testing
% init caffe net
caffe_log_file_base = fullfile(cache_dir, 'caffe_log');
caffe.init_log(caffe_log_file_base);
caffe_net = caffe.Net(opts.net_def_file, 'test');
caffe_net.copy_from(opts.net_file);
% set random seed
prev_rng = seed_rand(conf.rng_seed);
caffe.set_random_seed(conf.rng_seed);
% set gpu/cpu
if conf.use_gpu
caffe.set_mode_gpu();
else
caffe.set_mode_cpu();
end
% determine the maximum number of rois in testing
max_rois_num_in_gpu = check_gpu_memory(conf, caffe_net);
disp('opts:');
disp(opts);
disp('conf:');
disp(conf);
%heuristic: keep an average of 40 detections per class per images prior to NMS
max_per_set = 40 * num_images;
% heuristic: keep at most 100 detection per class per image prior to NMS
max_per_image = 100;
% detection thresold for each class (this is adaptively set based on the max_per_set constraint)
thresh = -inf * ones(num_classes, 1);
% top_scores will hold one minheap of scores per class (used to enforce the max_per_set constraint)
top_scores = cell(num_classes, 1);
% all detections are collected into:
% all_boxes[cls][image] = N x 5 array of detections in
% (x1, y1, x2, y2, score)
aboxes = cell(num_classes, 1);
box_inds = cell(num_classes, 1);
for i = 1:num_classes
aboxes{i} = cell(length(imdb.image_ids), 1);
box_inds{i} = cell(length(imdb.image_ids), 1);
end
count = 0;
t_start = tic;
for i = 1:num_images
count = count + 1;
fprintf('%s: test (%s) %d/%d ', procid(), imdb.name, count, num_images);
th = tic;
d = roidb.rois(i);
im = imread(imdb.image_at(i));
[boxes, scores] = fast_rcnn_im_detect(conf, caffe_net, im, d.boxes, max_rois_num_in_gpu);
for j = 1:num_classes
inds = find(~d.gt & scores(:, j) > thresh(j));
if ~isempty(inds)
[~, ord] = sort(scores(inds, j), 'descend');
ord = ord(1:min(length(ord), max_per_image));
inds = inds(ord);
cls_boxes = boxes(inds, (1+(j-1)*4):((j)*4));
cls_scores = scores(inds, j);
aboxes{j}{i} = [aboxes{j}{i}; cat(2, single(cls_boxes), single(cls_scores))];
box_inds{j}{i} = [box_inds{j}{i}; inds];
else
aboxes{j}{i} = [aboxes{j}{i}; zeros(0, 5, 'single')];
box_inds{j}{i} = box_inds{j}{i};
end
end
fprintf(' time: %.3fs\n', toc(th));
if mod(count, 1000) == 0
for j = 1:num_classes
[aboxes{j}, box_inds{j}, thresh(j)] = ...
keep_top_k(aboxes{j}, box_inds{j}, i, max_per_set, thresh(j));
end
disp(thresh);
end
end
for j = 1:num_classes
[aboxes{j}, box_inds{j}, thresh(j)] = ...
keep_top_k(aboxes{j}, box_inds{j}, i, max_per_set, thresh(j));
end
disp(thresh);
for i = 1:num_classes
top_scores{i} = sort(top_scores{i}, 'descend');
if (length(top_scores{i}) > max_per_set)
thresh(i) = top_scores{i}(max_per_set);
end
% go back through and prune out detections below the found threshold
for j = 1:length(imdb.image_ids)
if ~isempty(aboxes{i}{j})
I = find(aboxes{i}{j}(:,end) < thresh(i));
aboxes{i}{j}(I,:) = [];
box_inds{i}{j}(I,:) = [];
end
end
save_file = fullfile(cache_dir, [imdb.classes{i} '_boxes_' imdb.name opts.suffix]);
boxes = aboxes{i};
inds = box_inds{i};
save(save_file, 'boxes', 'inds');
clear boxes inds;
end
fprintf('test all images in %f seconds.\n', toc(t_start));
caffe.reset_all();
rng(prev_rng);
end
% ------------------------------------------------------------------------
% Peform AP evaluation
% ------------------------------------------------------------------------
if isequal(imdb.eval_func, @imdb_eval_voc)
for model_ind = 1:num_classes
cls = imdb.classes{model_ind};
res(model_ind) = imdb.eval_func(cls, aboxes{model_ind}, imdb, opts.cache_name, opts.suffix);
end
else
% ilsvrc
res = imdb.eval_func(aboxes, imdb, opts.cache_name, opts.suffix);
end
if ~isempty(res)
fprintf('\n~~~~~~~~~~~~~~~~~~~~\n');
fprintf('Results:\n');
aps = [res(:).ap]' * 100;
disp(aps);
disp(mean(aps));
fprintf('~~~~~~~~~~~~~~~~~~~~\n');
mAP = mean(aps);
else
mAP = nan;
end
diary off;
end
function max_rois_num = check_gpu_memory(conf, caffe_net)
%% try to determine the maximum number of rois
max_rois_num = 0;
for rois_num = 500:500:5000
% generate pseudo testing data with max size
im_blob = single(zeros(conf.max_size, conf.max_size, 3, 1));
rois_blob = single(repmat([0; 0; 0; conf.max_size-1; conf.max_size-1], 1, rois_num));
rois_blob = permute(rois_blob, [3, 4, 1, 2]);
net_inputs = {im_blob, rois_blob};
% Reshape net's input blobs
caffe_net.reshape_as_input(net_inputs);
caffe_net.forward(net_inputs);
gpuInfo = gpuDevice();
max_rois_num = rois_num;
if gpuInfo.FreeMemory < 2 * 10^9 % 2GB for safety
break;
end
end
end
% ------------------------------------------------------------------------
function [boxes, box_inds, thresh] = keep_top_k(boxes, box_inds, end_at, top_k, thresh)
% ------------------------------------------------------------------------
% Keep top K
X = cat(1, boxes{1:end_at});
if isempty(X)
return;
end
scores = sort(X(:,end), 'descend');
thresh = scores(min(length(scores), top_k));
for image_index = 1:end_at
if ~isempty(boxes{image_index})
bbox = boxes{image_index};
keep = find(bbox(:,end) >= thresh);
boxes{image_index} = bbox(keep,:);
box_inds{image_index} = box_inds{image_index}(keep);
end
end
end
|
github
|
xiaohuige1/udn_extend-master
|
fast_rcnn_prepare_image_roidb.m
|
.m
|
udn_extend-master/functions/fast_rcnn/fast_rcnn_prepare_image_roidb.m
| 6,244 |
utf_8
|
c1d573a68d0365fd02ff3a204ccf9a3b
|
function [image_roidb, bbox_means, bbox_stds] = fast_rcnn_prepare_image_roidb(conf, imdbs, roidbs, bbox_means, bbox_stds)
% [image_roidb, bbox_means, bbox_stds] = fast_rcnn_prepare_image_roidb(conf, imdbs, roidbs, cache_img, bbox_means, bbox_stds)
% Gather useful information from imdb and roidb
% pre-calculate mean (bbox_means) and std (bbox_stds) of the regression
% term for normalization
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
if ~exist('bbox_means', 'var')
bbox_means = [];
bbox_stds = [];
end
if ~iscell(imdbs)
imdbs = {imdbs};
roidbs = {roidbs};
end
imdbs = imdbs(:);
roidbs = roidbs(:);
image_roidb = ...
cellfun(@(x, y) ... // @(imdbs, roidbs)
arrayfun(@(z) ... //@([1:length(x.image_ids)])
struct('image_path', x.image_at(z), 'image_id', x.image_ids{z}, 'im_size', x.sizes(z, :), 'imdb_name', x.name, 'ignores', y.rois(z).ignores, ...
'overlap', y.rois(z).overlap, 'boxes', y.rois(z).boxes, 'class', y.rois(z).class, 'image', [], 'bbox_targets', []), ...
[1:length(x.image_ids)]', 'UniformOutput', true),...
imdbs, roidbs, 'UniformOutput', false);
image_roidb = cat(1, image_roidb{:});
% enhance roidb to contain bounding-box regression targets
[image_roidb, bbox_means, bbox_stds] = append_bbox_regression_targets(conf, image_roidb, bbox_means, bbox_stds);
end
function [image_roidb, means, stds] = append_bbox_regression_targets(conf, image_roidb, means, stds)
% means and stds -- (k+1) * 4, include background class
num_images = length(image_roidb);
% Infer number of classes from the number of columns in gt_overlaps
num_classes = size(image_roidb(1).overlap, 2);
valid_imgs = true(num_images, 1);
for i = 1:num_images
rois = image_roidb(i).boxes;
% try
[image_roidb(i).bbox_targets, valid_imgs(i)] = ...
compute_targets(conf, rois, image_roidb(i).overlap, image_roidb(i).ignores);
% catch
% debug = 1;
% end
end
if ~all(valid_imgs)
image_roidb = image_roidb(valid_imgs);
num_images = length(image_roidb);
fprintf('Warning: fast_rcnn_prepare_image_roidb: filter out %d images, which contains zero valid samples\n', sum(~valid_imgs));
end
if ~(exist('means', 'var') && ~isempty(means) && exist('stds', 'var') && ~isempty(stds))
% Compute values needed for means and stds
% var(x) = E(x^2) - E(x)^2
class_counts = zeros(num_classes, 1) + eps;
sums = zeros(num_classes, 4);
squared_sums = zeros(num_classes, 4);
for i = 1:num_images
targets = image_roidb(i).bbox_targets;
for cls = 1:num_classes
cls_inds = find(targets(:, 1) == cls);
if ~isempty(cls_inds)
class_counts(cls) = class_counts(cls) + length(cls_inds);
sums(cls, :) = sums(cls, :) + sum(targets(cls_inds, 2:end), 1);
squared_sums(cls, :) = squared_sums(cls, :) + sum(targets(cls_inds, 2:end).^2, 1);
end
end
end
means = bsxfun(@rdivide, sums, class_counts);
stds = (bsxfun(@minus, bsxfun(@rdivide, squared_sums, class_counts), means.^2)).^0.5;
% add background class
means = [0, 0, 0, 0; means];
stds = [0, 0, 0, 0; stds];
end
% Normalize targets
for i = 1:num_images
targets = image_roidb(i).bbox_targets;
for cls = 1:num_classes
cls_inds = find(targets(:, 1) == cls);
if ~isempty(cls_inds)
image_roidb(i).bbox_targets(cls_inds, 2:end) = ...
bsxfun(@minus, image_roidb(i).bbox_targets(cls_inds, 2:end), means(cls+1, :));
image_roidb(i).bbox_targets(cls_inds, 2:end) = ...
bsxfun(@rdivide, image_roidb(i).bbox_targets(cls_inds, 2:end), stds(cls+1, :));
end
end
end
end
function [bbox_targets, is_valid] = compute_targets(conf, rois, overlap, gt_ignores)
overlap = full(overlap);
[max_overlaps, max_labels] = max(overlap, [], 2);
% ensure ROIs are floats
rois = single(rois);
bbox_targets = zeros(size(rois, 1), 5, 'single');
% Indices of ground-truth ROIs
gt_inds_full = find(max_overlaps == 1);
if ~isempty(gt_inds_full)
gt_inds = gt_inds_full & ~gt_ignores;
max_overlaps(find(gt_inds == 0)) = -1;
gt_inds = find(gt_inds == 1);
% gt_inds(find(gt_inds == 0)) = [];
else
gt_inds = [];
end
if ~isempty(gt_inds)
% Indices of examples for which we try to make predictions
ex_inds = find(max_overlaps >= conf.bbox_thresh);
% Get IoU overlap between each ex ROI and gt ROI
ex_gt_overlaps = boxoverlap(rois(ex_inds, :), rois(gt_inds, :));
% try
assert(all(abs(max(ex_gt_overlaps, [], 2) - max_overlaps(ex_inds)) < 10^-4));
% catch
% debug = 1;
% end
% Find which gt ROI each ex ROI has max overlap with:
% this will be the ex ROI's gt target
[~, gt_assignment] = max(ex_gt_overlaps, [], 2);
gt_rois = rois(gt_inds(gt_assignment), :);
ex_rois = rois(ex_inds, :);
[regression_label] = fast_rcnn_bbox_transform(ex_rois, gt_rois);
bbox_targets(ex_inds, :) = [max_labels(ex_inds), regression_label];
end
% Select foreground ROIs as those with >= fg_thresh overlap
is_fg = max_overlaps >= conf.fg_thresh;
% Select background ROIs as those within [bg_thresh_lo, bg_thresh_hi)
is_bg = max_overlaps < conf.bg_thresh_hi & max_overlaps >= conf.bg_thresh_lo;
% check if there is any fg or bg sample. If no, filter out this image
is_valid = true;
if ~any(is_fg | is_bg)
is_valid = false;
end
end
|
github
|
xiaohuige1/udn_extend-master
|
fast_rcnn_generate_sliding_windows.m
|
.m
|
udn_extend-master/functions/fast_rcnn/fast_rcnn_generate_sliding_windows.m
| 1,729 |
utf_8
|
a788da565d8e7d1810407473c3135094
|
function roidb = fast_rcnn_generate_sliding_windows(conf, imdb, roidb, roipool_in_size)
% [pred_boxes, scores] = fast_rcnn_conv_feat_detect(conf, im, conv_feat, boxes, max_rois_num_in_gpu, net_idx)
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
regions.images = imdb.image_ids;
im_sizes = imdb.sizes;
regions.boxes = cellfun(@(x) generate_sliding_windows_one_image(conf, x, roipool_in_size), num2cell(im_sizes, 2), 'UniformOutput', false);
roidb = roidb_from_proposal(imdb, roidb, regions);
end
function boxes = generate_sliding_windows_one_image(conf, im_size, roipool_in_size)
im_scale = prep_im_for_blob_size(im_size, conf.scales, conf.max_size);
im_size = round(im_size * im_scale);
x1 = 1:conf.feat_stride:im_size(2);
y1 = 1:conf.feat_stride:im_size(1);
[x1, y1] = meshgrid(x1, y1);
x1 = x1(:);
y1 = y1(:);
x2 = x1 + roipool_in_size * conf.feat_stride - 1;
y2 = y1 + roipool_in_size * conf.feat_stride - 1;
boxes = [x1, y1, x2, y2];
boxes = filter_boxes(im_size, boxes);
boxes = bsxfun(@times, boxes-1, 1/im_scale) + 1;
end
function boxes = filter_boxes(im_size, boxes)
valid_ind = boxes(:, 1) >= 1 & boxes(:, 1) <= im_size(2) & ...
boxes(:, 2) >= 1 & boxes(:, 2) <= im_size(1) & ...
boxes(:, 3) >= 1 & boxes(:, 3) <= im_size(2) & ...
boxes(:, 4) >= 1 & boxes(:, 4) <= im_size(1);
boxes = boxes(valid_ind, :);
end
|
github
|
xiaohuige1/udn_extend-master
|
showboxes.m
|
.m
|
udn_extend-master/utils/showboxes.m
| 2,624 |
utf_8
|
be6b3bca7e6364f27e7ac8d3f76a3628
|
function showboxes(im, boxes, legends, color_conf)
% Draw bounding boxes on top of an image.
% showboxes(im, boxes)
%
% -------------------------------------------------------
fix_width = 800;
if isa(im, 'gpuArray')
im = gather(im);
end
imsz = size(im);
scale = fix_width / imsz(2);
im = imresize(im, scale);
if size(boxes{1}, 2) >= 5
boxes = cellfun(@(x) [x(:, 1:4) * scale, x(:, 5)], boxes, 'UniformOutput', false);
else
boxes = cellfun(@(x) x(:, 1:4) * scale, boxes, 'UniformOutput', false);
end
if ~exist('color_conf', 'var')
color_conf = 'default';
end
image(im);
axis image;
axis off;
set(gcf, 'Color', 'white');
valid_boxes = cellfun(@(x) ~isempty(x), boxes, 'UniformOutput', true);
valid_boxes_num = sum(valid_boxes);
if valid_boxes_num > 0
switch color_conf
case 'default'
colors_candidate = colormap('hsv');
colors_candidate = colors_candidate(1:(floor(size(colors_candidate, 1)/valid_boxes_num)):end, :);
colors_candidate = mat2cell(colors_candidate, ones(size(colors_candidate, 1), 1))';
colors = cell(size(valid_boxes));
colors(valid_boxes) = colors_candidate(1:sum(valid_boxes));
case 'voc'
colors_candidate = colormap('hsv');
colors_candidate = colors_candidate(1:(floor(size(colors_candidate, 1)/20)):end, :);
colors_candidate = mat2cell(colors_candidate, ones(size(colors_candidate, 1), 1))';
colors = colors_candidate;
end
for i = 1:length(boxes)
if isempty(boxes{i})
continue;
end
for j = 1:size(boxes{i})
box = boxes{i}(j, 1:4);
if size(boxes{i}, 2) >= 5
score = boxes{i}(j, end);
linewidth = 2 + min(max(score, 0), 1) * 2;
rectangle('Position', RectLTRB2LTWH(box), 'LineWidth', linewidth, 'EdgeColor', colors{i});
label = sprintf('%s : %.3f', legends{i}, score);
text(double(box(1))+2, double(box(2)), label, 'BackgroundColor', 'w');
else
linewidth = 2;
rectangle('Position', RectLTRB2LTWH(box), 'LineWidth', linewidth, 'EdgeColor', colors{i});
label = sprintf('%s(%d)', legends{i}, i);
text(double(box(1))+2, double(box(2)), label, 'BackgroundColor', 'w');
end
end
end
end
end
function [ rectsLTWH ] = RectLTRB2LTWH( rectsLTRB )
%rects (l, t, r, b) to (l, t, w, h)
rectsLTWH = [rectsLTRB(:, 1), rectsLTRB(:, 2), rectsLTRB(:, 3)-rectsLTRB(:,1)+1, rectsLTRB(:,4)-rectsLTRB(2)+1];
end
|
github
|
xiaohuige1/udn_extend-master
|
classification_demo.m
|
.m
|
udn_extend-master/external/caffe_new/matlab/demo/classification_demo.m
| 5,412 |
utf_8
|
8f46deabe6cde287c4759f3bc8b7f819
|
function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to you Matlab search PATH to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github
|
xiaohuige1/udn_extend-master
|
script_rpn_rcnn_new.m
|
.m
|
udn_extend-master/experiments/script_rpn_rcnn_new.m
| 4,036 |
utf_8
|
bcd6a8c3655d0587b6d7c9eca263c332
|
function [train_box train_box_rcnn train_box_rpn]= script_rpn_rcnn_new()
clc;
clear mex;
clear is_valid_handle; % to clear init_key
run(fullfile(fileparts(fileparts(mfilename('fullpath'))), 'startup'));
%% -------------------- CONFIG --------------------
opts.caffe_version = 'caffe';
opts.gpu_id = auto_select_gpu;
active_caffe_mex(opts.gpu_id, opts.caffe_version);
% opts.nms_overlap_thres = 0.7;
opts.after_nms_topN = 300;
opts.use_gpu = true;
opts.test_scales = 800;
%% -------------------- INIT_MODEL --------------------
model_dir_rcnn = fullfile(pwd, 'def_model/final_nohnm.caffemodel');
rcnn_model_net = fullfile(pwd, 'def_model/test_fastrcnn.prototxt');
proposal_detection_model = load_proposal_detection_model();
proposal_detection_model.detection_net_def ...
= rcnn_model_net;
proposal_detection_model.detection_net ...
= model_dir_rcnn;
proposal_detection_model.conf_proposal.test_scales = opts.test_scales;
proposal_detection_model.conf_detection.test_scales = opts.test_scales;
if opts.use_gpu
proposal_detection_model.conf_detection.image_means = gpuArray(proposal_detection_model.conf_detection.image_means);
end
caffe.init_log(fullfile(pwd, 'caffe_log'));
% proposal net
fast_rcnn_net = caffe.Net(proposal_detection_model.detection_net_def, 'test');
fast_rcnn_net.copy_from(proposal_detection_model.detection_net);
% set gpu/cpu
if opts.use_gpu
caffe.set_mode_gpu();
else
caffe.set_mode_cpu();
end
%% -------------------- WARM UP --------------------
load('imdb/cache/imdb_caltech_test.mat')
rpn = load('rpn_0_2.mat');
train_box ={};
train_box_rcnn = {};
running_time = [];
for j = 1:length(rpn.dt_boxes)
img_name = fullfile(imdb.image_dir, [imdb.image_ids{j} '.jpg']);
im = imread(img_name);
fprintf('%d: %s\n',j, img_name);
if opts.use_gpu
im = gpuArray(im);
end
aboxes = rpn.dt_boxes{j};
aboxes(:,3) = aboxes(:,1)+aboxes(:,3);
aboxes(:,4) = aboxes(:,2)+aboxes(:,4);
% test detection
th = tic();
if 0%proposal_detection_model.is_share_feature
[boxes, scores] = fast_rcnn_conv_feat_detect(proposal_detection_model.conf_detection, fast_rcnn_net, im, ...
rpn_net.blobs(proposal_detection_model.last_shared_output_blob_name), ...
aboxes(:, 1:4), opts.after_nms_topN);
else
[boxes, scores] = fast_rcnn_im_detect_our(proposal_detection_model.conf_detection, fast_rcnn_net, im, ...
aboxes(:, 1:4), 5);
end
t_detection = toc(th);
% visualize
classes = proposal_detection_model.classes;
boxes_cell = cell(length(classes), 1);
thres = 0;
for i = 1:length(boxes_cell)
if(isempty(boxes))
continue;
end
try
boxes_cell{i} = [boxes(:, (1+(i-1)*4):(i*4)), scores(:, i)];
train_box_rcnn{j} = boxes_cell{i};
catch
pause
end
boxes_cell{i} = boxes_cell{i}(nms(boxes_cell{i}, 0.3), :);
I = boxes_cell{i}(:, 5) >= thres;
boxes_cell{i} = boxes_cell{i}(I, :);
end
train_box{j} = boxes_cell;
end
save('test_rst', 'train_box_rcnn', 'train_box');
caffe.reset_all();
% clear mex;
end
function proposal_detection_model = load_proposal_detection_model()
ld = load(fullfile(pwd, 'final/model_setting.mat'));
proposal_detection_model = ld.proposal_detection_model;
clear ld;
end
function aboxes = boxes_filter(aboxes, per_nms_topN, nms_overlap_thres, after_nms_topN, use_gpu)
% to speed up nms
if per_nms_topN > 0
aboxes = aboxes(1:min(length(aboxes), per_nms_topN), :);
end
% do nms
if nms_overlap_thres > 0 && nms_overlap_thres < 1
aboxes = aboxes(nms(aboxes, nms_overlap_thres, use_gpu), :);
end
if after_nms_topN > 0
aboxes = aboxes(1:min(length(aboxes), after_nms_topN), :);
end
end
|
github
|
qboticslabs/Autoware-master
|
velCapture.m
|
.m
|
Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/velCapture.m
| 1,047 |
utf_8
|
994f8bb886b3e3ebef61b89d3c9c00a9
|
% Function to capture catvehicle velocity and plotting live graph
function velCapture(ROS_IP, roboname)
%If number of argument is not two, flag message and exit.
if nargin < 2
disp('Uage: velocityProfiler(192.168.0.32, catvehicle)');
return;
end
close all;
%rosshutdown;
modelname = strcat('/',roboname);
%Connect to ROS master
master_uri= strcat('http://',ROS_IP);
master_uri = strcat(master_uri,':11311');
%rosinit(master_uri);
%get handle for /catvehicle/vel topic for subscribing to the data
speedsub = rossubscriber(strcat(modelname,'/vel'));
dt = datestr(now,'mmmm-dd-yyyy-HH-MM-SS');
sprintf('Velocity capture starts at %s',dt)
t = 0:0.05:50;
output = zeros(length(t),1);
figure;
grid on;
title('Velocity [m/s]');
for i = 1:length(t)
speedata = receive(speedsub,10);
output(i) = speedata.Linear.X;
plot([max(i-1,1),i], output([max(i-1,1),i]),'b-');
hold on;
drawnow;
end
dt = datestr(now,'mmmm-dd-yyyy-HH-MM-SS');
file = strcat(dt,'.mat');
save(file, 'output');
grid on;
title('Velocity [m/s]');
end
|
github
|
qboticslabs/Autoware-master
|
profileByMatrix.m
|
.m
|
Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/profileByMatrix.m
| 1,840 |
utf_8
|
f81181e46cb60adc3466c4779083ce0d
|
%Implementation of follower algorithm
%Developed by Rahul Kumar Bhadani <[email protected]>
%ROS_IP = IP Address of ROS Master
%lead = name of the model of leader AV Car
%follower = name of the model of follower car
function profileByMatrix(ROS_IP, roboname, vel_input, time_input, tire_angle)
%If number of argument is not two, flag message and exit.
if nargin < 4
sprintf('Uage: velocityProfiler(192.168.0.32, catvehicle, velmatfile, timematfile)');
return;
end
if nargin < 5
tire_angle = 0.0;
end
rosshutdown;
close all;
modelname = strcat('/',roboname);
%Connect to ROS master
master_uri= strcat('http://',ROS_IP);
master_uri = strcat(master_uri,':11311');
rosinit(master_uri);
%get handle for /catvehicle/cmd_vel topic for publishing the data
velpub = rospublisher(strcat(modelname,'/cmd_vel'),rostype.geometry_msgs_Twist);
%get handle for /catvehicle/vel topic for subscribing to the data
speedsub = rossubscriber(strcat(modelname,'/vel'));
vmat = load(vel_input);
tmat = load(time_input);
t = tmat.t;
%Velocity profile
input = vmat.Vel;
%Velocity profile will be sine
%input = abs(2*sin(t));
%Variable to store output velocity
output = zeros(length(t),1);
%handle for rosmessage object for velpub topic
velMsgs = rosmessage(velpub);
for i=1:length(t)
velMsgs.Linear.X = input(i);
velMsgs.Angular.Z = tire_angle;
%Publish on the topic /catvehicle/cmd_vel
send(velpub, velMsgs);
%Read from the topic /catvehicle/speed
speedata = receive(speedsub,10);
output(i) = speedata.Linear.X;
pause(0.1);
if i == 3000
break;
end
end
%Plot the input and output velocity profile
[n, p] = size(output);
T = 1:n;
plot(T, input');
hold on;
plot(T, output);
title('Original Data');
legend('Input function', 'Output response');
grid on;
save input.mat input output
|
github
|
qboticslabs/Autoware-master
|
velocityProfiler.m
|
.m
|
Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/velocityProfiler.m
| 1,758 |
utf_8
|
d12bb47043d421e21fc4fd4fa8ce4b02
|
%Matlab scripto to publish velocity on /catvehicle/cmd_vel topic and
%subscribe to catvehicle/speed topic
%Developed by Rahul Kumar Bhadani <[email protected]>
%ROS_IP = IP Address of ROS Master
%roboname = name of the model
function velocityProfiler(ROS_IP, roboname, tire_angle)
%If number of argument is not two, flag message and exit.
if nargin < 2
sprintf('Uage: velocityProfiler(192.168.0.32, catvehicle)');
return;
end
if nargin < 3
tire_angle = 0.0;
end
rosshutdown;
close all;
modelname = strcat('/',roboname);
%Connect to ROS master
master_uri= strcat('http://',ROS_IP);
master_uri = strcat(master_uri,':11311');
rosinit(master_uri);
%get handle for /catvehicle/cmd_vel topic for publishing the data
velpub = rospublisher(strcat(modelname,'/cmd_vel'),rostype.geometry_msgs_Twist);
%get handle for /catvehicle/vel topic for subscribing to the data
speedsub = rossubscriber(strcat(modelname,'/vel'));
%Discretize timestamp
t = 0:0.01:150;
v1 = 3;
v2 = 6;
v3 = 0;
%Velocity profile
input = v1.*(t<50) + v2.*(t>=50).*(t<100) + v3.*(t>= 100);
%Velocity profile will be sine
%input = abs(2*sin(t));
%Variable to store output velocity
output = zeros(length(t),1);
%handle for rosmessage object for velpub topic
velMsgs = rosmessage(velpub);
for i=1:length(t)
velMsgs.Linear.X = input(i);
velMsgs.Angular.Z = tire_angle;
%Publish on the topic /catvehicle/cmd_vel
send(velpub, velMsgs);
%Read from the topic /catvehicle/speed
speedata = receive(speedsub,10);
output(i) = speedata.Linear.X;
end
%Plot the input and output velocity profile
[n, p] = size(output);
T = 1:n;
plot(T, input');
hold on;
plot(T, output);
title('Original Data');
legend('Input function', 'Output response');
grid on;
|
github
|
qboticslabs/Autoware-master
|
follower_profile.m
|
.m
|
Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/follower_profile.m
| 2,381 |
utf_8
|
ea7d00e67f5e7709a2cd7287216af4af
|
%Implementation of follower algorithm
%Developed by Rahul Kumar Bhadani <[email protected]>
%ROS_IP = IP Address of ROS Master
%lead = name of the model of leader AV Car
%follower = name of the model of follower car
function follower_profile(ROS_IP, lead, follower)
%If number of argument is not two, flag message and exit.
if nargin < 2
sprintf('Usage: velocityProfiler(192.168.0.32, catvehicle)');
return;
end
rosshutdown;
close all;
modelname1 = strcat('/',lead);
modelname2 = strcat('/',follower);
%Connect to ROS master
master_uri= strcat('http://',ROS_IP);
master_uri = strcat(master_uri,':11311');
rosinit(master_uri);
%get handle for cmd_vel topic for publishing the data
velpub1 = rospublisher(strcat(modelname1,'/cmd_vel'),rostype.geometry_msgs_Twist);
velpub2 = rospublisher(strcat(modelname2,'/cmd_vel'),rostype.geometry_msgs_Twist);
%get handle for speed topic for subscribing to the data
speedsub1 = rossubscriber(strcat(modelname1,'/vel'));
speedsub2 = rossubscriber(strcat(modelname2,'/vel'));
%get handle for /DistanceEstimator
distanceEstimaterSub = rossubscriber('/DistanceEstimator/dist');
%Discretize timestamp
t = 0:0.05:150;
v1 = 3;
v2 = 6;
v3 = 0;
%Velocity profile
input = v1.*(t<50) + v2.*(t>=50).*(t<100) + v3.*(t>= 100);
%Velocity profile will be sine
%input = abs(2*sin(t));
%Variable to store output velocity
output1 = zeros(length(t),1);
output2 = zeros(length(t),1);
%handle for rosmessage object for velpub topic
velMsgs1 = rosmessage(velpub1);
velMsgs2 = rosmessage(velpub2);
for i=1:length(t)
velMsgs1.Linear.X = input(i);
velMsgs1.Angular.Z = 0.0;
%Publish on the topic /catvehicle/cmd_vel
send(velpub1, velMsgs1);
%Read from the topic /catvehicle/speed
speedata1 = receive(speedsub1,10);
distance = receive(distanceEstimaterSub,10);
x = distance.Data;
%Follower control rule
velMsgs2.Linear.X = (1/30.*x + 2/3).*speedata1.Linear.X;
velMsgs2.Angular.Z = 0.0;
send(velpub2, velMsgs2);
speedata2 = receive(speedsub2,10);
output1(i) = speedata1.Linear.X;
output2(i) = speedata2.Linear.X;
end
%Plot the input and output velocity profile
[n, p] = size(output1);
T = 1:n;
plot(T, input');
hold on;
plot(T, output1);
plot(T, output2);
title('Original Data');
legend('Input function', 'Output response of lead','Output response of follower');
grid on;
|
github
|
qboticslabs/Autoware-master
|
plotDisvout.m
|
.m
|
Autoware-master/ros/src/system/gazebo/catvehicle/simulink/plotDisvout.m
| 241 |
utf_8
|
241fa676f6444e00a60b8c69a5e19efd
|
% Author: Jonathan Sprinkle
% plots the distance outputs from a data file
function plotData( timeseries )
% this timeseries is what we have
figure
hold on
plot(timeseries.Data);
plot(timeseries.uVelOut);
legend({'Distance','VelOut'});
end
|
github
|
qboticslabs/Autoware-master
|
plotData.m
|
.m
|
Autoware-master/ros/src/system/gazebo/catvehicle/simulink/plotData.m
| 350 |
utf_8
|
17951edcd31fa9c02deeb1c49a2e0d7b
|
% Author: Jonathan Sprinkle
% plots the distance outputs from a data file
function plotData( timeseries )
% this timeseries is what we have
figure
hold on
plot(timeseries.dist);
plot(timeseries.velConverted);
plot(timeseries.vdot);
plot(timeseries.vout);
plot(timeseries.uTireAngle);
legend({'dist','velConverted','vdot','vout','uTireAngle'});
end
|
github
|
qboticslabs/Autoware-master
|
plotDistances.m
|
.m
|
Autoware-master/ros/src/system/gazebo/catvehicle/simulink/plotDistances.m
| 288 |
utf_8
|
c0779b1561faff69c733c5ec8a3a9ac7
|
% Author: Jonathan Sprinkle
% plots the distance outputs from a data file
function plotDistances
load distances.mat
% this timeseries is what we have
figure
hold on
plot(DistanceEstimator.Data__signal_1_);
plot(DistanceEstimator.Data__signal_2_);
legend({'Distance','Angle (rad)'});
end
|
github
|
LucienVen/gd-master
|
Select.m
|
.m
|
gd-master/algorithm_demo/GA/Select.m
| 256 |
utf_8
|
179fd71a71f4daeb87894c1540de8ea6
|
%% 选择操作
%输入
%Chrom 种群
%FitnV 适应度值
%GGAP:代沟
%输出
%SelCh 被选择的个体
function SelCh=Select(Chrom,FitnV,GGAP)
NIND=size(Chrom,1);
NSel=max(floor(NIND*GGAP+.5),2);
ChrIx=Sus(FitnV,NSel);
SelCh=Chrom(ChrIx,:);
|
github
|
LucienVen/gd-master
|
PathLength.m
|
.m
|
gd-master/algorithm_demo/GA/PathLength.m
| 331 |
utf_8
|
13ebb52c35fa4850fcf2511f98294da0
|
%% 计算各个体的路径长度
% 输入:
% D 两两城市之间的距离
% Chrom 个体的轨迹
function len=PathLength(D,Chrom)
[row,col]=size(D);
NIND=size(Chrom,1);
len=zeros(NIND,1);
for i=1:NIND
p=[Chrom(i,:) Chrom(i,1)];
i1=p(1:end-1);
i2=p(2:end);
len(i,1)=sum(D((i1-1)*col+i2));
end
|
github
|
LucienVen/gd-master
|
InitPop.m
|
.m
|
gd-master/algorithm_demo/GA/InitPop.m
| 290 |
utf_8
|
6b17fdfc122469cbc5d1bfb4736c2100
|
%% 初始化种群
%输入:
% NIND:种群大小
% N: 个体染色体长度(这里为城市的个数)
%输出:
%初始种群
function Chrom=InitPop(NIND,N)
Chrom=zeros(NIND,N);%用于存储种群
for i=1:NIND
Chrom(i,:)=randperm(N);%随机生成初始种群
end
|
github
|
LucienVen/gd-master
|
Sus.m
|
.m
|
gd-master/algorithm_demo/GA/Sus.m
| 985 |
utf_8
|
6df9c400c837d331ed8072eab4de995e
|
% 输入:
%FitnV 个体的适应度值
%Nsel 被选择个体的数目
% 输出:
%NewChrIx 被选择个体的索引号
function NewChrIx = Sus(FitnV,Nsel)
[Nind,ans] = size(FitnV);
cumfit = cumsum(FitnV);
% 平均适应度*个体行号=适应度在每行的平均比例
trials = cumfit(Nind) / Nsel * (rand + (0:Nsel-1)');
% 适应度真实累加向量,拓展为Nind*Nsel维矩阵
Mf = cumfit(:, ones(1, Nsel));
% 适应度平均比例向量,拓展为Nsel*Nind维矩阵,转置后能与Mf进行比较操作
Mt = trials(:, ones(1, Nind))';
% 寻找适应度高于该种群每行应有的适应度平均比例的个体
% Mt<Mf:从上向下开始逼近该行最佳个体
% z<=mt:从下向上开始逼近该行最佳个体
% &:确定最佳个体所在行
% 获取其行号
[NewChrIx, ans] = find(Mt < Mf & [ zeros(1, Nsel); Mf(1:Nind-1, :) ] <= Mt);
% 生成随机序列
[ans, shuf] = sort(rand(Nsel, 1));
% 随机化
NewChrIx = NewChrIx(shuf);
|
github
|
LucienVen/gd-master
|
Distanse.m
|
.m
|
gd-master/algorithm_demo/GA/Distanse.m
| 303 |
utf_8
|
6596609d0bd418a504c5658780a7f85c
|
%% 计算两两城市之间的距离
%输入 a 各城市的位置坐标
%输出 D 两两城市之间的距离
function D=Distanse(a)
row=size(a,1);
D=zeros(row,row);
for i=1:row
for j=i+1:row
D(i,j)=((a(i,1)-a(j,1))^2+(a(i,2)-a(j,2))^2)^0.5;
D(j,i)=D(i,j);
end
end
|
github
|
LucienVen/gd-master
|
OutputPath.m
|
.m
|
gd-master/algorithm_demo/GA/OutputPath.m
| 186 |
UNKNOWN
|
ae0e96e563d28fa8e74cc505593c99cd
|
%% ���·������
%���룺R ·��
function p=OutputPath(R)
R=[R,R(1)];
N=length(R);
p=num2str(R(1));
for i=2:N
p=[p,'->',num2str(R(i))];
end
disp(p)
|
github
|
LucienVen/gd-master
|
Recombin.m
|
.m
|
gd-master/algorithm_demo/GA/Recombin.m
| 1,484 |
utf_8
|
3e1af8d1876ce772ba45578149206262
|
%% 交叉操作
% 输入
%SelCh 被选择的个体
%Pc 交叉概率
%输出:
% SelCh 交叉后的个体
function SelCh=Recombin(SelCh,Pc)
NSel=size(SelCh,1);
for i=1:2:NSel-mod(NSel,2)
if Pc>=rand %交叉概率Pc
[SelCh(i,:),SelCh(i+1,:)]=intercross(SelCh(i,:),SelCh(i+1,:));
end
end
%输入:
%a和b为两个待交叉的个体
%输出:
%a和b为交叉后得到的两个个体
function [a,b]=intercross(a,b)
L=length(a);
r1=randsrc(1,1,[1:L]);
r2=randsrc(1,1,[1:L]);
if r1~=r2
a0=a;b0=b;
s=min([r1,r2]);
e=max([r1,r2]);
for i=s:e
a1=a;b1=b;
a(i)=b0(i);
b(i)=a0(i);
x=find(a==a(i));
y=find(b==b(i));
i1=x(x~=i);
i2=y(y~=i);
if ~isempty(i1)
a(i1)=a1(i);
end
if ~isempty(i2)
b(i2)=b1(i);
end
end
end
%
% %交叉算法采用部分匹配交叉%交叉算法采用部分匹配交叉
% function [a,b]=intercross(a,b)
% L=length(a);
% r1=ceil(rand*L);
% r2=ceil(rand*L);
% r1=4;r2=7;
% if r1~=r2
% s=min([r1,r2]);
% e=max([r1,r2]);
% a1=a;b1=b;
% a(s:e)=b1(s:e);
% b(s:e)=a1(s:e);
% for i=[setdiff(1:L,s:e)]
% [tf, loc] = ismember(a(i),a(s:e));
% if tf
% a(i)=a1(loc+s-1);
% end
% [tf, loc]=ismember(b(i),b(s:e));
% if tf
% b(i)=b1(loc+s-1);
% end
% end
% end
|
github
|
LucienVen/gd-master
|
Reins.m
|
.m
|
gd-master/algorithm_demo/GA/Reins.m
| 338 |
utf_8
|
12d9f6b6178ac2b153a1fba9781b143c
|
%% 重插入子代的新种群
%输入:
%Chrom 父代的种群
%SelCh 子代种群
%ObjV 父代适应度
%输出
% Chrom 组合父代与子代后得到的新种群
function Chrom=Reins(Chrom,SelCh,ObjV)
NIND=size(Chrom,1);
NSel=size(SelCh,1);
[TobjV,index]=sort(ObjV);
Chrom=[Chrom(index(1:NIND-NSel),:);SelCh];
|
github
|
LucienVen/gd-master
|
Reverse.m
|
.m
|
gd-master/algorithm_demo/GA/Reverse.m
| 574 |
utf_8
|
9bc395d8caadb1712d5f089b36a7fc01
|
%% 进化逆转函数
%输入
%SelCh 被选择的个体
%D 个城市的距离矩阵
%输出
%SelCh 进化逆转后的个体
function SelCh=Reverse(SelCh,D)
[row,col]=size(SelCh);
ObjV=PathLength(D,SelCh); %计算路径长度
SelCh1=SelCh;
for i=1:row
r1=randsrc(1,1,[1:col]);
r2=randsrc(1,1,[1:col]);
mininverse=min([r1 r2]);
maxinverse=max([r1 r2]);
SelCh1(i,mininverse:maxinverse)=SelCh1(i,maxinverse:-1:mininverse);
end
ObjV1=PathLength(D,SelCh1); %计算路径长度
index=ObjV1<ObjV;
SelCh(index,:)=SelCh1(index,:);
|
github
|
LucienVen/gd-master
|
DrawPath.m
|
.m
|
gd-master/algorithm_demo/GA/DrawPath.m
| 637 |
utf_8
|
b3eab77cf2d7da9806543d7d85ff2f93
|
%% 画路径函数
%输入
% Chrom 待画路径
% X 各城市坐标位置
function DrawPath(Chrom,X)
R=[Chrom(1,:) Chrom(1,1)]; %一个随机解(个体)
figure;
hold on
plot(X(:,1),X(:,2),'o','color',[0.5,0.5,0.5])
plot(X(Chrom(1,1),1),X(Chrom(1,1),2),'rv','MarkerSize',20)
for i=1:size(X,1)
text(X(i,1)+0.05,X(i,2)+0.05,num2str(i),'color',[1,0,0]);
end
A=X(R,:);
row=size(A,1);
for i=2:row
%坐标转换
[arrowx,arrowy] = dsxy2figxy(gca,A(i-1:i,1),A(i-1:i,2));
annotation('textarrow',arrowx,arrowy,'HeadWidth',8,'color',[0,0,1]);
end
hold off
xlabel('X')
ylabel('Y')
title('Track')
box on
|
github
|
LucienVen/gd-master
|
Mutate.m
|
.m
|
gd-master/algorithm_demo/GA/Mutate.m
| 289 |
utf_8
|
b34c58d441f4ceffd3fdbf23eda39b62
|
%% 变异操作
%输入:
%SelCh 被选择的个体
%Pm 变异概率
%输出:
% SelCh 变异后的个体
function SelCh=Mutate(SelCh,Pm)
[NSel,L]=size(SelCh);
for i=1:NSel
if Pm>=rand
R=randperm(L);
SelCh(i,R(1:2))=SelCh(i,R(2:-1:1));
end
end
|
github
|
LucienVen/gd-master
|
Fitness.m
|
.m
|
gd-master/algorithm_demo/GA/Fitness.m
| 153 |
utf_8
|
feee0abaf4bf254c9cbad9e0e456053d
|
%% 适配值函数
%输入:
%个体的长度(TSP的距离)
%输出:
%个体的适应度值
function FitnV=Fitness(len)
FitnV=1./len;
|
github
|
BII-wushuang/FLLIT-master
|
intersections.m
|
.m
|
FLLIT-master/src/intersections.m
| 11,443 |
utf_8
|
ea1423b06fc1ebab4dbd147edf8c0a07
|
function [x0,y0,iout,jout] = intersections(x1,y1,x2,y2,robust)
%INTERSECTIONS Intersections of curves.
% Computes the (x,y) locations where two curves intersect. The curves
% can be broken with NaNs or have vertical segments.
%
% Example:
% [X0,Y0] = intersections(X1,Y1,X2,Y2,ROBUST);
%
% where X1 and Y1 are equal-length vectors of at least two points and
% represent curve 1. Similarly, X2 and Y2 represent curve 2.
% X0 and Y0 are column vectors containing the points at which the two
% curves intersect.
%
% ROBUST (optional) set to 1 or true means to use a slight variation of the
% algorithm that might return duplicates of some intersection points, and
% then remove those duplicates. The default is true, but since the
% algorithm is slightly slower you can set it to false if you know that
% your curves don't intersect at any segment boundaries. Also, the robust
% version properly handles parallel and overlapping segments.
%
% The algorithm can return two additional vectors that indicate which
% segment pairs contain intersections and where they are:
%
% [X0,Y0,I,J] = intersections(X1,Y1,X2,Y2,ROBUST);
%
% For each element of the vector I, I(k) = (segment number of (X1,Y1)) +
% (how far along this segment the intersection is). For example, if I(k) =
% 45.25 then the intersection lies a quarter of the way between the line
% segment connecting (X1(45),Y1(45)) and (X1(46),Y1(46)). Similarly for
% the vector J and the segments in (X2,Y2).
%
% You can also get intersections of a curve with itself. Simply pass in
% only one curve, i.e.,
%
% [X0,Y0] = intersections(X1,Y1,ROBUST);
%
% where, as before, ROBUST is optional.
% Version: 2.0, 25 May 2017
% Author: Douglas M. Schwarz
% Email: dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
% Real_email = regexprep(Email,{'=','*'},{'@','.'})
% Theory of operation:
%
% Given two line segments, L1 and L2,
%
% L1 endpoints: (x1(1),y1(1)) and (x1(2),y1(2))
% L2 endpoints: (x2(1),y2(1)) and (x2(2),y2(2))
%
% we can write four equations with four unknowns and then solve them. The
% four unknowns are t1, t2, x0 and y0, where (x0,y0) is the intersection of
% L1 and L2, t1 is the distance from the starting point of L1 to the
% intersection relative to the length of L1 and t2 is the distance from the
% starting point of L2 to the intersection relative to the length of L2.
%
% So, the four equations are
%
% (x1(2) - x1(1))*t1 = x0 - x1(1)
% (x2(2) - x2(1))*t2 = x0 - x2(1)
% (y1(2) - y1(1))*t1 = y0 - y1(1)
% (y2(2) - y2(1))*t2 = y0 - y2(1)
%
% Rearranging and writing in matrix form,
%
% [x1(2)-x1(1) 0 -1 0; [t1; [-x1(1);
% 0 x2(2)-x2(1) -1 0; * t2; = -x2(1);
% y1(2)-y1(1) 0 0 -1; x0; -y1(1);
% 0 y2(2)-y2(1) 0 -1] y0] -y2(1)]
%
% Let's call that A*T = B. We can solve for T with T = A\B.
%
% Once we have our solution we just have to look at t1 and t2 to determine
% whether L1 and L2 intersect. If 0 <= t1 < 1 and 0 <= t2 < 1 then the two
% line segments cross and we can include (x0,y0) in the output.
%
% In principle, we have to perform this computation on every pair of line
% segments in the input data. This can be quite a large number of pairs so
% we will reduce it by doing a simple preliminary check to eliminate line
% segment pairs that could not possibly cross. The check is to look at the
% smallest enclosing rectangles (with sides parallel to the axes) for each
% line segment pair and see if they overlap. If they do then we have to
% compute t1 and t2 (via the A\B computation) to see if the line segments
% cross, but if they don't then the line segments cannot cross. In a
% typical application, this technique will eliminate most of the potential
% line segment pairs.
% Input checks.
if verLessThan('matlab','7.13')
error(nargchk(2,5,nargin)) %#ok<NCHKN>
else
narginchk(2,5)
end
% Adjustments based on number of arguments.
switch nargin
case 2
robust = true;
x2 = x1;
y2 = y1;
self_intersect = true;
case 3
robust = x2;
x2 = x1;
y2 = y1;
self_intersect = true;
case 4
robust = true;
self_intersect = false;
case 5
self_intersect = false;
end
% x1 and y1 must be vectors with same number of points (at least 2).
if sum(size(x1) > 1) ~= 1 || sum(size(y1) > 1) ~= 1 || ...
length(x1) ~= length(y1)
error('X1 and Y1 must be equal-length vectors of at least 2 points.')
end
% x2 and y2 must be vectors with same number of points (at least 2).
if sum(size(x2) > 1) ~= 1 || sum(size(y2) > 1) ~= 1 || ...
length(x2) ~= length(y2)
error('X2 and Y2 must be equal-length vectors of at least 2 points.')
end
% Force all inputs to be column vectors.
x1 = x1(:);
y1 = y1(:);
x2 = x2(:);
y2 = y2(:);
% Compute number of line segments in each curve and some differences we'll
% need later.
n1 = length(x1) - 1;
n2 = length(x2) - 1;
xy1 = [x1 y1];
xy2 = [x2 y2];
dxy1 = diff(xy1);
dxy2 = diff(xy2);
% Determine the combinations of i and j where the rectangle enclosing the
% i'th line segment of curve 1 overlaps with the rectangle enclosing the
% j'th line segment of curve 2.
% Original method that works in old MATLAB versions, but is slower than
% using binary singleton expansion (explicit or implicit).
% [i,j] = find( ...
% repmat(mvmin(x1),1,n2) <= repmat(mvmax(x2).',n1,1) & ...
% repmat(mvmax(x1),1,n2) >= repmat(mvmin(x2).',n1,1) & ...
% repmat(mvmin(y1),1,n2) <= repmat(mvmax(y2).',n1,1) & ...
% repmat(mvmax(y1),1,n2) >= repmat(mvmin(y2).',n1,1));
% Select an algorithm based on MATLAB version and number of line
% segments in each curve. We want to avoid forming large matrices for
% large numbers of line segments. If the matrices are not too large,
% choose the best method available for the MATLAB version.
if n1 > 1000 || n2 > 1000 || verLessThan('matlab','7.4')
% Determine which curve has the most line segments.
if n1 >= n2
% Curve 1 has more segments, loop over segments of curve 2.
ijc = cell(1,n2);
min_x1 = mvmin(x1);
max_x1 = mvmax(x1);
min_y1 = mvmin(y1);
max_y1 = mvmax(y1);
for k = 1:n2
k1 = k + 1;
ijc{k} = find( ...
min_x1 <= max(x2(k),x2(k1)) & max_x1 >= min(x2(k),x2(k1)) & ...
min_y1 <= max(y2(k),y2(k1)) & max_y1 >= min(y2(k),y2(k1)));
ijc{k}(:,2) = k;
end
ij = vertcat(ijc{:});
i = ij(:,1);
j = ij(:,2);
else
% Curve 2 has more segments, loop over segments of curve 1.
ijc = cell(1,n1);
min_x2 = mvmin(x2);
max_x2 = mvmax(x2);
min_y2 = mvmin(y2);
max_y2 = mvmax(y2);
for k = 1:n1
k1 = k + 1;
ijc{k}(:,2) = find( ...
min_x2 <= max(x1(k),x1(k1)) & max_x2 >= min(x1(k),x1(k1)) & ...
min_y2 <= max(y1(k),y1(k1)) & max_y2 >= min(y1(k),y1(k1)));
ijc{k}(:,1) = k;
end
ij = vertcat(ijc{:});
i = ij(:,1);
j = ij(:,2);
end
elseif verLessThan('matlab','9.1')
% Use bsxfun.
[i,j] = find( ...
bsxfun(@le,mvmin(x1),mvmax(x2).') & ...
bsxfun(@ge,mvmax(x1),mvmin(x2).') & ...
bsxfun(@le,mvmin(y1),mvmax(y2).') & ...
bsxfun(@ge,mvmax(y1),mvmin(y2).'));
else
% Use implicit expansion.
[i,j] = find( ...
mvmin(x1) <= mvmax(x2).' & mvmax(x1) >= mvmin(x2).' & ...
mvmin(y1) <= mvmax(y2).' & mvmax(y1) >= mvmin(y2).');
end
% Find segments pairs which have at least one vertex = NaN and remove them.
% This line is a fast way of finding such segment pairs. We take
% advantage of the fact that NaNs propagate through calculations, in
% particular subtraction (in the calculation of dxy1 and dxy2, which we
% need anyway) and addition.
% At the same time we can remove redundant combinations of i and j in the
% case of finding intersections of a line with itself.
if self_intersect
remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2)) | j <= i + 1;
else
remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));
end
i(remove) = [];
j(remove) = [];
% Initialize matrices. We'll put the T's and B's in matrices and use them
% one column at a time. AA is a 3-D extension of A where we'll use one
% plane at a time.
n = length(i);
T = zeros(4,n);
AA = zeros(4,4,n);
AA([1 2],3,:) = -1;
AA([3 4],4,:) = -1;
AA([1 3],1,:) = dxy1(i,:).';
AA([2 4],2,:) = dxy2(j,:).';
B = -[x1(i) x2(j) y1(i) y2(j)].';
% Loop through possibilities. Trap singularity warning and then use
% lastwarn to see if that plane of AA is near singular. Process any such
% segment pairs to determine if they are colinear (overlap) or merely
% parallel. That test consists of checking to see if one of the endpoints
% of the curve 2 segment lies on the curve 1 segment. This is done by
% checking the cross product
%
% (x1(2),y1(2)) - (x1(1),y1(1)) x (x2(2),y2(2)) - (x1(1),y1(1)).
%
% If this is close to zero then the segments overlap.
% If the robust option is false then we assume no two segment pairs are
% parallel and just go ahead and do the computation. If A is ever singular
% a warning will appear. This is faster and obviously you should use it
% only when you know you will never have overlapping or parallel segment
% pairs.
if robust
overlap = false(n,1);
warning_state = warning('off','MATLAB:singularMatrix');
% Use try-catch to guarantee original warning state is restored.
try
lastwarn('')
for k = 1:n
T(:,k) = AA(:,:,k)\B(:,k);
[unused,last_warn] = lastwarn; %#ok<ASGLU>
lastwarn('')
if strcmp(last_warn,'MATLAB:singularMatrix')
% Force in_range(k) to be false.
T(1,k) = NaN;
% Determine if these segments overlap or are just parallel.
overlap(k) = rcond([dxy1(i(k),:);xy2(j(k),:) - xy1(i(k),:)]) < eps;
end
end
warning(warning_state)
catch err
warning(warning_state)
rethrow(err)
end
% Find where t1 and t2 are between 0 and 1 and return the corresponding
% x0 and y0 values.
in_range = (T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) <= 1 & T(2,:) <= 1).';
% For overlapping segment pairs the algorithm will return an
% intersection point that is at the center of the overlapping region.
if any(overlap)
ia = i(overlap);
ja = j(overlap);
% set x0 and y0 to middle of overlapping region.
T(3,overlap) = (max(min(x1(ia),x1(ia+1)),min(x2(ja),x2(ja+1))) + ...
min(max(x1(ia),x1(ia+1)),max(x2(ja),x2(ja+1)))).'/2;
T(4,overlap) = (max(min(y1(ia),y1(ia+1)),min(y2(ja),y2(ja+1))) + ...
min(max(y1(ia),y1(ia+1)),max(y2(ja),y2(ja+1)))).'/2;
selected = in_range | overlap;
else
selected = in_range;
end
xy0 = T(3:4,selected).';
% Remove duplicate intersection points.
[xy0,index] = unique(xy0,'rows');
x0 = xy0(:,1);
y0 = xy0(:,2);
% Compute how far along each line segment the intersections are.
if nargout > 2
sel_index = find(selected);
sel = sel_index(index);
iout = i(sel) + T(1,sel).';
jout = j(sel) + T(2,sel).';
end
else % non-robust option
for k = 1:n
[L,U] = lu(AA(:,:,k));
T(:,k) = U\(L\B(:,k));
end
% Find where t1 and t2 are between 0 and 1 and return the corresponding
% x0 and y0 values.
in_range = (T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) < 1 & T(2,:) < 1).';
x0 = T(3,in_range).';
y0 = T(4,in_range).';
% Compute how far along each line segment the intersections are.
if nargout > 2
iout = i(in_range) + T(1,in_range).';
jout = j(in_range) + T(2,in_range).';
end
end
% Plot the results (useful for debugging).
% plot(x1,y1,x2,y2,x0,y0,'ok');
function y = mvmin(x)
% Faster implementation of movmin(x,k) when k = 1.
y = min(x(1:end-1),x(2:end));
function y = mvmax(x)
% Faster implementation of movmax(x,k) when k = 1.
y = max(x(1:end-1),x(2:end));
|
github
|
BII-wushuang/FLLIT-master
|
DataProcessing_New.m
|
.m
|
FLLIT-master/src/DataProcessing_New.m
| 29,995 |
utf_8
|
7ca0ff2ca117284f58bb761b4646e067
|
% Processes the raw data to extract relevant parameters
function DataProcessing_New(fps,data_dir,scale, bodylength)
if (nargin < 1)
fps = 2000;
scale=11; % dimension of arena is 11mm
data_dir = uigetdir('./Results/Tracking/');
bodylength = 2.88;
end
bodylength = bodylength * 512 / scale;
try
addpath('./Export-Fig');
catch
end
pixel_mm = 11/512; % 1 pixel corresponds to how many mm
frame_ms = 1000/fps; % 1 frame corresponds to how many ms
pos_bs = strfind(data_dir,'Results');
sub_dir = data_dir(pos_bs(end)+length('Results/Tracking/'):length(data_dir));
output_dir = ['./Results/Tracking/' sub_dir '/'];
seg_dir = ['./Results/SegmentedImages/' sub_dir '/'];
load([output_dir 'trajectory.mat']);
load([output_dir 'norm_trajectory.mat']);
load([output_dir 'CoM.mat']);
%trajectory(:,:,2) = -trajectory(:,:,2);
norm_trajectory(:,:,2) = -norm_trajectory(:,:,2);
nlegs = size(trajectory,2);
if (nlegs == 6)
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1];
else
legs_id = {'L1', 'L2', 'L3', 'L4', 'R1', 'R2', 'R3', 'R4'};
colors = [1 0 0; 0 1 0; 0 0 1; 1 0 0.5; 1 1 0; 1 0 1; 0 1 1; 1 0.5 0];
end
start = zeros(nlegs,1);
missing = zeros(nlegs,1);
for j = 1:nlegs
if (isempty(find(trajectory(:,j,1),1)))
missing(j) = 1;
continue;
end
start(j) = find(trajectory(:,j,1),1);
end
startframe = max(start);
endframe = length(CoM);
nframes = endframe - startframe + 1;
dist = zeros(endframe,1);
x = zeros(endframe, nlegs);
y = zeros(endframe, nlegs);
nx = zeros(endframe, nlegs);
ny = zeros(endframe, nlegs);
% body length
try
img = imread([seg_dir 'roi_' num2str(1) '.png']);
body_length = zeros(nframes,1);
for i = startframe : endframe
img = imread([seg_dir 'roi_' num2str(i) '.png']);
img_norm = imtranslate(img, [255 - CoM(i,1), 255 - CoM(i,2)]);
img_norm = imrotate(img_norm, CoM(i,3));
img_norm = imcrop(img_norm, [size(img_norm,1)/2-150 size(img_norm,2)/2-150 300 300]);
[Y,X] = find(img_norm);
body_length(i-startframe+1) = max(Y(find(X==150)))-min(Y(find(X==150)));
end
fileID = fopen([output_dir 'bodylength.xlsx'],'w');
fprintf(fileID, '%s\t\n', 'Mean body length (mm)');
fprintf(fileID, '%d\n\n', mean(body_length)*scale/512);
fprintf(fileID, '%s\t%s\t\n', 'Frame #', 'Length (mm)');
fclose(fileID);
dlmwrite([output_dir 'bodylength.xlsx'],[(startframe:endframe)', body_length*scale/512],'delimiter','\t','-append');
catch
end
for j =1:nlegs
if(missing(j))
continue;
end
nonzero = find(trajectory(:,j,1));
for i = startframe : endframe
if (trajectory(i,j,1) ~= 0)
x(i,j) = trajectory(i,j,1);
y(i,j) = trajectory(i,j,2);
nx(i,j) = norm_trajectory(i,j,1);
ny(i,j) = norm_trajectory(i,j,2);
else
previdx = nonzero(find(nonzero<i, 1));
nextidx = nonzero(find(nonzero>i, 1));
if (~isempty(nextidx))
x(i,j) = trajectory(previdx,j,1) + (i-previdx)/(nextidx-previdx) * (trajectory(nextidx,j,1) - trajectory(previdx,j,1));
y(i,j) = trajectory(previdx,j,2) + (i-previdx)/(nextidx-previdx) * (trajectory(nextidx,j,2) - trajectory(previdx,j,2));
nx(i,j) = norm_trajectory(previdx,j,1) + (i-previdx)/(nextidx-previdx) * (norm_trajectory(nextidx,j,1) - norm_trajectory(previdx,j,1));
ny(i,j) = norm_trajectory(previdx,j,2) + (i-previdx)/(nextidx-previdx) * (norm_trajectory(nextidx,j,2) - norm_trajectory(previdx,j,2));
else
x(i,j) = x(i-1,j);
y(i,j) = y(i-1,j);
nx(i,j) = nx(i-1,j);
ny(i,j) = ny(i-1,j);
end
end
end
end
for i = startframe : endframe
if (i == startframe)
dist(i) = 0;
else
dist(i) = dist(i-1) + (CoM(i,1) - CoM(i-1,1))*sind(CoM(i-1,3)) + (CoM(i,2) - CoM(i-1,2))*-cosd(CoM(i-1,3));
end
end
%% Locate turning points
%Finding the turning points: first use the RDP algorithm to reduce number
%of points to describe the 2D trajectory, if the turning angle at a reduced point
%is larger than a threshold (set to 50 deg), this point
%will be identified as a turning point.
reducedpoints = DouglasPeucker([CoM(startframe:endframe,1), CoM(startframe:endframe,2)],10,0);
turn_angle = zeros(length(reducedpoints)-2,1);
for i = 1 : length(reducedpoints) - 2
vec_1 = [reducedpoints(i+2,1)-reducedpoints(i+1,1), reducedpoints(i+2,2)-reducedpoints(i+1,2)];
vec_2 = [reducedpoints(i+1,1)-reducedpoints(i,1), reducedpoints(i+1,2)-reducedpoints(i,2)];
turn_angle(i) = acosd(dot(vec_1,vec_2) / (norm(vec_1)*norm(vec_2)));
end
turn_thres = 50;
turn_points_idx = find(turn_angle>turn_thres);
turn_points = zeros(length(turn_points_idx),2);
for i = 1 : length(turn_points_idx)
turn_points(i,:) = [reducedpoints(turn_points_idx(i)+1,1), reducedpoints(turn_points_idx(i)+1,2)];
turn_labels{i} = ['Turn' num2str(i) ' = (' num2str(round(turn_points(i,1))) ', ' num2str(round(turn_points(i,2))) ')'];
end
try
clf(1);
catch
end
figure(1);
scatter(CoM(startframe : endframe,1),CoM(startframe : endframe,2),'*');
title('Trajectory');
axis([0 512 0 512]);
axis square
set(gca,'Ydir','reverse')
% if (~isempty(turn_points_idx))
% labelpoints(turn_points(:,1)', turn_points(:,2)', turn_labels, 'Center');
% end
export_fig([output_dir 'BodyTrajectory.pdf'], '-pdf','-transparent');
%% Obtaining the CoM speed
i = startframe : endframe;
Distance = dist(startframe : endframe);
skip = min(nframes/2,floor(50/frame_ms));
B(1) = 0;
B(startframe+1:endframe) = diff(dist(startframe:endframe));
f = fit((startframe + skip / 2: skip: endframe - skip/2)', B(startframe + skip / 2: skip: endframe - skip/2)', 'smoothingspline', 'SmoothingParam', 0.8);
%Speedhist = hist(11000/512*f(i),(-20:0.5:50));
Speed = [[1:nframes]'*frame_ms, f(i)*pixel_mm*1000/frame_ms];
fileID = fopen([output_dir 'BodyVelocity.xlsx'],'w');
fprintf(fileID,'%s \t %s', 'Time(ms)', 'Velocity (mm/s)');
fprintf(fileID,'\n');
fclose(fileID);
dlmwrite([output_dir 'BodyVelocity.xlsx'],Speed,'delimiter','\t','-append');
clf(1);
figure(1);
hold on
Speedplot = plot(Speed(:,1),Speed(:,2));
plot(zeros(nframes,1),'--','color',[0 0 0]);
hold off
title('Body Velocity');
axis([1 nframes*frame_ms -30 60]);
Speedplot.Parent.XLabel.String = 'Time(ms)';
Speedplot.Parent.YLabel.String = 'Velocity (mm/s)';
export_fig([output_dir 'BodyVelocity.pdf'], '-pdf','-transparent');
% Speedhistplot = plot(Speedhist);
% title('Histogram of Drosophila Velocity');
% Speedhistplot.Parent.XLabel.String = 'Velocity';
% Speedhistplot.Parent.YLabel.String = '# Occurence';
% export_fig([output_dir 'HistogramVelocity.pdf'], '-pdf','-transparent');
%% Leg Speed and Gait
legspd = zeros(nframes,nlegs);
nlegspd = zeros(nframes,nlegs);
legsy = zeros(nframes,nlegs);
gait = zeros(nframes,nlegs);
ngait = zeros(nframes,nlegs);
foot_dragging = zeros(nframes,nlegs);
i = startframe : endframe;
clf(1);
figure(1);
for j = 1:nlegs
% Speed in arena-centered frame of reference
displacement(startframe: endframe)=sqrt(x(startframe: endframe,j).^2+y(startframe: endframe,j).^2);
for k = startframe:endframe
if (k==startframe)
spd(k,j) = 0;
else
spd(k,j) = sqrt((x(k,j)-x(k-1,j))^2+(y(k,j)-y(k-1,j))^2);
end
end
f = fit((startframe: 10: endframe)', spd(startframe: 10: endframe,j), 'smoothingspline', 'SmoothingParam', 1);
legspd(:, j) = abs(f(i))*pixel_mm*1000/frame_ms;
% Vertical leg trajectories in body-centred frame of reference
f = fit((startframe: 10: endframe)', ny(startframe: 10: endframe,j), 'smoothingspline', 'SmoothingParam', 0.95);
legsy(:, j) = f(i);
hold on
subplot(2, round(nlegs/2), j);
plot(legsy(:,j));
title(legs_id{j});
axis([1 nframes -150 150]);
hold off
% Gait coordination
skip = floor(10 / frame_ms);
g = fit((startframe: skip: endframe)', x(startframe: skip: endframe,j), 'smoothingspline', 'SmoothingParam', 1);
h = fit((startframe: skip: endframe)', y(startframe: skip: endframe,j), 'smoothingspline', 'SmoothingParam', 1);
gait_idx = find(abs(gradient(g(i)))>0.3*frame_ms | abs(gradient(h(i)))>0.3*frame_ms);
% gait_idx = find(legspd(:,j)>mean(legspd(:,j))/3);
gait(gait_idx,j) = 1;
ng = fit((startframe: skip: endframe)', nx(startframe: skip: endframe,j), 'smoothingspline', 'SmoothingParam', 1);
nh = fit((startframe: skip: endframe)', ny(startframe: skip: endframe,j), 'smoothingspline', 'SmoothingParam', 1);
ngait_idx = find(abs(gradient(ng(i)))>0.2*frame_ms | abs(gradient(nh(i)))>0.2*frame_ms);
ngait(ngait_idx,j) = 1;
thres = 15/frame_ms;
cc = bwconncomp(gait(:,j));
for k = 1 : cc.NumObjects
if cellfun(@length,cc.PixelIdxList(k))<thres
gait(cc.PixelIdxList{k},j) = 0;
end
end
cc = bwconncomp(~gait(:,j));
for k = 1 : cc.NumObjects
if cellfun(@length,cc.PixelIdxList(k))<thres
gait(cc.PixelIdxList{k},j) = 1;
end
end
cc = bwconncomp(ngait(:,j));
for k = 1 : cc.NumObjects
if cellfun(@length,cc.PixelIdxList(k))<thres
ngait(cc.PixelIdxList{k},j) = 0;
end
end
cc = bwconncomp(~ngait(:,j));
for k = 1 : cc.NumObjects
if cellfun(@length,cc.PixelIdxList(k))<thres
ngait(cc.PixelIdxList{k},j) = 1;
end
end
% Foot dragging is identified as an event where the leg is moving with
% respect to the arena yet relatively stationary with respect to the
% body. The episode must last a minimum of 20ms.
foot_dragging(:,j) = ~ngait(:,j).*gait(:,j);
cc = bwconncomp(foot_dragging(:,j));
for k = 1 : cc.NumObjects
if cellfun(@length,cc.PixelIdxList(k))<20/frame_ms
foot_dragging(cc.PixelIdxList{k},j) = 0;
end
end
clear connComp;
end
mtit('Vertical leg trajectories in body-centred frame of reference','xoff',0,'yoff',.04);
export_fig([output_dir 'LegVerticalTrajectories.pdf'], '-pdf','-transparent');
% legspd = legspd.*gait;
fileID = fopen([output_dir 'LegSpeed.xlsx'],'w');
fprintf(fileID,'%s \t %s \t', 'Time(ms)', legs_id{:});
fprintf(fileID,'\n');
fclose(fileID);
dlmwrite([output_dir 'LegSpeed.xlsx'],[[1:nframes]'*frame_ms, legspd],'delimiter','\t','-append');
% fileID = fopen([output_dir 'FootDragging.xlsx'],'w');
% fprintf(fileID,'%s \t %s \t %s \n', 'Leg', 'StartFrame', 'EndFrame');
% for j = 1 : nlegs
% cc = bwconncomp(foot_dragging(:,j));
% if(cc.NumObjects>0)
% fprintf(fileID,'%s', legs_id{j});
% for k = 1 : cc.NumObjects
% fprintf(fileID,'\t %d \t %d \n', min(cc.PixelIdxList{k}), max(cc.PixelIdxList{k}));
% end
% end
% end
% fclose(fileID);
clf(1);
figure(1);
colormap('jet');
clims = [0 200];
Gaitplot = imagesc([1 nframes*frame_ms], [1 nlegs], abs(legspd)', clims);
colorbar;
title('Gait and Speed');
Gaitplot.Parent.YTickLabel = legs_id;
Gaitplot.Parent.XLabel.String = 'Time(ms)';
export_fig([output_dir 'Gait.pdf'], '-pdf','-transparent');
%% Gait index
if (nlegs ==6)
gaitindex = zeros(nframes,1);
for i = 1:nframes
if isequal(gait(i,:),[1 0 1 0 1 0]) || isequal(gait(i,:),[0 1 0 1 0 1])
gaitindex(i) = 1;
continue;
elseif isequal(gait(i,:),[1 0 0 0 1 0]) || isequal(gait(i,:),[0 1 0 1 0 0 0]) || isequal(gait(i,:),[1 0 0 0 0 1]) || isequal(gait(i,:),[0 0 1 1 0 0]) || isequal(gait(i,:),[0 1 0 0 0 1]) || isequal(gait(i,:),[0 0 1 0 1 0])
gaitindex(i) = -1;
end
end
% Gait index averaged over a moving window of 80ms
gaitindex = movmean(gaitindex,80/frame_ms);
fileID = fopen([output_dir 'GaitIndex.xlsx'],'w');
fprintf(fileID,'%s \t %s', 'Time(ms)', 'Gait Index');
fprintf(fileID,'\n');
fclose(fileID);
dlmwrite([output_dir 'GaitIndex.xlsx'],[[1:nframes]'*frame_ms, gaitindex],'delimiter','\t','-append');
clf(1);
figure(1);
GaitIndexplot = plot([1:nframes]'*frame_ms, gaitindex);
title('Gait Index');
axis([0 nframes*frame_ms -1 1]);
GaitIndexplot.Parent.YLabel.String = 'Gait Index';
GaitIndexplot.Parent.XLabel.String = 'Time(ms)';
export_fig([output_dir 'GaitIndex.pdf'], '-pdf','-transparent');
end
%% Stride Parameters
fileID = fopen([output_dir 'StrideParameters.xlsx'],'w');
fclose(fileID);
landing_std = zeros(nlegs,2);
takeoff_std = zeros(nlegs,2);
landing_mean = zeros(nlegs,2);
takeoff_mean = zeros(nlegs,2);
for j = 1:nlegs
if(missing(j))
continue;
end
cc = bwconncomp(gait(:,j));
nstrides(j) = cc.NumObjects;
if(nstrides(j)==0)
fileID = fopen([output_dir 'StrideParameters.xlsx'],'a');
fprintf(fileID,'%s',legs_id{j});
fprintf(fileID,'\n');
fprintf(fileID,'%s \t', 'Stride #', 'Duration (ms)', 'Period (ms)', 'Displacement (mm)', 'Path Covered (mm)', 'Take-off time (ms)', 'Landing time (ms)', 'AEP x (mm)', 'AEP y (mm)', 'PEP x (mm)', 'PEP y (mm)', 'Amplitude (mm)', 'Stance linearity (mm)', 'Stretch (mm)');
fprintf(fileID,'\n');
fclose(fileID);
continue;
end
for k = 1 : nstrides(j)
stride_start(j,k) = min(cc.PixelIdxList{k});
stride_duration(j,k) = max(cc.PixelIdxList{k}) - min(cc.PixelIdxList{k});
stride_end(j,k) = max(cc.PixelIdxList{k});
stride_dist(j,k) = sqrt((y(startframe-1 + stride_start(j,k)+stride_duration(j,k),j) - y(startframe-1 + stride_start(j,k),j))^2+(x(startframe-1 + stride_start(j,k)+stride_duration(j,k),j) - x(startframe-1 + stride_start(j,k),j))^2);
path_length(j,k) = sum(spd(startframe-1 + stride_start(j,k):startframe-1 + stride_start(j,k)+stride_duration(j,k),j));
landing(j,k,:) = [nx(startframe-1 + stride_start(j,k)+stride_duration(j,k),j), ny(startframe-1 + stride_start(j,k)+stride_duration(j,k),j)];
takeoff(j,k,:) = [nx(startframe-1 + stride_start(j,k),j), ny(startframe-1 + stride_start(j,k),j)];
Xinter= interp1(startframe-1 + stride_start(j,k):min(20,stride_duration(j,k)-1):startframe-1 + stride_start(j,k) + stride_duration(j,k),nx(startframe-1 + stride_start(j,k):min(20,stride_duration(j,k)-1):startframe-1 + stride_start(j,k)+stride_duration(j,k),j),startframe-1+stride_start(j,k):startframe-1+stride_start(j,k)+stride_duration(j,k),'spline');
Yinter= interp1(startframe-1 + stride_start(j,k):min(20,stride_duration(j,k)-1):startframe-1 + stride_start(j,k) + stride_duration(j,k),ny(startframe-1 + stride_start(j,k):min(20,stride_duration(j,k)-1):startframe-1 + stride_start(j,k)+stride_duration(j,k),j),startframe-1+stride_start(j,k):startframe-1+stride_start(j,k)+stride_duration(j,k),'spline');
stride_amplitude(j,k) = ny(startframe-1 + stride_start(j,k)+stride_duration(j,k),j) - ny(startframe-1 + stride_start(j,k),j);
stride_regularity(j,k) = mean(sqrt(sum(abs([nx(startframe-1+stride_start(j,k):startframe-1+stride_start(j,k)+stride_duration(j,k),j), ny(startframe-1+stride_start(j,k):startframe-1+stride_start(j,k)+stride_duration(j,k),j)] - [Xinter' Yinter']).^2,2)));
stretch(j,k) = mean(sqrt(sum(nx(startframe-1+stride_start(j,k)+round(stride_duration(j,k)/2),j)^2+(ny(startframe-1+stride_start(j,k)+round(stride_duration(j,k)/2),j)-0.157*bodylength)^2)));
end
for k = 1 : nstrides(j)-1
stride_period(j,k) = stride_start(j,k+1) - stride_start(j,k);
end
if (nstrides(j)>1)
mean_stride_period(j) = sum(stride_period(j,:))/(nstrides(j)-1);
else
stride_period(j,1) = nan;
mean_stride_period(j) = nan;
end
stride_period(j,nstrides(j)) = nan;
landing_std(j,:) = squeeze(std(landing(j,1 : nstrides(j),:)))';
takeoff_std(j,:) = squeeze(std(takeoff(j,1 : nstrides(j),:)))';
landing_mean(j,:) = squeeze(sum(landing(j,:,:)))'/nstrides(j);
takeoff_mean(j,:) = squeeze(sum(takeoff(j,:,:)))'/nstrides(j);
l_std(j) = 0;
t_std(j) = 0;
for k = 1: nstrides(j)
l_std(j) = l_std(j) + sqrt((landing(j,k,1)-landing_mean(j,1))^2 + (landing(j,k,2)-landing_mean(j,2))^2);
t_std(j) = t_std(j) + sqrt((takeoff(j,k,1)-takeoff_mean(j,1))^2 + (takeoff(j,k,2)-takeoff_mean(j,2))^2);
end
l_std(j) = l_std(j) / nstrides(j);
t_std(j) = t_std(j) / nstrides(j);
total_path_length(j) = sum(path_length(j,:));
mov_percentage(j) = sum(stride_duration(j,:))/nframes;
fileID = fopen([output_dir 'StrideParameters.xlsx'],'a');
fprintf(fileID,'%s',legs_id{j});
fprintf(fileID,'\n');
fprintf(fileID,'%s \t', 'Stride #', 'Duration (ms)', 'Period (ms)', 'Displacement (mm)', 'Path Covered (mm)', 'Take-off time (ms)', 'Landing time (ms)', 'AEP x (mm)', 'AEP y (mm)', 'PEP x (mm)', 'PEP y (mm)', 'Amplitude (mm)', 'Stance linearity (mm)', 'Stretch (mm)');
fprintf(fileID,'\n');
fclose(fileID);
dlmwrite([output_dir 'StrideParameters.xlsx'], [[1:nstrides(j)]' stride_duration(j,1:nstrides(j))'*frame_ms stride_period(j,1:nstrides(j))'*frame_ms stride_dist(j,1:nstrides(j))'*scale/512 path_length(j,1:nstrides(j))'*scale/512 stride_start(j,1:nstrides(j))'*frame_ms stride_end(j,1:nstrides(j))'*frame_ms landing(j,1:nstrides(j),1)'*scale/512 landing(j,1:nstrides(j),2)'*scale/512 takeoff(j,1:nstrides(j),1)'*scale/512 takeoff(j,1:nstrides(j),2)'*scale/512 stride_amplitude(j,1:nstrides(j))'*scale/512 stride_regularity(j,1:nstrides(j))'*scale/512 stretch(j,1:nstrides(j))'*scale/512],'delimiter','\t','-append');
fileID = fopen([output_dir 'StrideParameters.xlsx'],'a');
fprintf(fileID,'\n');
fclose(fileID);
dlmwrite([output_dir 'StrideParameters.xlsx'], ['______________'],'delimiter','\t','-append');
end
%% Path area covered
% Returns the area of the minimum convex hull required to cover the entire
% path covered by each leg in the body-centered frame of reference
area = zeros(nlegs,1);
area_over_path = zeros(nlegs,1);
pathpca = zeros(nlegs,2,2);
centre = zeros(nlegs, 2);
fileID = fopen([output_dir 'LegParameters.xlsx'],'w');
% fprintf(fileID,'%s \t', 'Leg', 'Movement %', 'Mean Stride Period (ms)', 'Total Path Covered (mm)', 'Mean Landing x (mm)', 'Mean Landing y (mm)', 'Mean Take-off x (mm)', 'Mean Take-off y (mm)', 'Std Landing x (mm)', 'Std Landing y (mm)', 'Std Take-off x (mm)', 'Std Take-off y (mm)', 'Domain Area (mm^2)', 'Domain Area / Path (mm)', 'Domain Length (mm)', 'Domain Width (mm)', 'Footprint/PCA deviation (deg)');
fprintf(fileID,'%s \t', 'Leg', 'Movement %', 'Mean Stride Period (ms)', 'Total Path Covered (mm)', 'Mean AEP x (mm)', 'Mean AEP y (mm)', 'Mean PEP x (mm)', 'Mean PEP y (mm)', 'Std AEP (mm)', 'Std PEP (mm)', 'Domain Area (mm^2)', 'Domain Area / Path (mm)', 'Domain Length (mm)', 'Domain Width (mm)', 'Footprint/PCA deviation (deg)');
fprintf(fileID,'\n');
clf(1);
figure(1);
for j = 1:nlegs
if(missing(j) || nstrides(j)==0)
continue;
end
[convex{j},area(j)] = convhull(nx(startframe : endframe,j),ny(startframe : endframe,j));
area_over_path(j) = area(j)/total_path_length(j);
centre(j,:) = mean([nx(startframe : endframe,j),ny(startframe : endframe,j)]);
[domain_length(j), domain_width(j)] = projectpca([nx(startframe : endframe,j),ny(startframe : endframe,j)]);
bounding = boundary(nx(startframe : endframe,j),ny(startframe : endframe,j));
bounding = mod(bounding,nframes)+((mod(bounding,nframes)==0)*nframes)+startframe-1;
hold on
legplot(j) = scatter(nx(startframe : endframe,j),ny(startframe : endframe,j),3,[colors(j,1) colors(j,2) colors(j,3)],'filled');
landingplot(j) = scatter(landing_mean(j,1),landing_mean(j,2),50,[0 0 0],'filled');
takeoffplot(j) = scatter(takeoff_mean(j,1),takeoff_mean(j,2),50,[0 0 0],'d','filled');
landingplot(j) = scatter(landing_mean(j,1),landing_mean(j,2),30,[colors(j,1) colors(j,2) colors(j,3)],'filled');
takeoffplot(j) = scatter(takeoff_mean(j,1),takeoff_mean(j,2),30,[colors(j,1) colors(j,2) colors(j,3)],'d','filled');
% plot(nx(bounding,j),ny(bounding,j));
k = -100:100;
stride_vec = [landing_mean(j,1)-takeoff_mean(j,1) landing_mean(j,2)-takeoff_mean(j,2)];
stride_vec = stride_vec/norm(stride_vec);
footprint_dev(j) = acos(stride_vec(1)*pathpca(j,1,1) + stride_vec(2)*pathpca(j,1,2))*180/pi;
hold off
fprintf(fileID,'%s',legs_id{j});
fprintf(fileID,'\t %0.2f', [100*mov_percentage(j) mean_stride_period(j)*frame_ms total_path_length(j)*scale/512 landing_mean(j,1)*scale/512 landing_mean(j,2)*scale/512 takeoff_mean(j,1)*scale/512 takeoff_mean(j,2)*scale/512 landing_std(j,1)*scale/512 landing_std(j,2)*scale/512 takeoff_std(j,1)*scale/512 takeoff_std(j,2)*scale/512 area(j)*scale/512*scale/512 area_over_path(j)*scale/512 domain_length(j)*scale/512 domain_width(j)*scale/512 footprint_dev(j)]);
% fprintf(fileID,'\t %0.3f', [100*mov_percentage(j) mean_stride_period(j)*frame_ms total_path_length(j)*scale/512 landing_mean(j,1)*scale/512 landing_mean(j,2)*scale/512 takeoff_mean(j,1)*scale/512 takeoff_mean(j,2)*scale/512 l_std(j)*scale/512 t_std(j)*scale/512 area(j)*scale/512*scale/512 area_over_path(j)*scale/512 domain_length(j)*scale/512 domain_width(j)*scale/512 footprint_dev(j)]);
fprintf(fileID,'\n');
end
fclose(fileID);
axis([-150 150 -150 150]);
axis square
title('Leg trajectories in body-centered frame of reference');
export_fig([output_dir 'LegDomain.pdf'], '-pdf','-transparent');
fileID = fopen([output_dir 'LegDomainOverlap.xlsx'],'w');
for j = 1:nlegs
if(missing(j) || nstrides(j)==0)
continue;
end
for k = j+1:nlegs
if(missing(k) || nstrides(k)==0)
continue;
end
P1.x = nx(convex{j}+startframe-1,j);
P1.y = ny(convex{j}+startframe-1,j);
P1.hole = 0;
P2.x = nx(convex{k}+startframe-1,k);
P2.y = ny(convex{k}+startframe-1,k);
P2.hole = 0;
if(isempty(intersections(P1.x,P1.y,P2.x,P2.y)))
overlap = 0;
else
% Returns the intesersection polygon between the convex polygons for leg j and k
C = PolygonClip(P1,P2,1);
overlap = polyarea(C.x,C.y) * (scale/512)^2;
end
fprintf(fileID,'%s \t %0.3f \n', ['Overlap ' legs_id{j} '&' legs_id{k}], overlap);
end
end
fclose(fileID);
%% Estimate leg lengths
% imroi = imread([seg_dir 'roi_' num2str(1) '.png']);
% imsize = size(imroi);
% leglengths = zeros(endframe-startframe+1,nlegs);
%
% for i = startframe:endframe;
% imroi = imread([seg_dir 'roi_' num2str(i) '.png']);
% imseg = imread([seg_dir 'img_' num2str(i) '.png']);
% imlegs = imseg(:,:,1)==255;
% imbody = imroi-imlegs;
% legs = bwconncomp(imlegs);
% idxlegs = zeros(nlegs,2);
% idxconncomp = zeros(nlegs,1);
% for b = 1 : legs.NumObjects
% imglegs{b} = zeros(imsize);
% imglegs{b}(legs.PixelIdxList{b})=1;
% end
% for j = 1:nlegs
% overallMinDistance = inf;
% for b = 1 : legs.NumObjects
% [legY, legX] = ind2sub(imsize, legs.PixelIdxList{b});
% distances = sqrt((legX - x(i,j)).^2 + (legY - y(i,j)).^2);
% [minDistance, indexOfMin] = min(distances);
% if minDistance < overallMinDistance
% overallMinDistance = minDistance;
% idxlegs(j,:) = [legX(indexOfMin), legY(indexOfMin)];
% idxconncomp(j) = b;
% end
% end
% D = bwdistgeodesic(imbody+imglegs{idxconncomp(j)}>0,[idxlegs(j,1)], [idxlegs(j,2)],'quasi-euclidean');
% leglengths(i-startframe+1,j) = D(round(CoM(i,2)+0.2*body_length),round(CoM(i,1)));
% end
%
% % geodesic distance between middle legs
% D = bwdistgeodesic(imbody+imglegs{idxconncomp(2)}+imglegs{idxconncomp(5)}>0,[idxlegs(2,1)], [idxlegs(2,2)],'quasi-euclidean');
% middlelegs_dist(i-startframe+1) = D(idxlegs(5,2),idxlegs(5,1));
% % horizontal spread distance across middle legs
% if (norm_trajectory(i-startframe+1,2,1)~=0 && norm_trajectory(i-startframe+1,5,1)~=0)
% middlelegs_spread(i-startframe+1) = abs(norm_trajectory(i-startframe+1,2,1) -norm_trajectory(i-startframe+1,5,1));
% else
% middlelegs_spread(i-startframe+1) = nan;
% end
% end
% leglengths2 = leglengths;
% leglengths2(find(isnan(leglengths))) = 0;
% leglengths2(find(isinf(leglengths))) = 0;
% fileID = fopen([output_dir 'Leglengths.xlsx'],'w');
% for j = 1: nlegs
% fprintf(fileID,'\t%s',legs_id{j});
% end
% fprintf(fileID,'\n');
% fprintf(fileID, '%s\t', 'Mean (mm)');
% fclose(fileID);
% mean_ll = zeros (1, nlegs);
% std_ll = zeros (1, nlegs);
% for j = 1 : nlegs
% A = leglengths2(:,j);
% mean_ll(j) = mean(A(A>0));
% std_ll(j) = std(A(A>0));
% end
% dlmwrite([output_dir 'Leglengths.xlsx'],mean_ll*scale/512,'delimiter','\t','-append');
% fileID = fopen([output_dir 'Leglengths.xlsx'],'a');
% fprintf(fileID,'\n');
% fprintf(fileID, '%s\t', 'Std (mm)');
% fclose(fileID);
% dlmwrite([output_dir 'Leglengths.xlsx'],std_ll*scale/512,'delimiter','\t','-append');
% fileID = fopen([output_dir 'Leglengths.xlsx'],'a');
% fprintf(fileID,'\n');
% fprintf(fileID,'Frame #\n');
% fclose(fileID);
% dlmwrite([output_dir 'Leglengths.xlsx'],[(startframe:endframe)', leglengths*scale/512],'delimiter','\t','-append');
%
% middlelegsAEP = sqrt((landing_mean(2,1)-landing_mean(5,1))^2+(landing_mean(2,2)-landing_mean(5,2))^2);
% middlelegsPEP = sqrt((takeoff_mean(2,1)-takeoff_mean(5,1))^2+(takeoff_mean(2,2)-takeoff_mean(5,2))^2);
%
% middlelegs_dist2 = middlelegs_dist;
% middlelegs_spread2 = middlelegs_spread;
% middlelegs_dist2(find(isnan(middlelegs_dist))) = 0;
% middlelegs_dist2(find(isinf(middlelegs_dist))) = 0;
% middlelegs_spread2(find(isnan(middlelegs_spread))) = 0;
% middlelegs_spread2(find(isnan(middlelegs_spread))) = 0;
%
% fileID = fopen([output_dir 'MiddleLegsSpread.xlsx'],'w');
% fprintf(fileID, '%s\t%s\t%s\t%s\t\n', 'Mean Shortest Path Distance (mm)', 'Mean Horizontal Spread (mm)', 'Mean AEP Distance (mm)', 'Mean PEP Distance (mm)');
% fprintf(fileID, '%0.3f\t', mean(middlelegs_dist2(middlelegs_dist2>0)) * scale/512, mean(middlelegs_spread2(middlelegs_spread2>0)) * scale / 512, middlelegsAEP * scale/512, middlelegsPEP * scale/512);
% fprintf(fileID,'\n\n');
% fprintf(fileID, '%s\t', 'Frame #', 'Shortest Path Distance (mm)', 'Horizontal Spread (mm)');
% fprintf(fileID,'\n');
% fclose(fileID);
% dlmwrite([output_dir 'MiddleLegsSpread.xlsx'],[(startframe:endframe)', (middlelegs_dist*scale/512)', (middlelegs_spread*scale/512)'],'delimiter','\t','-append');
middlelegsAEP = sqrt((landing_mean(2,1)-landing_mean(5,1))^2+(landing_mean(2,2)-landing_mean(5,2))^2);
middlelegsPEP = sqrt((takeoff_mean(2,1)-takeoff_mean(5,1))^2+(takeoff_mean(2,2)-takeoff_mean(5,2))^2);
stancewidth = (middlelegsAEP + middlelegsPEP)/2;
fileID = fopen([output_dir 'StanceWidth.xlsx'],'w');
fprintf(fileID, '%s\t%s\t%s\n', 'Mean AEP Distance (mm)', 'Mean PEP Distance (mm)', 'Stance Width (mm)');
fprintf(fileID, '%0.3f\t', middlelegsAEP * scale/512, middlelegsPEP * scale/512, stancewidth * scale / 512);
fclose(fileID);
%% Estimate angle subtended by leg from vertical axis
% legangles = zeros(endframe-startframe+1,nlegs);
%
% for i = startframe:endframe
% for j = 1:3
% if (nx(i,j)==0)
% legangles(i-startframe+1,j) = nan;
% else
% legangles(i-startframe+1,j) = -mod(-atan2d(nx(i,j),ny(i,j)-0.157*bodylength)+360,360);
% end
% end
% for j = 4:6
% if (nx(i,j)==0)
% legangles(i-startframe+1,j) = nan;
% else
% legangles(i-startframe+1,j) = mod(atan2d(nx(i,j),ny(i,j)-0.157*bodylength)+360,360);
% end
% end
% end
%
% if ~exist([output_dir 'LegAngles'], 'dir')
% mkdir([output_dir 'LegAngles']);
% end
%
% fileID = fopen([output_dir 'LegAngles/LegAngles.xlsx'],'w');
% fprintf(fileID,'%s \t %s \t', 'Time(ms)', legs_id{:});
% fprintf(fileID,'\n');
% fclose(fileID);
% dlmwrite([output_dir 'LegAngles/LegAngles.xlsx'],[[1:nframes]'*frame_ms, legangles],'delimiter','\t','-append', 'precision','%.1f');
%
% PEP_angles = cell(6,1);
% AEP_angles = cell(6,1);
% angle_variations = cell(6,1);
% fileID = fopen([output_dir 'LegAngles/StrideVariation.xlsx'],'w');
% for j = 1:size(stride_start,1)
% fprintf(fileID,'%s \n', legs_id{j});
% fprintf(fileID,'%s \t', 'Stride #', 'PEP Angle', 'AEP Angle', 'Angle Swiped');
% fprintf(fileID,'\n');
% for i = 1:size(stride_start,2)
% if (stride_start(j,i)==0)
% continue;
% end
% PEP_angles{j}(i) = legangles(stride_start(j,i),j);
% AEP_angles{j}(i) = legangles(stride_end(j,i),j);
% angle_variations{j}(i) = abs(legangles(stride_end(j,i),j)-legangles(stride_start(j,i),j));
% fprintf(fileID,'%d \t', i, PEP_angles{j}(i), AEP_angles{j}(i), angle_variations{j}(i));
% fprintf(fileID,'\n');
% end
% end
% fprintf(fileID,'\n');
% fprintf(fileID,'\n');
%
% fprintf(fileID,'%s \t', 'Leg', 'Mean PEP Angle', 'Std PEP Angle', 'Mean AEP Angle', 'Std AEP Angle', 'Mean Angle Swiped', 'Std Angle Swiped');
% fprintf(fileID,'\n');
% for j = 1:nlegs
% fprintf(fileID,'%s \t %d \t', legs_id{j}, mean(PEP_angles{j}), std(PEP_angles{j}), mean(AEP_angles{j}), std(AEP_angles{j}), mean(angle_variations{j}), std(angle_variations{j}));
% fprintf(fileID,'\n');
% end
% fclose(fileID);
%% Project onto PCA eigenvectors to compute the domain length/width
function [domain_length, domain_width] = projectpca(points)
m = mean(points);
v = pca(points);
n = size(points,1);
p_v1 = zeros(n,1);
p_v2 = zeros(n,1);
for i = 1 : n
p_v1(i) = projectaxis(points(i,:), v(:,1), m);
p_v2(i) = projectaxis(points(i,:), v(:,2), m);
end
domain_length = max(p_v1) - min(p_v1);
domain_width = max(p_v2) - min(p_v2);
function p_proj = projectaxis(p, v, m, axis)
p_proj = p*v-m*v;
|
github
|
BII-wushuang/FLLIT-master
|
Segmentation.m
|
.m
|
FLLIT-master/src/Segmentation.m
| 8,894 |
utf_8
|
89de5a8eba5bbe2e49b22b847761cc93
|
%Classifier for leg segmentation
function Segmentation (data_dir,score_thres,foreground_thres,load_wl)
%% locate the image folders and the output folders
if (nargin < 1)
load_wl = 1;
score_thres = 0.65;
foreground_thres = 0.1;
data_dir = uigetdir('./Data');
addpath(genpath('./KernelBoost-v0.1/'));
end
clear weak_learners;
%addpath(genpath('./KernelBoost-v0.1/'));
%fprintf('Processing the folder: %s \n',data_dir);
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
data_dir = [pwd '/Data' sub_dir '/'];
output_dir = [pwd '/Results/SegmentedImages' sub_dir '/'];
if(~exist(output_dir))
mkdir(output_dir);
end
img_list = load_img_list(data_dir);
I = imread([data_dir img_list(1).name]);
%% Call the background
if(~exist([data_dir 'Background/Background.png']))
[~,~,ref_img,~] = video2background(data_dir, sub_dir);
if(~exist([data_dir 'Background']))
mkdir([data_dir 'Background'])
end
imwrite(uint8(ref_img),[data_dir 'Background/Background.png'], 'png');
else
ref_img = double(imread([data_dir 'Background/Background.png']));
end
imshow(uint8(ref_img));
pause(2);
for i = 1 : length(img_list)
I = imread([data_dir img_list(i).name]);
I = double(I);
roi_img = (max(ref_img - I(:,:,1),0) ./ ref_img) > foreground_thres;
roi_img = bwareaopen(roi_img, 200);
img_output = repmat(I/255,[1 1 3]);
img_output(:,:,3) = img_output(:,:,3) + roi_img;
imshow(img_output);
pause(0.01);
imwrite(roi_img,[output_dir 'roi_' num2str(i) '.png'],'png');
end
%% Another section
ref_img = imread([data_dir 'Background/Background.png']);
ref_img = double(ref_img);
ref_img = padarray(ref_img,[20 20],'replicate');
params = setup_config_L('Drive');
%params = setup_lists(params);
%params = setup_directories_L(params);
params.border_skip_size = 20;
params.pos_samples_no = 30000;
params.neg_samples_no = 30000;
params.sample_size = [41 41]';
if (load_wl)
fprintf('Please select the trained classifier to be used.\n');
[wl_file, wl_dir] = uigetfile([pwd '/Results/Classifiers/','*.mat']);
load([wl_dir wl_file]);
else
if(~exist([pwd '/Results/Classifiers' sub_dir '_Classifier.mat']))
sample_ratio = 20;
tot_idx.pos = 0;
tot_idx.neg = 0;
data = [];
% Collect the positive and negative samples
for i_img = 1 : floor(length(img_list) / sample_ratio)
I = imread([data_dir img_list(i_img * sample_ratio).name]);
I = double(I);
I = padarray(I,[20 20],'replicate');
[pos_img,neg_img_body,neg_img_bkg] = leg_segment(I,ref_img,foreground_thres);
show_img_output = repmat(I/255,[1 1 3]);
show_img_output(:,:,1) = show_img_output(:,:,1) + pos_img;
show_img_output(:,:,3) = show_img_output(:,:,3) + neg_img_body;
imshow(show_img_output,[]);
data.train.imgs.X{i_img,1} = I / 255;
data.train.imgs.X{i_img,2} = (ref_img - I) / 255;
gt_img = zeros(size(I));
gt_img(pos_img > 0) = 1;
gt_img(neg_img_body > 0) = -1;
gt_img(neg_img_bkg > 0) = -1;
data.train.gts.X{i_img} = gt_img;
% ------------------------------
border_img = zeros(size(I));
border_img(1:params.border_skip_size,:) = 1;
border_img(:,1:params.border_skip_size) = 1;
border_img((end-params.border_skip_size):end,:) = 1;
border_img(:,(end-params.border_skip_size):end) = 1;
pos_sampling = find((pos_img) & (~border_img) & (~neg_img_body));
neg_body_sampling = find(neg_img_body & (~border_img) & (~pos_img));
neg_bkg_sampling = find(neg_img_bkg & (~border_img));
% sample counts
imgs_no = floor(length(img_list) / sample_ratio);
npos_img = ceil(params.pos_samples_no / imgs_no);
nneg_img = ceil(params.neg_samples_no / imgs_no);
% getting a random subset?
neg_sampling = neg_body_sampling(randi(length(neg_body_sampling),[nneg_img,1]));
neg_sampling = [neg_sampling; neg_bkg_sampling(randi(length(neg_bkg_sampling),[nneg_img,1]))];
npos = length(pos_sampling);
nneg = length(neg_sampling);
good_sampling_idx{i_img}.pos = pos_sampling(randi(npos,[max(npos_img,nneg_img),1]));
good_sampling_idx{i_img}.neg = neg_sampling(randi(nneg,[max(npos_img,nneg_img),1]));
good_sampling_idx{i_img}.pos_val = pos_img(good_sampling_idx{i_img}.pos);
good_sampling_idx{i_img}.neg_val = pos_img(good_sampling_idx{i_img}.neg);
tot_idx.pos = tot_idx.pos+length(good_sampling_idx{i_img}.pos);
tot_idx.neg = tot_idx.neg+length(good_sampling_idx{i_img}.neg);
end
data.train.imgs.idxs = 1:2;
data.train.imgs.sub_ch_no = 2;
samples_idx = [];
for i_img = 1 : floor(length(img_list) / sample_ratio)
I = imread([data_dir img_list(i_img * sample_ratio).name]);
I = padarray(I,[20 20],'replicate');
samp_idx = [good_sampling_idx{i_img}.pos ; good_sampling_idx{i_img}.neg];
samp_idx_2D = zeros(length(samp_idx),2);
[samp_idx_2D(:,1),samp_idx_2D(:,2)] = ind2sub(size(I),samp_idx);
labels = [good_sampling_idx{i_img}.pos_val ; good_sampling_idx{i_img}.neg_val];
labels = double(labels);
labels(labels < 0.5) = -1;
samples_idx_img = zeros(length(samp_idx),4);
samples_idx_img(:,1) = i_img;
samples_idx_img(:,2:3) = samp_idx_2D;
samples_idx_img(:,4) = labels;
samples_idx = cat(1,samples_idx,samples_idx_img);
end
samples_idx = samples_idx(1 : (params.pos_samples_no + params.neg_samples_no),:);
params.pos_samples_no = sum(samples_idx(:,end)==1);
params.neg_samples_no = sum(samples_idx(:,end)==-1);
params.T1_size = round((params.pos_samples_no+params.neg_samples_no)/3);
params.T2_size = round((params.pos_samples_no+params.neg_samples_no)/3);
params.pos_to_sample_no = params.T1_size;
params.neg_to_sample_no = params.T1_size;
params.wl_no = 100;
fprintf('Training the classifier over a random subset of the images.\n');
% Train the classifier here
weak_learners = train_boost_general(params,data,samples_idx);
sub_dir_pos = strfind(sub_dir,'/');
if(~exist(['./Results/Classifiers/' sub_dir(1:sub_dir_pos(end))]))
mkdir(['./Results/Classifiers/' sub_dir(1:sub_dir_pos(end))]);
end
save ([pwd '/Results/Classifiers/' sub_dir '_Classifier.mat'],'weak_learners');
else
load([pwd '/Results/Classifiers/' sub_dir '_Classifier.mat']);
end
end
fprintf('Training completed, now applying the classifier to all images.\n');
fprintf('Output directory: %s\n', output_dir);
% Applying the classifier
sample_ratio = 1;
sec_no = 100;
for i_sec = 1 : ceil(length(img_list) / sample_ratio / sec_no)
X = [];
if (i_sec < ceil(length(img_list) / sample_ratio / sec_no))
imgs_sec = 1 + (i_sec - 1) * sec_no : sample_ratio :(i_sec) * sec_no;
else
imgs_sec = 1 + (i_sec - 1) * sec_no : sample_ratio : length(img_list);
end
for i_img = 1 : length(imgs_sec)
I = imread([data_dir img_list(imgs_sec(i_img)).name]);
I = double(I);
I = padarray(I,[20 20],'replicate');
%neg_img{i_img} = leg_segment_clean(I,roi_img);
bkg_sub = (ref_img - I);
I(:,:,2) = bkg_sub;
I = I / 255;
X{i_img,1} = I(:,:,1);
X{i_img,2} = I(:,:,2);
roi_img = imread([output_dir 'roi_' num2str(imgs_sec(i_img)) '.png']);
roi_images{i_img} = padarray(roi_img,[20 20],'replicate');
end
score_images = batch_evaluate_boost_images(X,params,weak_learners,roi_images);
for i_img = 1 : length(imgs_sec)
I = imread([data_dir img_list(imgs_sec(i_img)).name]);
I = double(I)/255;
I = padarray(I,[20 20],'replicate');
score_img = score_images{i_img};
est_leg = score_img > score_thres;
%est_leg = bwdist(est_leg)<3 .*roi_images{i_img};
%est_leg = est_leg & ~ neg_img{i_img} & roi_images{i_img};
est_leg = filter_small_comp(est_leg,15);
show_img_output = repmat(I,[1 1 3]);
show_img_output(:,:,1) = show_img_output(:,:,1) + est_leg;
imshow(show_img_output);
imwrite(imcrop(show_img_output,[21 21 size(I,2)-41 size(I,1)-41]),[output_dir 'img_' num2str(imgs_sec(i_img)) '.png'],'png');
end
end
|
github
|
BII-wushuang/FLLIT-master
|
FLLIT.m
|
.m
|
FLLIT-master/src/FLLIT.m
| 94,500 |
utf_8
|
d0a100d59fd1e1a11f9e0a06ec94cee3
|
% FLLIT program: GUI incorporating the program workflow
% This GUI is created with the MATLAB GUIDE feature.
% The pushbuttons call functions to perform individual tasks such as
% segmentation, tracking or data processing.
function varargout = FLLIT(varargin)
% FLLIT MATLAB code for FLLIT.fig
% FLLIT, by itself, creates a new FLLIT or raises the existing
% singleton*.
%
% H = FLLIT returns the handle to a new FLLIT or the handle to
% the existing singleton*.
%
% FLLIT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in FLLIT.M with the given input arguments.
%
% FLLIT('Property','Value',...) creates a new FLLIT or raises
% the existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before FLLIT_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to FLLIT_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help FLLIT
% Last Modified by GUIDE v2.5 04-Nov-2021 00:00:59
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @FLLIT_OpeningFcn, ...
'gui_OutputFcn', @FLLIT_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
%% --- Executes just before FLLIT is made visible.
function FLLIT_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin Command line arguments to FLLIT (see VARARGIN)
% Addpath
try
addpath(genpath('./KernelBoost-v0.1/'));
catch
end
% Choose default Command line output for FLLIT
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% 'gcf' refers to 'get current figure' and in this context all the updated
% data are feed into the 'hMainGui'. The 'hMainGui' can then provide the
% data as global variables to the other functions that are called in this GUI
setappdata(0, 'hMainGui', gcf);
S.fh = handles.figMain;
% Fix the central figure axis in pixel coordinates
S.ax = gca;
set(S.ax,'unit','pix','position',[(handles.figMain.Position(3)-512)/2 handles.figMain.Position(4)-512 512 512]);
S.XLM = get(S.ax,'xlim');
S.YLM = get(S.ax,'ylim');
S.AXP = get(S.ax,'pos');
S.DFX = diff(S.XLM);
S.DFY = diff(S.YLM);
S.tx = handles.Position_Text;
% The fh_wbmcfn function captures motion of the mouse cursor and the cursor
% location is displayed in the GUI
set(S.fh,'windowbuttonmotionfcn',{@fh_wbmfcn,S})
% The clicker function captures double clicks of the mouse and is used for
% annotating / labelling of the leg tip locations
set(handles.figMain, 'WindowButtonDownFcn', {@clicker,handles});
initialize_gui(hObject, handles, false);
%% --- Outputs from this function are returned to the Command line.
function varargout = FLLIT_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default Command line output from handles structure
varargout{1} = handles.output;
%% --------------------------------------------------------------------
function initialize_gui(fig_handle, handles, isreset)
% Update handles structure
guidata(handles.figMain, handles);
%% --- Executes on button press in Adjust_Prediction.
function Adjust_Prediction_Callback(hObject, eventdata, handles)
% hObject handle to Adjust_Prediction (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% First, obtain the global variables stored in 'hMainGui': named the
% current frame in the tracking progess as well as currently stored
% trajectory data of the legs
hMainGui = getappdata(0, 'hMainGui');
i = getappdata(hMainGui, 'current_frame');
trajectory = getappdata(hMainGui, 'trajectory');
nLegs = 8 - handles.L4.Value - handles.R4.Value;
if (nLegs > 6)
colors = [1 0 0; 0 1 0; 0 0 1; 1 0 0.5; 1 1 0; 0 1 1; 1 0 1; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3','L4', 'R1', 'R2', 'R3','R4'};
else
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1; 1 0 0.5; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
end
if (isempty(i))
% If current frame is empty, it means that tracking has not been run
handles.Text_Display.String = 'Adjustments are to correct tracking errors, please run tracking first.';
elseif (strcmp(hObject.String, 'Adjust Prediction'))
% Clicking on the adjust prediction button will result in itself being
% displayed as the 'Exit without Saving' button. Once the adjust
% prediction mode is activated, double clicking on the image will be
% registered and return the tip location of the selected leg.
hObject.String = 'Exit without saving';
% A new button 'Save and Exit' will also appear. The handle to this
% 'Save and Exit' button is handles.Annotation.
handles.Annotation.Enable = 'On';
handles.Annotation.Visible = 'On';
handles.Annotation.String = 'Save and Exit';
handles.ConsoleUpdate.Enable = 'On';
handles.ConsoleUpdate.Visible = 'On';
handles.prevframe.Enable = 'Off';
handles.prevframe.Visible = 'Off';
handles.nextframe.Enable = 'Off';
handles.nextframe.Visible = 'Off';
if (~strcmp(handles.Tracking.String, 'Initial'))
handles.Tracking.String = 'Resume';
end
set(handles.Text_Display,'String',['Entering adjustment mode: select a leg and double click on figure to assign tip location.']);
elseif (strcmp(hObject.String, 'Exit without saving'))
% if user decides to exit without saving, all user input on the current frame will be
% discarded
hObject.String = 'Adjust Prediction';
handles.Annotation.String = 'Annotate';
handles.Annotation.Enable = 'Off';
handles.Annotation.Visible = 'Off';
handles.ConsoleUpdate.Enable = 'Off';
handles.ConsoleUpdate.Visible = 'Off';
handles.prevframe.Enable = 'On';
handles.prevframe.Visible = 'On';
handles.nextframe.Enable = 'On';
handles.nextframe.Visible = 'On';
handles.Tracking_Text.String = '';
for kk = 1:nLegs
if(trajectory(i,kk,1)~=0)
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: %3d %3d', legs_id{kk}, trajectory(i,kk,1), trajectory(i,kk,2))];
else
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
for j = 1: 2 : length(handles.figMain.CurrentAxes.Children)-2
if(strcmp(handles.figMain.CurrentAxes.Children(j).Type,'text') && strcmp(handles.figMain.CurrentAxes.Children(j).String,legs_id{kk}))
delete(handles.figMain.CurrentAxes.Children(j:j+1));
end
end
end
end
for i = 1 : nLegs
x = str2num(handles.Tracking_Text.String(i,9:11));
y = str2num(handles.Tracking_Text.String(i,13:15));
for j = 1: 2 : length(handles.figMain.CurrentAxes.Children)-2
if(strcmp(handles.figMain.CurrentAxes.Children(j).Type,'text') && strcmp(handles.figMain.CurrentAxes.Children(j).String,legs_id{i}))
delete(handles.figMain.CurrentAxes.Children(j:j+1));
if(x~=0)
hold on
scatter(x,y,'w');
text(x,y,legs_id{i},'Color',[colors(i,1) colors(i,2) colors(i,3)],'FontSize',14);
hold off
end
end
end
end
end
handles.ManualInitiate.Value = 0;
%% --- Executes on button press in ConsoleUpdate.
function ConsoleUpdate_Callback(hObject, eventdata, handles)
% hObject handle to ConsoleUpdate (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
nLegs = 8 - handles.L4.Value - handles.R4.Value;
if (nLegs > 6)
colors = [1 0 0; 0 1 0; 0 0 1; 1 0 0.5; 1 1 0; 0 1 1; 1 0 1; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3','L4', 'R1', 'R2', 'R3','R4'};
else
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1; 1 0 0.5; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
end
for i = 1 : nLegs
x = str2num(handles.Tracking_Text.String(i,9:11));
y = str2num(handles.Tracking_Text.String(i,13:15));
for j = 1 : length(handles.figMain.CurrentAxes.Children)-2
if(strcmp(handles.figMain.CurrentAxes.Children(j).Type,'text') && strcmp(handles.figMain.CurrentAxes.Children(j).String,legs_id{i}))
delete(handles.figMain.CurrentAxes.Children(j:j+1));
hold on
scatter(x,y,'w');
text(x,y,legs_id{i},'Color',[colors(i,1) colors(i,2) colors(i,3)],'FontSize',14);
hold off
end
end
end
%% --- Executes on button press in Annotation.
function Annotation_Callback(hObject, eventdata, handles)
% hObject handle to Annotation (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% This allows the user input to relabel the legs on the current frame. This
% will then update the data in the trajectory as well as the normalised
% trajectory.
hMainGui = getappdata(0, 'hMainGui');
data_dir = getappdata(hMainGui, 'data_dir');
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
seg_dir = ['./Results/SegmentedImages' sub_dir '/'];
output_dir = ['./Results/Tracking/' sub_dir '/'];
if(~exist(output_dir))
mkdir(output_dir);
end
CoM = getappdata(hMainGui, 'CoM');
trajectory = getappdata(hMainGui, 'trajectory');
norm_trajectory = getappdata(hMainGui, 'norm_trajectory');
current_frame = getappdata(hMainGui,'current_frame');
nLegs = 8 - handles.L4.Value - handles.R4.Value;
trajectory(current_frame,2,1) = str2num(handles.Tracking_Text.String(2,9:11));
trajectory(current_frame,2,2) = str2num(handles.Tracking_Text.String(2,13:15));
norm_trajectory(current_frame,2,1) = cosd(CoM(current_frame,3))*((trajectory(current_frame,2,1)-CoM(current_frame,1))) + sind(CoM(current_frame,3))*((trajectory(current_frame,2,2)-CoM(current_frame,2)));
if(strcmp(handles.Tracking.String, 'Initial') && norm_trajectory(current_frame,2,1)>0)
CoM(current_frame,3) = mod(CoM(current_frame,3)+180,360);
setappdata(hMainGui,'CoM',CoM);
% find body_length
i = current_frame;
img = imread([seg_dir 'roi_' num2str(i) '.png']);
img_norm = imtranslate(img, [255 - CoM(i,1), 255 - CoM(i,2)]);
img_norm = imrotate(img_norm, CoM(i,3));
img_norm = imcrop(img_norm, [size(img_norm,1)/2-150 size(img_norm,2)/2-150 300 300]);
[Y,X] = find(img_norm);
bodylength = max(Y(find(X==150)))-min(Y(find(X==150)));
setappdata(hMainGui, 'bodylength', bodylength);
handles.BLText.Visible = 'On';
handles.BLText.Visible = 'On';
handles.BodyLength.String = num2str(round(bodylength));
ResetImageSize_Callback(hObject, eventdata, handles);
end
for i = 1: nLegs
if (~isempty(str2num(handles.Tracking_Text.String(i,9:11))))
trajectory(current_frame,i,1) = str2num(handles.Tracking_Text.String(i,9:11));
trajectory(current_frame,i,2) = str2num(handles.Tracking_Text.String(i,13:15));
norm_trajectory(current_frame,i,1) = cosd(CoM(current_frame,3))*((trajectory(current_frame,i,1)-CoM(current_frame,1))) + sind(CoM(current_frame,3))*((trajectory(current_frame,i,2)-CoM(current_frame,2)));
norm_trajectory(current_frame,i,2) = -sind(CoM(current_frame,3))*((trajectory(current_frame,i,1)-CoM(current_frame,1))) + cosd(CoM(current_frame,3))*((trajectory(current_frame,i,2)-CoM(current_frame,2)));
else
trajectory(current_frame,i,:) = 0;
norm_trajectory(current_frame,i,:) = 0;
end
end
setappdata(hMainGui,'trajectory',trajectory);
setappdata(hMainGui,'norm_trajectory',norm_trajectory);
save([output_dir 'CoM.mat'],'CoM');
save([output_dir 'trajectory.mat'],'trajectory');
save([output_dir 'norm_trajectory.mat'],'norm_trajectory');
csvwrite([output_dir 'CoM.csv'],CoM);
csvwrite([output_dir 'trajectory.csv'],trajectory);
csvwrite([output_dir 'norm_trajectory.csv'],norm_trajectory);
hObject.String = 'Annotate';
hObject.Enable = 'Off';
hObject.Visible = 'Off';
handles.ConsoleUpdate.Enable = 'Off';
handles.ConsoleUpdate.Visible = 'Off';
handles.prevframe.Enable = 'On';
handles.prevframe.Visible = 'On';
handles.nextframe.Enable = 'On';
handles.nextframe.Visible = 'On';
handles.Adjust_Prediction.String = 'Adjust Prediction';
handles.Tracking.String = 'Resume';
%% --- Executes on button press in prevframe.
function prevframe_Callback(hObject, eventdata, handles)
% hObject handle to prevframe (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
data_dir = getappdata(hMainGui, 'data_dir');
bodylength = getappdata(hMainGui, 'bodylength');
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
seg_dir = ['./Results/SegmentedImages' sub_dir '/'];
data_dir = ['./Data' sub_dir '/'];
img_list = load_img_list(data_dir);
setappdata(hMainGui,'current_frame', getappdata(hMainGui, 'current_frame') - 1);
i = getappdata(hMainGui, 'current_frame');
handles.text.String = ['Current frame: ' num2str(i)];
handles.GoToDropdown.Value = i;
display = handles.ChooseDisplay.Value;
switch display
case 1
handles.GoToDropdown.String = 1:length(img_list);
imshow([data_dir img_list(i).name]);
case 2
roi_list = dir([seg_dir 'roi_*.png']);
handles.GoToDropdown.String = 1:length(roi_list);
imshow([seg_dir 'roi_' num2str(i) '.png']);
case 3
seg_list = dir([seg_dir 'img_*.png']);
handles.GoToDropdown.String = 1:length(seg_list);
imshow([seg_dir 'img_' num2str(i) '.png']);
case 4
handles.Tracking.String = 'Resume';
CoM = getappdata(hMainGui, 'CoM');
trajectory = getappdata(hMainGui, 'trajectory');
nLegs = 8 - handles.L4.Value - handles.R4.Value;
if (nLegs > 6)
colors = [1 0 0; 0 1 0; 0 0 1; 1 0 0.5; 1 1 0; 0 1 1; 1 0 1; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3','L4', 'R1', 'R2', 'R3','R4'};
else
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1; 1 0 0.5; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
end
if(~isempty(trajectory))
handles.text.String = ['Current frame: ' num2str(i)];
handles.Tracking_Text.String = '';
imshow([data_dir img_list(i).name]);
hold on;
scatter(CoM(i,1)+sind(CoM(i,3))*.157*bodylength,CoM(i,2)-cosd(CoM(i,3))*.157*bodylength,'w*');
for kk = 1:nLegs
if(eval(['handles.' legs_id{kk} '.Value']))
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
continue;
end
if(trajectory(i,kk,1)~=0)
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: %3d %3d', legs_id{kk}, trajectory(i,kk,1), trajectory(i,kk,2))];
scatter(trajectory(i,kk,1),trajectory(i,kk,2),'w');
text(trajectory(i,kk,1),trajectory(i,kk,2),legs_id{kk},'Color',[colors(kk,1) colors(kk,2) colors(kk,3)],'FontSize',14);
else
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
end
end
hold off;
drawnow
% Update Display
nLegs = 8 - handles.L1.Value - handles.L2.Value - handles.L3.Value - handles.R1.Value - handles.R2.Value - handles.R3.Value - handles.L4.Value - handles.R4.Value;
if(length(str2num(handles.Tracking_Text.String(:,9:11))) < nLegs)
set(handles.Missing, 'BackgroundColor', [1 0 0]);
else
set(handles.Missing, 'BackgroundColor', [0 1 0]);
end
end
end
%% --- Executes on button press in nextframe.
function nextframe_Callback(hObject, eventdata, handles)
% hObject handle to nextframe (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
data_dir = getappdata(hMainGui, 'data_dir');
bodylength = getappdata(hMainGui, 'bodylength');
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
seg_dir = ['./Results/SegmentedImages' sub_dir '/'];
data_dir = ['./Data' sub_dir '/'];
img_list = load_img_list(data_dir);
setappdata(hMainGui,'current_frame', getappdata(hMainGui, 'current_frame') + 1);
i = getappdata(hMainGui, 'current_frame');
handles.text.String = ['Current frame: ' num2str(i)];
handles.GoToDropdown.Value = i;
display = handles.ChooseDisplay.Value;
switch display
case 1
handles.GoToDropdown.String = 1:length(img_list);
imshow([data_dir img_list(i).name]);
case 2
roi_list = dir([seg_dir 'roi_*.png']);
handles.GoToDropdown.String = 1:length(roi_list);
imshow([seg_dir 'roi_' num2str(i) '.png']);
case 3
seg_list = dir([seg_dir 'img_*.png']);
handles.GoToDropdown.String = 1:length(seg_list);
imshow([seg_dir 'img_' num2str(i) '.png']);
case 4
CoM = getappdata(hMainGui, 'CoM');
trajectory = getappdata(hMainGui, 'trajectory');
norm_trajectory = getappdata(hMainGui, 'norm_trajectory');
se = strel('disk',4);
skip = 1;
max_distance = 20;
nLegs = 8 - handles.L4.Value - handles.R4.Value;
if (nLegs > 6)
colors = [1 0 0; 0 1 0; 0 0 1; 1 0 0.5; 1 1 0; 0 1 1; 1 0 1; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3','L4', 'R1', 'R2', 'R3','R4'};
else
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1; 1 0 0.5; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
end
if (handles.ViewerMode.Value)
if(~isempty(trajectory))
handles.text.String = ['Current frame: ' num2str(i)];
handles.Tracking_Text.String = '';
imshow([data_dir img_list(i).name]);
hold on;
scatter(CoM(i,1)+sind(CoM(i,3))*.157*bodylength,CoM(i,2)-cosd(CoM(i,3))*.157*bodylength,'w*');
for kk = 1:nLegs
if(eval(['handles.' legs_id{kk} '.Value']))
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
continue;
end
if(trajectory(i,kk,1)~=0)
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: %3d %3d', legs_id{kk}, trajectory(i,kk,1), trajectory(i,kk,2))];
scatter(trajectory(i,kk,1),trajectory(i,kk,2),'w');
text(trajectory(i,kk,1),trajectory(i,kk,2),legs_id{kk},'Color',[colors(kk,1) colors(kk,2) colors(kk,3)],'FontSize',14);
else
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
end
end
hold off;
drawnow
% Update Display
nLegs = 8 - handles.L1.Value - handles.L2.Value - handles.L3.Value - handles.R1.Value - handles.R2.Value - handles.R3.Value - handles.L4.Value - handles.R4.Value;
if(length(str2num(handles.Tracking_Text.String(:,9:11))) < nLegs)
set(handles.Missing, 'BackgroundColor', [1 0 0]);
else
set(handles.Missing, 'BackgroundColor', [0 1 0]);
end
end
else
handles.Tracking.String = 'Resume';
Im = (imread([seg_dir 'img_' num2str(i) '.png']));
Imroi = imread([seg_dir 'roi_' num2str(i) '.png']);
% Fix image/segmentation irregularities
Imwork = double(Im(:,:,1) == 255) .* Imroi;
if (nLegs>6)
Imwork = Imwork - (bwdist(imerode(Imroi,strel('disk',6)))<15);
Imwork = bwareaopen(Imwork>0,5);
else
Imwork = Imwork - (bwdist(imerode(Imroi,se))<10);
Imwork = bwareaopen(Imwork>0,3);
end
[locY,locX] = find(imerode(Imroi,se) > 0);
[centre_of_mass,theta] = findCoM(locX,locY);
if (abs(theta - CoM(i-skip,3)) > 90 && abs(theta - CoM(i-skip,3)) < 270)
theta = mod(theta + 180,360);
end
CoM(i, :) = [centre_of_mass, theta];
clear raw_tips;
clear raw_normtips;
[raw_tips, raw_normtips] = findtips(Imwork, Imroi, locX, locY, centre_of_mass, theta);
x_t1 = raw_normtips;
x_t0 = reshape(norm_trajectory(i-1,:),[nLegs 2]);
target_indices = hungarianlinker(x_t0, x_t1, max_distance);
for kk = 1:length(target_indices)
if (target_indices(kk) > 0)
norm_trajectory(i, kk, :) = raw_normtips(target_indices(kk),:);
trajectory(i, kk, :) = raw_tips(target_indices(kk),:);
else
norm_trajectory(i, kk, :) = 0;
trajectory(i, kk, :) = 0;
end
end
leftoveridx = find(hungarianlinker(raw_normtips, x_t0, max_distance)==-1);
x_t1 = raw_normtips(leftoveridx,:);
x_t2 = raw_tips(leftoveridx,:);
last_seen_tips = reshape(norm_trajectory(i,:),[nLegs 2]);
unassigned_idx = find(last_seen_tips(:,1) == 0);
for kk = 1:length(unassigned_idx)
if(eval(['handles.' legs_id{unassigned_idx(kk)} '.Value']))
continue;
end
idx = find(norm_trajectory(1:i,unassigned_idx(kk),1),1,'last');
last_seen_tips(unassigned_idx(kk),:) = reshape(norm_trajectory(idx,unassigned_idx(kk),:), [1 2]);
end
if (~isempty(unassigned_idx) && ~isempty(x_t1))
C = hungarianlinker(last_seen_tips(unassigned_idx,:), x_t1, 1.25*max_distance);
for l = 1:length(C)
if (C(l) ~= -1)
norm_trajectory(i,unassigned_idx(l), :) = x_t1(C(l), :);
trajectory(i,unassigned_idx(l), :) = x_t2(C(l), :);
end
end
end
handles.Tracking_Text.String = '';
oriIm = im2double(imread([data_dir img_list(i).name]));
imshow(oriIm);
hold on;
scatter(CoM(i,1)+sind(CoM(i,3))*.157*bodylength,CoM(i,2)-cosd(CoM(i,3))*.157*bodylength,'w*');
for kk = 1:nLegs
if (eval(['handles.' legs_id{kk} '.Value']))
trajectory(i,kk,1) = 0;
trajectory(i,kk,2) = 0;
norm_trajectory(i,kk,1) = 0;
norm_trajectory(i,kk,2) = 0;
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
continue;
end
if(trajectory(i,kk,1)~=0)
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: %3d %3d', legs_id{kk}, trajectory(i,kk,1), trajectory(i,kk,2))];
scatter(trajectory(i,kk,1),trajectory(i,kk,2),'w');
text(trajectory(i,kk,1),trajectory(i,kk,2),legs_id{kk},'Color',[colors(kk,1) colors(kk,2) colors(kk,3)],'FontSize',14);
else
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
end
end
hold off;
drawnow
% Update Display
nLegs = 8 - handles.L1.Value - handles.L2.Value - handles.L3.Value - handles.R1.Value - handles.R2.Value - handles.R3.Value - handles.L4.Value - handles.R4.Value;
if(length(str2num(handles.Tracking_Text.String(:,9:11))) < nLegs)
set(handles.Missing, 'BackgroundColor', [1 0 0]);
else
set(handles.Missing, 'BackgroundColor', [0 1 0]);
end
setappdata(hMainGui, 'CoM' , CoM);
setappdata(hMainGui, 'trajectory' , trajectory);
setappdata(hMainGui, 'norm_trajectory' , norm_trajectory);
handles.GoToDropdown.String = 1:find(trajectory,1,'last');
end
end
%% --- Executes on button press in Select_Folder.
function Select_Folder_Callback(hObject, eventdata, handles)
% hObject handle to Select_Folder (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
if(~isempty(getappdata(hMainGui, 'trajectory')))
choice = questdlg('Save tracking data?', ...
'FLLIT', ...
'Yes', 'No', 'Cancel', 'Cancel');
% Handle response
switch choice
case 'Yes'
data_dir = getappdata(hMainGui, 'data_dir');
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
output_dir = ['./Results/SegmentedImages' sub_dir '/'];
trajectory = getappdata(hMainGui, 'trajectory');
norm_trajectory = getappdata(hMainGui, 'norm_trajectory');
CoM = getappdata(hMainGui, 'CoM');
save([output_dir 'CoM.mat'],'CoM');
save([output_dir 'trajectory.mat'],'trajectory');
save([output_dir 'norm_trajectory.mat'],'norm_trajectory');
csvwrite([output_dir 'CoM.csv'],CoM);
csvwrite([output_dir 'trajectory.csv'],trajectory);
csvwrite([output_dir 'norm_trajectory.csv'],norm_trajectory);
setappdata(hMainGui, 'trajectory', []);
case 'No'
setappdata(hMainGui, 'trajectory', []);
case 'Cancel'
return;
end
end
handles.BLText.Visible = 'Off';
handles.BodyLength.Visible = 'Off';
handles.BodyLength.String = '0';
handles.ViewBackground.Enable = 'Off';
handles.Foreground.Enable = 'Off';
handles.Segmentation.Enable = 'Off';
handles.Tracking.Enable = 'Off';
handles.Adjust_Prediction.Enable = 'Off';
handles.Video.Enable = 'Off';
handles.DataProcessing.Enable = 'Off';
handles.prevframe.Enable = 'Off';
handles.nextframe.Enable = 'Off';
handles.GoToFrame.Visible = 'Off';
handles.GoToDropdown.Visible = 'Off';
handles.ChooseDisplay.Visible = 'Off';
handles.Tracking_Text.String = '';
data_dir = uigetdir(['./Data']);
pos_bs = strfind(data_dir,'Data');
if(~isempty(pos_bs))
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
setappdata(hMainGui, 'data_dir', data_dir);
set(handles.Text_Display, 'String', data_dir);
else
return;
end
data_dir = ['./Data' sub_dir '/'];
handles.Progress.String = '';
handles.Tracking.String = 'Tracking';
img_list = load_img_list(data_dir);
if(~isempty(img_list))
handles.ViewBackground.Enable = 'On';
handles.Foreground.Enable = 'On';
handles.Segmentation.Enable = 'On';
handles.Tracking.Enable = 'On';
handles.Adjust_Prediction.Enable = 'On';
handles.Video.Enable = 'On';
handles.DataProcessing.Enable = 'On';
handles.prevframe.Enable = 'On';
handles.nextframe.Enable = 'On';
handles.GoToFrame.Visible = 'On';
handles.GoToDropdown.Visible = 'On';
handles.ChooseDisplay.Visible = 'On';
handles.GoToDropdown.String = 1:length(img_list);
handles.GoToDropdown.Value = 1;
handles.ChooseDisplay.String = {'Original'};
handles.ChooseDisplay.Value = 1;
handles.text.String = 'Current frame: 1';
setappdata(hMainGui,'current_frame',1);
handles.Tracking_Text.String = '';
oriIm = im2double(imread([data_dir img_list(1).name]));
imshow(oriIm);
else
handles.ViewBackground.Enable = 'Off';
handles.Foreground.Enable = 'Off';
handles.Segmentation.Enable = 'Off';
handles.Tracking.Enable = 'Off';
handles.Video.Enable = 'Off';
handles.Adjust_Prediction.Enable = 'Off';
handles.DataProcessing.Enable = 'Off';
handles.prevframe.Enable = 'Off';
handles.nextframe.Enable = 'Off';
handles.GoToFrame.Visible = 'Off';
handles.GoToDropdown.Visible = 'Off';
handles.ChooseDisplay.Visible = 'Off';
end
seg_dir = ['./Results/SegmentedImages' sub_dir '/'];
seg_list = dir([seg_dir 'img_*.png']);
if(~isempty(seg_list))
handles.ChooseDisplay.String{2} = 'ROI';
handles.ChooseDisplay.String{3} = 'Segmented';
handles.ChooseDisplay.Value = 3;
segIm = im2double(imread([seg_dir seg_list(1).name]));
imshow(segIm);
end
output_dir = ['./Results/Tracking' sub_dir '/'];
if(exist([output_dir 'trajectory.mat']))
handles.ChooseDisplay.String{4} = 'Tracking';
handles.ChooseDisplay.Value = 4;
handles.Progress.String = 'Tracking Complete.';
set(handles.Text_Display, 'String', 'Tracking already completed for this folder');
load([output_dir 'trajectory.mat']);
load([output_dir 'norm_trajectory.mat']);
load([output_dir 'CoM.mat']);
handles.ViewerMode.Value = 1;
handles.ViewTracking.Visible = 'On';
handles.ViewTracking.Enable = 'On';
startframe = find(trajectory, 1, 'first');
endframe = length(CoM);
% find body_length
i = startframe;
try
img = imread([seg_dir 'roi_' num2str(i) '.png']);
img_norm = imtranslate(img, [255 - CoM(i,1), 255 - CoM(i,2)]);
img_norm = imrotate(img_norm, CoM(i,3));
img_norm = imcrop(img_norm, [size(img_norm,1)/2-150 size(img_norm,2)/2-150 300 300]);
[Y,X] = find(img_norm);
bodylength = max(Y(find(X==150)))-min(Y(find(X==150)));
catch
bodylength = 130;
end
setappdata(hMainGui, 'bodylength', bodylength);
handles.BLText.Visible = 'On';
handles.BodyLength.Visible = 'On';
handles.BodyLength.String = num2str(round(bodylength));
ResetImageSize_Callback(hObject, eventdata, handles);
setappdata(hMainGui, 'start_frame',startframe);
setappdata(hMainGui,'current_frame',startframe);
setappdata(hMainGui, 'trajectory', trajectory);
setappdata(hMainGui, 'norm_trajectory', norm_trajectory);
setappdata(hMainGui, 'CoM', CoM);
handles.VideoStart.Visible = 'On';
handles.VideoEnd.Visible = 'On';
handles.VideoStartFrame.Visible = 'On';
handles.VideoEndFrame.Visible = 'On';
handles.VideoStartFrame.String = num2str(startframe);
handles.VideoEndFrame.String = num2str(endframe);
nLegs = size(trajectory,2);
if (nLegs > 6)
colors = [1 0 0; 0 1 0; 0 0 1; 1 0 0.5; 1 1 0; 0 1 1; 1 0 1; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3','L4', 'R1', 'R2', 'R3','R4'};
else
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1; 1 0 0.5; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
end
i = startframe;
handles.text.String = ['Current frame: ' num2str(i)];
handles.GoToDropdown.Value = i;
handles.Tracking_Text.String = '';
oriIm = im2double(imread([data_dir img_list(i).name]));
imshow(oriIm);
hold on;
scatter(CoM(i,1)+sind(CoM(i,3))*.157*bodylength,CoM(i,2)-cosd(CoM(i,3))*.157*bodylength,'w*');
for kk = 1:size(trajectory,2)
if(trajectory(i,kk,1)~=0)
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: %3d %3d', legs_id{kk}, trajectory(i,kk,1), trajectory(i,kk,2))];
scatter(trajectory(i,kk,1),trajectory(i,kk,2),'w');
text(trajectory(i,kk,1),trajectory(i,kk,2),legs_id{kk},'Color',[colors(kk,1) colors(kk,2) colors(kk,3)],'FontSize',14);
else
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
end
end
hold off;
drawnow
% Update Display
nLegs = 8 - handles.L1.Value - handles.L2.Value - handles.L3.Value - handles.R1.Value - handles.R2.Value - handles.R3.Value - handles.L4.Value - handles.R4.Value;
if(length(str2num(handles.Tracking_Text.String(:,9:11))) < nLegs)
set(handles.Missing, 'BackgroundColor', [1 0 0]);
else
set(handles.Missing, 'BackgroundColor', [0 1 0]);
end
else
setappdata(hMainGui, 'bodylength', 0);
setappdata(hMainGui, 'trajectory', []);
setappdata(hMainGui, 'norm_trajectory', []);
setappdata(hMainGui, 'CoM', []);
handles.ViewerMode.Value = 0;
handles.ViewTracking.Visible = 'Off';
handles.ViewTracking.Enable = 'Off';
handles.VideoStart.Visible = 'Off';
handles.VideoEnd.Visible = 'Off';
handles.VideoStartFrame.Visible = 'Off';
handles.VideoEndFrame.Visible = 'Off';
end
%% --- Executes on button press in Segmentation.
function Segmentation_Callback(hObject, eventdata, handles)
% hObject handle to Segmentation (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
data_dir = getappdata(hMainGui, 'data_dir');
set(handles.Text_Display, 'String', 'Starting segmentation.');
pause(1);
handles.axes1 = gcf;
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
data_dir = ['./Data' sub_dir '/'];
output_dir = ['./Results/SegmentedImages' sub_dir '/'];
if (~exist([output_dir '/roi_1.png']))
pause(1);
Foreground_Callback(hObject, eventdata, handles);
end
handles.ChooseDisplay.Value = 3;
ref_img = imread([data_dir 'Background/Background.png']);
ref_img = double(ref_img);
ref_img = padarray(ref_img,[20 20],'replicate');
img_list = load_img_list(data_dir);
params = setup_config_L('Drive');
%params = setup_lists(params);
%params = setup_directories_L(params);
params.border_skip_size = 20;
params.pos_samples_no = 30000;
params.neg_samples_no = 30000;
params.sample_size = [41 41]';
load_wl = handles.LoadClassifier.Value;
foreground_thres = handles.ForegroundSlider.Value;
score_thres = handles.SegmentationSlider.Value;
if (load_wl)
set(handles.Text_Display, 'String','Please select the trained classifier to be used.');
[wl_file, wl_dir] = uigetfile(['./Results/Classifiers/','*.mat']);
load([wl_dir wl_file]);
else
if(~exist(['./Results/Classifiers' sub_dir '_Classifier.mat']))
set(handles.Text_Display, 'String','Training the classifer over a random subset of the images.');
sample_ratio = 20;
tot_idx.pos = 0;
tot_idx.neg = 0;
data = [];
% Collect the positive and negative samples
for i_img = 1 : floor(length(img_list) / sample_ratio)
I = imread([data_dir img_list(i_img * sample_ratio).name]);
I = double(I);
I = padarray(I,[20 20],'replicate');
[pos_img,neg_img_body,neg_img_bkg] = leg_segment(I,ref_img,foreground_thres);
show_img_output = repmat(I/255,[1 1 3]);
show_img_output(:,:,1) = show_img_output(:,:,1) + pos_img;
show_img_output(:,:,3) = show_img_output(:,:,3) + neg_img_body;
imshow(show_img_output,[]);
pause(0.1);
data.train.imgs.X{i_img,1} = I / 255;
data.train.imgs.X{i_img,2} = (ref_img - I) / 255;
gt_img = zeros(size(I));
gt_img(pos_img > 0) = 1;
gt_img(neg_img_body > 0) = -1;
gt_img(neg_img_bkg > 0) = -1;
data.train.gts.X{i_img} = gt_img;
% ------------------------------
border_img = zeros(size(I));
border_img(1:params.border_skip_size,:) = 1;
border_img(:,1:params.border_skip_size) = 1;
border_img((end-params.border_skip_size):end,:) = 1;
border_img(:,(end-params.border_skip_size):end) = 1;
pos_sampling = find((pos_img) & (~border_img) & (~neg_img_body));
neg_body_sampling = find(neg_img_body & (~border_img) & (~pos_img));
neg_bkg_sampling = find(neg_img_bkg & (~border_img));
% sample counts
imgs_no = floor(length(img_list) / sample_ratio);
npos_img = ceil(params.pos_samples_no / imgs_no);
nneg_img = ceil(params.neg_samples_no / imgs_no);
% getting a random subset?
neg_sampling = neg_body_sampling(randi(length(neg_body_sampling),[nneg_img,1]));
neg_sampling = [neg_sampling; neg_bkg_sampling(randi(length(neg_bkg_sampling),[nneg_img,1]))];
npos = length(pos_sampling);
nneg = length(neg_sampling);
good_sampling_idx{i_img}.pos = pos_sampling(randi(npos,[ceil(npos_img),1]));
good_sampling_idx{i_img}.neg = neg_sampling(randi(nneg,[ceil(nneg_img),1]));
good_sampling_idx{i_img}.pos_val = pos_img(good_sampling_idx{i_img}.pos);
good_sampling_idx{i_img}.neg_val = pos_img(good_sampling_idx{i_img}.neg);
tot_idx.pos = tot_idx.pos+length(good_sampling_idx{i_img}.pos);
tot_idx.neg = tot_idx.neg+length(good_sampling_idx{i_img}.neg);
end
data.train.imgs.idxs = 1:2;
data.train.imgs.sub_ch_no = 2;
samples_idx = [];
% Preparing the samples
for i_img = 1 : floor(length(img_list) / sample_ratio)
I = imread([data_dir img_list(i_img * sample_ratio).name]);
I = padarray(I,[20 20],'replicate');
samp_idx = [good_sampling_idx{i_img}.pos ; good_sampling_idx{i_img}.neg];
samp_idx_2D = zeros(length(samp_idx),2);
[samp_idx_2D(:,1),samp_idx_2D(:,2)] = ind2sub(size(I),samp_idx);
labels = [good_sampling_idx{i_img}.pos_val ; good_sampling_idx{i_img}.neg_val];
labels = double(labels);
labels(labels < 0.5) = -1;
samples_idx_img = zeros(length(samp_idx),4);
samples_idx_img(:,1) = i_img;
samples_idx_img(:,2:3) = samp_idx_2D;
samples_idx_img(:,4) = labels;
samples_idx = cat(1,samples_idx,samples_idx_img);
end
samples_idx = samples_idx(1 : (params.pos_samples_no + params.neg_samples_no),:);
params.pos_samples_no = sum(samples_idx(:,end)==1);
params.neg_samples_no = sum(samples_idx(:,end)==-1);
params.T1_size = round((params.pos_samples_no+params.neg_samples_no)/3);
params.T2_size = round((params.pos_samples_no+params.neg_samples_no)/3);
params.pos_to_sample_no = params.T1_size;
params.neg_to_sample_no = params.T1_size;
params.wl_no = 100;
% Train the classifier here
weak_learners = train_boost_general(params,data,samples_idx);
sub_dir_pos = strfind(sub_dir,'/');
if(~exist(['./Results/Classifiers/' sub_dir(1:sub_dir_pos(end))]))
mkdir(['./Results/Classifiers/' sub_dir(1:sub_dir_pos(end))]);
end
save (['./Results/Classifiers/' sub_dir '_Classifier.mat'],'weak_learners');
else
load(['./Results/Classifiers/' sub_dir '_Classifier.mat']);
end
end
set(handles.Text_Display, 'String','Training completed, now applying the classifier to all images.');
fprintf('Output directory: %s\n', output_dir);
% Applying the classifier
sample_ratio = 1;
sec_no = 10;
for i_sec = 1 : ceil(length(img_list) / sample_ratio / sec_no)
X = [];
if (i_sec < ceil(length(img_list) / sample_ratio / sec_no))
imgs_sec = 1 + (i_sec - 1) * sec_no : sample_ratio :(i_sec) * sec_no;
else
imgs_sec = 1 + (i_sec - 1) * sec_no : sample_ratio : length(img_list);
end
for i_img = 1 : length(imgs_sec)
I = imread([data_dir img_list(imgs_sec(i_img)).name]);
I = double(I);
I = padarray(I,[20 20],'replicate');
%neg_img{i_img} = leg_segment_clean(I,roi_img);
bkg_sub = (ref_img - I);
I(:,:,2) = bkg_sub;
I = I / 255;
X{i_img,1} = I(:,:,1);
X{i_img,2} = I(:,:,2);
roi_img = imread([output_dir 'roi_' num2str(imgs_sec(i_img)) '.png']);
roi_images{i_img} = padarray(roi_img,[20 20],'replicate');
end
score_images = batch_evaluate_boost_images(X,params,weak_learners,roi_images);
for i_img = 1 : length(imgs_sec)
I = imread([data_dir img_list(imgs_sec(i_img)).name]);
I = double(I)/255;
I = padarray(I,[20 20],'replicate');
score_img = score_images{i_img};
est_leg = score_img > score_thres;
%est_leg = bwdist(est_leg)<3 .*roi_images{i_img};
%est_leg = est_leg & ~ neg_img{i_img} & roi_images{i_img};
est_leg = filter_small_comp(est_leg,5);
show_img_output = repmat(I,[1 1 3]);
show_img_output(:,:,1) = show_img_output(:,:,1) + est_leg;
imwrite(imcrop(show_img_output,[21 21 size(I,2)-41 size(I,1)-41]),[output_dir 'img_' num2str(imgs_sec(i_img)) '.png'],'png');
if (i_img == 1)
imshow(imcrop(show_img_output,[21 21 size(I,2)-41 size(I,1)-41]));
handles.GoToDropdown.Value = (i_sec-1)*10 + i_img;
handles.Progress.String = ['Segmentation Progress: ' num2str(min(i_sec*10,length(img_list))) '/' num2str(length(img_list))];
pause(0.1);
end
end
end
handles.Text_Display.String = 'Segmentation complete, proceeding with tracking.';
pause(5);
Tracking_Callback(hObject, eventdata, handles);
%% --- Executes on button press in Tracking.
function Tracking_Callback(hObject, eventdata, handles)
% hObject handle to Tracking (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
data_dir = getappdata(hMainGui, 'data_dir');
if(isempty(getappdata(hMainGui, 'trajectory')))
setappdata(hMainGui, 'CoM', []);
setappdata(hMainGui, 'trajectory', []);
setappdata(hMainGui, 'norm_trajectory', []);
setappdata(hMainGui, 'start_frame', []);
end
bodylength = getappdata(hMainGui, 'bodylength');
CoM = getappdata(hMainGui, 'CoM');
trajectory = getappdata(hMainGui, 'trajectory');
norm_trajectory = getappdata(hMainGui, 'norm_trajectory');
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
seg_dir = ['./Results/SegmentedImages' sub_dir '/'];
data_dir = ['./Data' sub_dir '/'];
img_list = load_img_list(data_dir);
output_dir = ['./Results/Tracking/' sub_dir '/'];
if(~exist(output_dir))
mkdir(output_dir);
end
if(length(handles.ChooseDisplay.String)<4)
handles.ChooseDisplay.String{4} = 'Tracking';
end
removed_legs = handles.L1.Value+handles.L2.Value+handles.L3.Value+handles.L4.Value+handles.R1.Value+handles.R2.Value+handles.R3.Value+handles.R4.Value;
nLegs = 8 - handles.L4.Value - handles.R4.Value;
if (nLegs > 6)
colors = [1 0 0; 0 1 0; 0 0 1; 1 0 0.5; 1 1 0; 0 1 1; 1 0 1; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3','L4', 'R1', 'R2', 'R3','R4'};
else
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1; 1 0 0.5; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
end
se = strel('disk',4);
max_distance = 20;
if (isempty(seg_dir))
set(handles.Text_Display, 'String', 'Please ensure that segmentation has been completed first.');
else
set(handles.Text_Display, 'String', 'Performing legs tracking.');
pause(1);
handles.axes1 = gcf;
drawnow
end_frame = length(dir([seg_dir 'img_*.png']));
handles.ChooseDisplay.Value = 4;
%Manually initiate tracking by labeling leg tips on chosen frame
if(get(handles.ManualInitiate,'Value'))
setappdata(hMainGui, 'CoM', []);
setappdata(hMainGui, 'trajectory', []);
setappdata(hMainGui, 'norm_trajectory', []);
i = handles.GoToDropdown.Value;
Imroi = imread([seg_dir 'roi_' num2str(i) '.png']);
handles.Tracking_Text.String = '';
setappdata(hMainGui, 'current_frame', i);
setappdata(hMainGui, 'start_frame', i);
handles.GoToDropdown.String = i:i;
Imroi = imerode(Imroi,se);
[locY,locX] = find(Imroi > 0);
%Centre_of_Mass
[centre_of_mass,theta] = findCoM(locX,locY);
CoM(i, :) = [centre_of_mass, theta];
setappdata(hMainGui, 'CoM' , CoM);
oriIm = im2double(imread([data_dir img_list(i).name]));
imshow(oriIm);
handles.Tracking.String = 'Initial';
% find body_length
img = imread([seg_dir 'roi_' num2str(i) '.png']);
img_norm = imtranslate(img, [255 - CoM(i,1), 255 - CoM(i,2)]);
img_norm = imrotate(img_norm, CoM(i,3));
img_norm = imcrop(img_norm, [size(img_norm,1)/2-150 size(img_norm,2)/2-150 300 300]);
[Y,X] = find(img_norm);
bodylength = max(Y(find(X==150)))-min(Y(find(X==150)));
setappdata(hMainGui, 'bodylength', bodylength);
handles.BLText.Visible = 'On';
handles.BodyLength.Visible = 'On';
handles.BodyLength.String = num2str(round(bodylength));
ResetImageSize_Callback(hObject, eventdata, handles);
hold on
scatter(CoM(i,1)+sind(CoM(i,3))*.157*bodylength,CoM(i,2)-cosd(CoM(i,3))*.157*bodylength,'w*');
hold off
%Automatically initiate tracking
elseif(isempty(getappdata(hMainGui, 'start_frame')));
for i = 1: end_frame
clear connComp;
% Load necessary images
Im = imread([seg_dir 'img_' num2str(i) '.png']);
Imroi = imread([seg_dir 'roi_' num2str(i) '.png']);
% Fix image/segmentation irregularities
Imwork = double(Im(:,:,1) == 255) .* Imroi;
connComp = bwconncomp(Imwork);
%Find a frame with correct number of legs (each leg component
%must contain at least 35 pixels)
if (connComp.NumObjects == 8 - removed_legs && min(cellfun(@length,connComp.PixelIdxList)) > 35)
handles.text.String = ['Current frame: ' num2str(i)];
Imroi = imerode(Imroi,se);
[locY,locX] = find(Imroi > 0);
%Centre_of_Mass
[centre_of_mass,theta] = findCoM(locX,locY);
locX_norm = locX - centre_of_mass(1);
locY_norm = locY - centre_of_mass(2);
points = [cosd(theta) sind(theta); -sind(theta) cosd(theta)]* [locX_norm'; locY_norm'];
%Attempt to ensure that the head is in the positive
%y-direction by comparing which side has more number of
%pixel points
if (length(find(points(2,:) > 0)) < length(find(points(2,:) < 0)))
theta = mod(theta + 180,360);
end
for cc = 1 : 8 - removed_legs
legpixels = connComp.PixelIdxList{cc};
imleg = zeros(size(Imwork));
imleg(legpixels) = 1;
[skr,~] = skeleton(imleg);
skr_start = 3;
[~,exy,~] = anaskel(bwmorph(skr > skr_start,'skel',Inf));
imgX = exy(1,:) - centre_of_mass(1);
imgY = exy(2,:) - centre_of_mass(2);
normpoints = [cosd(theta) sind(theta); -sind(theta) cosd(theta)]* [imgX; imgY];
[~,tipidx]=max(min(pdist2(points',normpoints','euclidean')));
for j = 1:2
raw_normtips(cc,j) = normpoints(j,tipidx);
raw_tips(cc,j) = exy(j,tipidx);
end
end
leftlegs_idx = find(raw_normtips(:,1)<0);
if(length(leftlegs_idx)~=4 - handles.L1.Value - handles.L2.Value - handles.L3.Value - handles.L4.Value)
continue;
end
rightlegs_idx = find(raw_normtips(:,1)>0);
if(length(rightlegs_idx)~=4 - handles.R1.Value - handles.R2.Value - handles.R3.Value - handles.R4.Value)
continue;
end
[~,left_sort] = sort(raw_normtips(leftlegs_idx,2));
leg_counter = 0;
for kk = 1 : nLegs/2
if (eval(['handles.L' num2str(kk) '.Value']))
leg_counter = leg_counter+1;
continue;
end
trajectory(i, kk, :) = raw_tips(leftlegs_idx(left_sort(kk-leg_counter)),:);
norm_trajectory(i, kk, :) = raw_normtips(leftlegs_idx(left_sort(kk-leg_counter)),:);
end
[~,right_sort] = sort(raw_normtips(rightlegs_idx,2));
leg_counter = 0;
for kk = 1 :nLegs/2
if (eval(['handles.R' num2str(kk) '.Value']))
leg_counter = leg_counter+1;
continue;
end
trajectory(i, kk+nLegs/2, :) = raw_tips(rightlegs_idx(right_sort(kk-leg_counter)),:);
norm_trajectory(i, kk+nLegs/2, :) = raw_normtips(rightlegs_idx(right_sort(kk-leg_counter)),:);
end
CoM(i, :) = [centre_of_mass, theta];
handles.Tracking_Text.String = '';
setappdata(hMainGui, 'start_frame', i);
setappdata(hMainGui, 'current_frame', i);
oriIm = im2double(imread([data_dir img_list(i).name]));
imshow(oriIm);
hold on;
% find body_length
img = imread([seg_dir 'roi_' num2str(i) '.png']);
img_norm = imtranslate(img, [255 - CoM(i,1), 255 - CoM(i,2)]);
img_norm = imrotate(img_norm, CoM(i,3));
img_norm = imcrop(img_norm, [size(img_norm,1)/2-150 size(img_norm,2)/2-150 300 300]);
[Y,X] = find(img_norm);
bodylength = max(Y(find(X==150)))-min(Y(find(X==150)));
setappdata(hMainGui, 'bodylength', bodylength);
handles.BLText.Visible = 'On';
handles.BodyLength.Visible = 'On';
handles.BodyLength.String = num2str(round(bodylength));
ResetImageSize_Callback(hObject, eventdata, handles);
scatter(CoM(i,1)+sind(CoM(i,3))*.157*bodylength,CoM(i,2)-cosd(CoM(i,3))*.157*bodylength,'w*');
for kk = 1:nLegs
if (eval(['handles.' legs_id{kk} '.Value']))
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
end
scatter(trajectory(i,kk,1),trajectory(i,kk,2),'w');
text(trajectory(i,kk,1),trajectory(i,kk,2),legs_id{kk},'Color',[colors(kk,1) colors(kk,2) colors(kk,3)],'FontSize',14);
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: %3d %3d', legs_id{kk}, trajectory(i,kk,1), trajectory(i,kk,2))];
end
hold off;
drawnow
break
else
continue;
end
end
end
startframe = getappdata(hMainGui, 'start_frame');
if (~get(handles.ManualInitiate,'Value') && startframe>1)
for k = startframe-1 : -1 : 1
Im = (imread([seg_dir 'img_' num2str(k) '.png']));
Imroi = imread([seg_dir 'roi_' num2str(k) '.png']);
% Fix image/segmentation irregularities
Imwork = double(Im(:,:,1) == 255) .* Imroi;
if (nLegs>6)
Imwork = Imwork - (bwdist(imerode(Imroi,strel('disk',6)))<15);
Imwork = bwareaopen(Imwork>0,5);
else
Imwork = Imwork - (bwdist(imerode(Imroi,se))<10);
Imwork = bwareaopen(Imwork>0,3);
end
[locY,locX] = find(imerode(Imroi,se) > 0);
[centre_of_mass,theta] = findCoM(locX,locY);
if (abs(theta - CoM(k+1,3)) > 90 && abs(theta - CoM(k+1,3)) < 270)
theta = mod(theta + 180,360);
end
CoM(k, :) = [centre_of_mass, theta];
clear raw_tips;
clear raw_normtips;
[raw_tips, raw_normtips] = findtips(Imwork, Imroi, locX, locY, centre_of_mass, theta);
x_t1 = raw_normtips;
x_t0 = reshape(norm_trajectory(k+1,:),[nLegs 2]);
target_indices = hungarianlinker(x_t0, x_t1, max_distance);
for kk = 1:length(target_indices)
if (target_indices(kk) > 0)
norm_trajectory(k, kk, :) = raw_normtips(target_indices(kk),:);
trajectory(k, kk, :) = raw_tips(target_indices(kk),:);
else
norm_trajectory(k, kk, :) = 0;
trajectory(k, kk, :) = 0;
end
end
leftoveridx = find(hungarianlinker(raw_normtips, x_t0, max_distance)==-1);
x_t1 = raw_normtips(leftoveridx,:);
x_t2 = raw_tips(leftoveridx,:);
last_seen_tips = reshape(norm_trajectory(k,:),[nLegs 2]);
unassigned_idx = find(last_seen_tips(:,1) == 0);
for kk = 1:length(unassigned_idx)
if(eval(['handles.' legs_id{unassigned_idx(kk)} '.Value']))
continue;
end
idx = find(norm_trajectory(1:startframe,unassigned_idx(kk),1),1,'last');
last_seen_tips(unassigned_idx(kk),:) = reshape(norm_trajectory(idx,unassigned_idx(kk),:), [1 2]);
end
if (~isempty(unassigned_idx) && ~isempty(x_t1))
C = hungarianlinker(last_seen_tips(unassigned_idx,:), x_t1, 1.25*max_distance);
for l = 1:length(C)
if (C(l) ~= -1)
norm_trajectory(k,unassigned_idx(l), :) = x_t1(C(l), :);
trajectory(k,unassigned_idx(l), :) = x_t2(C(l), :);
end
end
end
end
setappdata(hMainGui, 'start_frame', 1);
end
if (strcmp(handles.Tracking.String, 'Tracking') || strcmp(handles.Tracking.String, 'Resume'))
handles.Tracking.String = 'Pause';
else
if (~strcmp(handles.Tracking.String, 'Initial'))
handles.Tracking.String = 'Resume';
end
end
skip = 1;
while (strcmp(handles.Tracking.String, 'Pause'))
setappdata(hMainGui, 'current_frame', getappdata(hMainGui, 'current_frame') + skip);
i = getappdata(hMainGui, 'current_frame');
if (i>end_frame)
setappdata(hMainGui, 'current_frame', end_frame);
break;
end
handles.Progress.String = ['Tracking Progress: ' num2str(i) '/' num2str(length(img_list))];
handles.text.String = ['Current frame: ' num2str(i)];
% Load necessary images
Im = (imread([seg_dir 'img_' num2str(i) '.png']));
Imroi = imread([seg_dir 'roi_' num2str(i) '.png']);
% Fix image/segmentation irregularities
Imwork = double(Im(:,:,1) == 255) .* Imroi;
[locY,locX] = find(imerode(Imroi,se) > 0);
if (nLegs>6)
Imwork = Imwork - (bwdist(imerode(Imroi,strel('disk',6)))<15);
Imwork = bwareaopen(Imwork>0,5);
else
Imwork = Imwork - (bwdist(imerode(Imroi,se))<10);
Imwork = bwareaopen(Imwork>0,3);
end
%Centre_of_Mass
[centre_of_mass,theta] = findCoM(locX,locY);
if (abs(theta - CoM(i-skip,3)) > 90 && abs(theta - CoM(i-skip,3)) < 270)
theta = mod(theta + 180,360);
end
CoM(i, :) = [centre_of_mass, theta];
clear raw_tips;
clear raw_normtips;
[raw_tips, raw_normtips] = findtips(Imwork, Imroi, locX, locY, centre_of_mass, theta);
x_t1 = raw_normtips;
x_t0 = reshape(norm_trajectory(i-1,:),[nLegs 2]);
target_indices = hungarianlinker(x_t0, x_t1, max_distance);
for kk = 1:length(target_indices)
if (target_indices(kk) > 0)
norm_trajectory(i, kk, :) = raw_normtips(target_indices(kk),:);
trajectory(i, kk, :) = raw_tips(target_indices(kk),:);
else
norm_trajectory(i, kk, :) = 0;
trajectory(i, kk, :) = 0;
end
end
leftoveridx = find(hungarianlinker(raw_normtips, x_t0, max_distance)==-1);
x_t1 = raw_normtips(leftoveridx,:);
x_t2 = raw_tips(leftoveridx,:);
last_seen_tips = reshape(norm_trajectory(i,:),[nLegs 2]);
unassigned_idx = find(last_seen_tips(:,1) == 0);
for kk = 1:length(unassigned_idx)
if(eval(['handles.' legs_id{unassigned_idx(kk)} '.Value']))
continue;
end
idx = find(norm_trajectory(1:i,unassigned_idx(kk),1),1,'last');
last_seen_tips(unassigned_idx(kk),:) = reshape(norm_trajectory(idx,unassigned_idx(kk),:), [1 2]);
end
if (~isempty(unassigned_idx) && ~isempty(x_t1))
C = hungarianlinker(last_seen_tips(unassigned_idx,:), x_t1, 1.25*max_distance);
for l = 1:length(C)
if (C(l) ~= -1)
norm_trajectory(i,unassigned_idx(l), :) = x_t1(C(l), :);
trajectory(i,unassigned_idx(l), :) = x_t2(C(l), :);
end
end
end
handles.GoToDropdown.Value = i;
handles.Tracking_Text.String = '';
oriIm = im2double(imread([data_dir img_list(i).name]));
imshow(oriIm);
hold on;
scatter(CoM(i,1)+sind(CoM(i,3))*.157*bodylength,CoM(i,2)-cosd(CoM(i,3))*.157*bodylength,'w*');
for kk = 1:nLegs
if (eval(['handles.' legs_id{kk} '.Value']))
trajectory(i,kk,1) = 0;
trajectory(i,kk,2) = 0;
norm_trajectory(i,kk,1) = 0;
norm_trajectory(i,kk,2) = 0;
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
continue;
end
if(trajectory(i,kk,1)~=0)
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: %3d %3d', legs_id{kk}, trajectory(i,kk,1), trajectory(i,kk,2))];
scatter(trajectory(i,kk,1),trajectory(i,kk,2),'w');
text(trajectory(i,kk,1),trajectory(i,kk,2),legs_id{kk},'Color',[colors(kk,1) colors(kk,2) colors(kk,3)],'FontSize',14);
else
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
end
end
hold off;
drawnow
% Update Display
nLegs = 8 - handles.L1.Value - handles.L2.Value - handles.L3.Value - handles.R1.Value - handles.R2.Value - handles.R3.Value - handles.L4.Value - handles.R4.Value;
if(length(str2num(handles.Tracking_Text.String(:,9:11))) < nLegs)
set(handles.Missing, 'BackgroundColor', [1 0 0]);
else
set(handles.Missing, 'BackgroundColor', [0 1 0]);
end
setappdata(hMainGui, 'CoM' , CoM);
setappdata(hMainGui, 'trajectory' , trajectory);
setappdata(hMainGui, 'norm_trajectory' , norm_trajectory);
handles.GoToDropdown.String = 1:find(CoM(:,1),1,'last');
end
if (getappdata(hMainGui, 'current_frame') == end_frame)
save([output_dir 'CoM.mat'],'CoM');
save([output_dir 'trajectory.mat'],'trajectory');
save([output_dir 'norm_trajectory.mat'],'norm_trajectory');
csvwrite([output_dir 'CoM.csv'],CoM);
csvwrite([output_dir 'trajectory.csv'],trajectory);
csvwrite([output_dir 'norm_trajectory.csv'],norm_trajectory);
handles.Tracking.String = 'Complete';
handles.Text_Display.String = 'Tracking Complete';
handles.VideoStart.Visible = 'On';
handles.VideoEnd.Visible = 'On';
handles.VideoStartFrame.Visible = 'On';
handles.VideoEndFrame.Visible = 'On';
handles.VideoStartFrame.String = num2str(getappdata(hMainGui, 'start_frame'));
handles.VideoEndFrame.String = num2str(end_frame);
end
end
%% --- Mouse cursor location in axis
function fh_wbmfcn(varargin)
% WindowButtonMotionFcn for the figure.
S = varargin{3}; % Get the structure.
F = get(S.fh,'currentpoint'); % The current point w.r.t the figure.
% Figure out of the current point is over the axes or not -> logicals.
tf1 = (S.fh.Position(3)-512)/2 <= F(1) && F(1) <= (S.fh.Position(3)+512)/2;
tf2 = (S.fh.Position(4)-512) <= F(2) && F(2) <= S.fh.Position(4);
if tf1 && tf2
% Calculate the current point w.r.t. the axes.
Cx = round(F(1) - (S.fh.Position(3)-512)/2);
Cy = round(S.fh.Position(4) - F(2));
% The mouse location is displayed at handles.Position_Text.
set(S.tx,'str',num2str([Cx,Cy],'%3.0f %3.0f'))
end
%% --- Double click to label tip position of a leg
function clicker(h,~,handles)
hMainGui = getappdata(0, 'hMainGui');
nLegs = 8 - handles.L4.Value - handles.R4.Value;
if (nLegs > 6)
colors = [1 0 0; 0 1 0; 0 0 1; 1 0 0.5; 1 1 0; 0 1 1; 1 0 1; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3','L4', 'R1', 'R2', 'R3','R4'};
switch get(get(handles.Labelling_Panel, 'SelectedObject'), 'Tag');
case 'Leg_L1', id = 1;
case 'Leg_L2', id = 2;
case 'Leg_L3', id = 3;
case 'Leg_L4', id = 4;
case 'Leg_R1', id = 5;
case 'Leg_R2', id = 6;
case 'Leg_R3', id = 7;
case 'Leg_R4', id = 8;
end
else
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1; 1 0 0.5; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
switch get(get(handles.Labelling_Panel, 'SelectedObject'), 'Tag');
case 'Leg_L1', id = 1;
case 'Leg_L2', id = 2;
case 'Leg_L3', id = 3;
case 'Leg_R1', id = 4;
case 'Leg_R2', id = 5;
case 'Leg_R3', id = 6;
end
end
F = get(h, 'currentpoint');
if (strcmp(get(h, 'selectiontype'),'open') && (handles.figMain.Position(3)-512)/2 <= F(1) && F(1) <= (handles.figMain.Position(3)+512)/2 && (handles.figMain.Position(4)-512) <= F(2) && F(2) <= handles.figMain.Position(4))
Cx = round(F(1) - (handles.figMain.Position(3)-512)/2);
Cy = round(handles.figMain.Position(4) - F(2));
if (strcmp(handles.Annotation.String,'Save and Exit'))
handles.Tracking_Text.String(id,:) = sprintf('Leg %2s: %3d %3d', legs_id{id}, Cx, Cy);
for i = 1: length(handles.figMain.CurrentAxes.Children)-2
if(strcmp(handles.figMain.CurrentAxes.Children(i).Type,'text') && strcmp(handles.figMain.CurrentAxes.Children(i).String,legs_id{id}))
delete(handles.figMain.CurrentAxes.Children(i:i+1));
end
end
hold on
scatter(Cx,Cy,'w');
text(Cx,Cy,legs_id{id},'Color',[colors(id,1) colors(id,2) colors(id,3)],'FontSize',14);
hold off
end
end
function update_display(hObject, eventdata, handles)
nLegs = 8 - handles.L1.Value - handles.L2.Value - handles.L3.Value - handles.R1.Value - handles.R2.Value - handles.R3.Value - handles.L4.Value - handles.R4.Value;
if(length(str2num(handles.Tracking_Text.String(:,9:11))) < nLegs)
set(handles.Missing, 'BackgroundColor', [1 0 0]);
else
set(handles.Missing, 'BackgroundColor', [0 1 0]);
end
%% --- Executes when selected object is changed in Labelling_Panel.
function Labelling_Panel_SelectionChangedFcn(hObject, eventdata, handles)
% hObject handle to the selected object in Labelling_Panel
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if (strcmp(handles.Tracking.String,'Resume'))
switch get(get(handles.Labelling_Panel, 'SelectedObject'), 'Tag');
case 'Leg_L1', set(handles.Text_Display,'String','Selecting leg L1');
case 'Leg_L2', set(handles.Text_Display,'String','Selecting leg L2');
case 'Leg_L3', set(handles.Text_Display,'String','Selecting leg L3');
case 'Leg_R1', set(handles.Text_Display,'String','Selecting leg R1');
case 'Leg_R2', set(handles.Text_Display,'String','Selecting leg R2');
case 'Leg_R3', set(handles.Text_Display,'String','Selecting leg R3');
case 'Leg_L4', set(handles.Text_Display,'String','Selecting leg L4');
case 'Leg_R4', set(handles.Text_Display,'String','Selecting leg R4');
end
end
%% --- Executes on button press in Video.
function Video_Callback(hObject, eventdata, handles)
% hObject handle to Video (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
data_dir = getappdata(hMainGui, 'data_dir');
bodylength = getappdata(hMainGui, 'bodylength');
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
tracking_dir = ['./Results/Tracking' sub_dir '/'];
if (exist(['./Results/Tracking' sub_dir '/trajectory.mat']))
Video_base(data_dir,30,str2num(handles.Video_Step.String),str2num(handles.VideoStartFrame.String),str2num(handles.VideoEndFrame.String), bodylength);
else
handles.Text_Display.String = 'Please ensure that tracking has been completed first.';
end
%% --- Executes on selection change in GoToDropdown.
function GoToDropdown_Callback(hObject, eventdata, handles)
% hObject handle to GoToDropdown (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns GoToDropdown contents as cell array
% contents{get(hObject,'Value')} returns selected item from GoToDropdown
hMainGui = getappdata(0, 'hMainGui');
i = handles.GoToDropdown.Value;
setappdata(hMainGui,'current_frame',i);
handles.text.String = ['Current frame: ' num2str(i)];
data_dir = getappdata(hMainGui, 'data_dir');
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
data_dir = ['./Data' sub_dir '/'];
img_list = load_img_list(data_dir);
oriIm = im2double(imread([data_dir img_list(i).name]));
imshow(oriIm);
display = handles.ChooseDisplay.Value;
switch display
case 1
handles.GoToDropdown.String = 1:length(img_list);
imshow(oriIm);
case 2
seg_dir = ['./Results/SegmentedImages' sub_dir '/'];
roi_list = dir([seg_dir 'roi_*.png']);
handles.GoToDropdown.String = 1:length(roi_list);
imshow([seg_dir 'roi_' num2str(i) '.png']);
case 3
seg_dir = ['./Results/SegmentedImages' sub_dir '/'];
seg_list = dir([seg_dir 'img_*.png']);
handles.GoToDropdown.String = 1:length(seg_list);
imshow([seg_dir 'img_' num2str(i) '.png']);
case 4
trajectory = getappdata(hMainGui, 'trajectory');
CoM = getappdata(hMainGui, 'CoM');
bodylength = getappdata(hMainGui, 'bodylength');
startframe = 1;
handles.Tracking_Text.String = '';
i = handles.GoToDropdown.Value + startframe - 1;
setappdata(hMainGui,'current_frame',i);
handles.text.String = ['Current frame: ' num2str(i)];
oriIm = im2double(imread([data_dir img_list(i).name]));
imshow(oriIm);
handles.GoToDropdown.String = 1:length(trajectory);
nLegs = size(trajectory,2);
if (nLegs > 6)
colors = [1 0 0; 0 1 0; 0 0 1; 1 0 0.5; 1 1 0; 0 1 1; 1 0 1; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3','L4', 'R1', 'R2', 'R3','R4'};
else
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1; 1 0 0.5; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
end
hold on;
scatter(CoM(i,1)+sind(CoM(i,3))*.157*bodylength,CoM(i,2)-cosd(CoM(i,3))*.157*bodylength,'w*');
for kk = 1:nLegs
if(eval(['handles.' legs_id{kk} '.Value']))
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
continue;
end
if(trajectory(i,kk,1)~=0)
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: %3d %3d', legs_id{kk}, trajectory(i,kk,1), trajectory(i,kk,2))];
scatter(trajectory(i,kk,1),trajectory(i,kk,2),'w');
text(trajectory(i,kk,1),trajectory(i,kk,2),legs_id{kk},'Color',[colors(kk,1) colors(kk,2) colors(kk,3)],'FontSize',14);
else
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
end
end
hold off;
drawnow
% Update Display
nLegs = 8 - handles.L1.Value - handles.L2.Value - handles.L3.Value - handles.R1.Value - handles.R2.Value - handles.R3.Value - handles.L4.Value - handles.R4.Value;
if(length(str2num(handles.Tracking_Text.String(:,9:11))) < nLegs)
set(handles.Missing, 'BackgroundColor', [1 0 0]);
else
set(handles.Missing, 'BackgroundColor', [0 1 0]);
end
end
%% --- Executes on button press in BatchProcess.
function BatchProcess_Callback(hObject, eventdata, handles)
% hObject handle to BatchProcess (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
prompt = {'Input 0 for segmentation only or 1 to include tracking'};
dlg_title = 'Options for batch process';
num_lines = 1;
defaultans = {'0'};
answer = inputdlg(prompt,dlg_title,num_lines,defaultans);
if(isempty(answer))
return;
end
answer = ~(answer{1}=='0');
data_dir = uipickfiles;
try
if(data_dir==0)
return;
end
catch
end
if(isempty(data_dir))
return;
end
for i = 1 : length(data_dir)
ProcessFolder(data_dir{i}, answer, handles);
end
function ProcessFolder(data_dir, answer, handles)
score_thres = str2num(handles.SegmentationEdit.String);
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
if(exist(data_dir) && isempty(dir([data_dir '/*.tif'])) && isempty(dir([data_dir '/*.bmp'])))
dir_fn = dir(data_dir);
for i_dir = 1:length(dir_fn)-2
if (dir_fn(i_dir+2).isdir)
ProcessFolder([data_dir '/' dir_fn(i_dir+2).name], answer, handles);
pause(1);
end
end
else
data_dir = ['./Data' sub_dir];
handles.Text_Display.String = ['Performing segmentation for the folder: ' data_dir];
fprintf('Performing segmentation for the folder: %s.\n', data_dir);
pause(1);
try
Segmentation(data_dir,score_thres,0);
catch MExc
fprintf('An error occured during segmentation for the folder: %s.\n', data_dir);
disp('Execution will continue.');
disp(MExc.message);
end
handles.Text_Display.String = ['Completed segmentation for the folder: ' data_dir];
fprintf('Completed segmentation for the folder: %s.\n', data_dir);
pause(1)
if (answer)
handles.Text_Display.String = ['Performing tracking for the folder: ' data_dir];
fprintf('Performing tracking for the folder: %s.\n', data_dir);
pause(1);
try
Tracking_Base(data_dir);
catch MExc
fprintf('An error occured during tracking for the folder: %s.\n', data_dir);
disp('Execution will continue.');
disp(MExc.message);
end
handles.Text_Display.String = ['Completed tracking for the folder: ' data_dir];
fprintf('Completed tracking for the folder: %s.\n', data_dir);
pause(1);
end
end
%% --- Change display mode
function ChooseDisplay_Callback(hObject, eventdata, handles)
% hObject handle to ChooseDisplay (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns ChooseDisplay contents as cell array
% contents{get(hObject,'Value')} returns selected item from ChooseDisplay
GoToDropdown_Callback(hObject, eventdata, handles);
%% --- Change start frame of make video
function VideoStartFrame_Callback(hObject, eventdata, handles)
% hObject handle to VideoStartFrame (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
if (str2num(hObject.String) < 1)
hObject.String = '1';
end
%% --- Change end frame of make video
function VideoEndFrame_Callback(hObject, eventdata, handles)
% hObject handle to VideoEndFrame (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
CoM = getappdata(hMainGui, 'CoM');
if (str2num(hObject.String) > length(CoM))
hObject.String = num2str(length(CoM));
end
if (str2num(hObject.String) < str2num(handles.VideoStartFrame.String))
hObject.String = num2str(str2num(handles.VideoStartFrame.String)+str2num(handles.Video_Step.String));
end
%% --- Change segmentation threshold via slider
function SegmentationSlider_Callback(hObject, eventdata, handles)
% hObject handle to SegmentationSlider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.SegmentationEdit.String = num2str(handles.SegmentationSlider.Value);
%% --- Change segmentation threshold via numerical input
function SegmentationEdit_Callback(hObject, eventdata, handles)
% hObject handle to SegmentationEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of SegmentationEdit as text
% str2double(get(hObject,'String')) returns contents of SegmentationEdit as a double
handles.SegmentationSlider.Value = str2num(handles.SegmentationEdit.String);
%% --- Change foreground threshold via slider
function ForegroundSlider_Callback(hObject, eventdata, handles)
% hObject handle to SegmentationSlider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.ForegroundEdit.String = num2str(handles.ForegroundSlider.Value);
%% --- Change foreground threshold via numerical input
function ForegroundEdit_Callback(hObject, eventdata, handles)
% hObject handle to SegmentationEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of SegmentationEdit as text
% str2double(get(hObject,'String')) returns contents of SegmentationEdit as a double
handles.ForegroundSlider.Value = str2num(handles.ForegroundEdit.String);
%% --- Executes when figMain is resized.
function figMain_SizeChangedFcn(hObject, eventdata, handles)
% hObject handle to figMain (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S.fh = handles.figMain;
% Fix the central figure axis in pixel coordinates
S.ax = gca;
set(S.ax,'unit','pix','position',[(handles.figMain.Position(3)-512)/2 handles.figMain.Position(4)-512 512 512]);
%% --- Executes on button press in ViewerMode.
function ViewerMode_Callback(hObject, eventdata, handles)
% hObject handle to ViewerMode (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of ViewerMode
if (handles.ViewerMode.Value)
handles.ViewTracking.Visible = 'On';
handles.ViewTracking.Enable = 'On';
else
handles.ViewTracking.Visible = 'Off';
handles.ViewTracking.Enable = 'Off';
end
%% --- Executes on button press in ViewTracking.
function ViewTracking_Callback(hObject, eventdata, handles)
% hObject handle to ViewTracking (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
data_dir = getappdata(hMainGui, 'data_dir');
if(isempty(getappdata(hMainGui, 'trajectory')))
setappdata(hMainGui, 'CoM', []);
setappdata(hMainGui, 'trajectory', []);
setappdata(hMainGui, 'norm_trajectory', []);
setappdata(hMainGui, 'start_frame', []);
end
bodylength = getappdata(hMainGui, 'bodylength');
CoM = getappdata(hMainGui, 'CoM');
trajectory = getappdata(hMainGui, 'trajectory');
norm_trajectory = getappdata(hMainGui, 'norm_trajectory');
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
seg_dir = ['./Results/SegmentedImages' sub_dir '/'];
data_dir = ['./Data' sub_dir '/'];
img_list = load_img_list(data_dir);
output_dir = ['./Results/Tracking/' sub_dir '/'];
if(~exist(output_dir))
mkdir(output_dir);
end
if(length(handles.ChooseDisplay.String)<4)
handles.ChooseDisplay.String{4} = 'Tracking';
end
nLegs = 8 - handles.L4.Value - handles.R4.Value;
if (nLegs > 6)
colors = [1 0 0; 0 1 0; 0 0 1; 1 0 0.5; 1 1 0; 0 1 1; 1 0 1; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3','L4', 'R1', 'R2', 'R3','R4'};
else
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1; 1 0 0.5; 1 0.5 0];
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
end
end_frame = length(dir([seg_dir 'img_*.png']));
if (strcmp(handles.ViewTracking.String, 'View Tracking'))
handles.ViewTracking.String = 'Pause Viewing';
else
handles.ViewTracking.String = 'View Tracking';
end
while (strcmp(handles.ViewTracking.String, 'Pause Viewing'))
setappdata(hMainGui, 'current_frame', getappdata(hMainGui, 'current_frame') + 1);
i = getappdata(hMainGui, 'current_frame');
if (i>end_frame)
setappdata(hMainGui, 'current_frame', end_frame);
break;
end
if(~isempty(trajectory))
handles.text.String = ['Current frame: ' num2str(i)];
handles.GoToDropdown.Value = i;
handles.Tracking_Text.String = '';
imshow([data_dir img_list(i).name]);
hold on;
scatter(CoM(i,1)+sind(CoM(i,3))*.157*bodylength,CoM(i,2)-cosd(CoM(i,3))*.157*bodylength,'w*');
for kk = 1:nLegs
if(eval(['handles.' legs_id{kk} '.Value']))
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
end
if(trajectory(i,kk,1)~=0)
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: %3d %3d', legs_id{kk}, trajectory(i,kk,1), trajectory(i,kk,2))];
scatter(trajectory(i,kk,1),trajectory(i,kk,2),'w');
text(trajectory(i,kk,1),trajectory(i,kk,2),legs_id{kk},'Color',[colors(kk,1) colors(kk,2) colors(kk,3)],'FontSize',14);
else
handles.Tracking_Text.String = [handles.Tracking_Text.String; sprintf('Leg %2s: ', legs_id{kk})];
end
end
hold off;
drawnow
% Update Display
nLegs = 8 - handles.L1.Value - handles.L2.Value - handles.L3.Value - handles.R1.Value - handles.R2.Value - handles.R3.Value - handles.L4.Value - handles.R4.Value;
if(length(str2num(handles.Tracking_Text.String(:,9:11))) < nLegs)
set(handles.Missing, 'BackgroundColor', [1 0 0]);
else
set(handles.Missing, 'BackgroundColor', [0 1 0]);
end
end
end
%% --- Executes on button press in DataProcess.
function DataProcess_Callback(hObject, eventdata, handles)
% hObject handle to DataProcess (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
if(isempty(getappdata(hMainGui, 'data_dir')))
set(handles.Text_Display, 'String', 'Analysing tracked data.');
pause(0.5);
tracking_dir = uigetdir('./Results/Tracking/');
defaultfps = {'1000'};
fps = inputdlg({'Recording FPS for dataset?'},'Input Recording FPS',1,defaultfps);
fps = str2num(fps{:});
defaultscale = {'11.0'};
scale = inputdlg({'Image Size (mm)?'},'Image Size Input',1,defaultscale);
scale = str2double(scale{:});
defaultbodylength = {'2.90'};
bodylength = inputdlg({'Body length (mm)?'},'Input Body Length',1,defaultbodylength);
bodylength = str2double(bodylength{:});
DataProcessing_New(fps, tracking_dir, scale, bodylength);
set(handles.Text_Display, 'String', 'Data Processing complete.');
else
data_dir = getappdata(hMainGui, 'data_dir');
defaultfps = {'1000'};
fps = inputdlg({'Recording FPS for dataset?'},'Input Recording FPS',1,defaultfps);
fps = str2num(fps{:});
defaultscale = {'11.0'};
scale = inputdlg({'Image Size (mm)?'},'Image Size Input',1,defaultscale);
scale = str2double(scale{:});
defaultbodylength = {'2.90'};
bodylength = inputdlg({'Body length (mm)?'},'Input Body Length',1,defaultbodylength);
bodylength = str2double(bodylength{:});
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
tracking_dir = ['./Results/Tracking' sub_dir '/'];
if(~exist([tracking_dir 'CoM.mat']))
handles.Text_Display.String = 'Please ensure that tracking has been completed first.';
else
set(handles.Text_Display, 'String', 'Analysing tracked data.');
pause(0.5);
DataProcessing_New(fps, tracking_dir, scale, bodylength);
set(handles.Text_Display, 'String', 'Data Processing complete.');
end
end
%% --- Executes on button press in BatchDataProcess.
function BatchDataProcess_Callback(hObject, eventdata, handles)
% hObject handle to BatchDataProcess (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data_dir = uipickfiles('filterspec',[pwd '/Results/Tracking']);
defaultfps = {'1000'};
fps = inputdlg({'Recording FPS for dataset?'},'Input Recording FPS',1,defaultfps);
fps = str2num(fps{:});
defaultscale = {'11.0'};
scale = inputdlg({'Image Size (mm)?'},'Image Size Input',1,defaultscale);
scale = str2double(scale{:});
defaultbodylength = {'2.90'};
bodylength = inputdlg({'Body length (mm)?'},'Input Body Length',1,defaultbodylength);
bodylength = str2double(bodylength{:});
try
if(data_dir==0)
return;
end
catch
end
if(isempty(data_dir))
return;
end
for i = 1 : length(data_dir)
AnalyseFolder(data_dir{i}, fps, scale, bodylength);
end
function AnalyseFolder(data_dir, fps, scale, bodylength)
pos_bs = strfind(data_dir,'Results');
sub_dir = data_dir(pos_bs(end)+length('Results/Tracking/'):length(data_dir));
output_dir = ['./Results/Tracking/' sub_dir '/'];
if(~exist([output_dir 'trajectory.mat']))
dir_fn = dir(output_dir);
for i_dir = 1:length(dir_fn)-2
AnalyseFolder([output_dir '/' dir_fn(i_dir+2).name], fps, scale, bodylength);
pause(1);
end
else
try
DataProcessing_New(fps, output_dir, scale, bodylength);
catch MExc
fprintf('An error occured during data processing for the folder: %s.\n', data_dir);
disp('Execution will continue.');
disp(MExc.message);
end
end
%% --- Executes on key press with focus on figMain or any of its controls.
function figMain_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject handle to figMain (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.FIGURE)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
trajectory = getappdata(hMainGui, 'trajectory');
last = max(length(trajectory),1);
switch eventdata.Key
case '1', handles.Leg_L1.Value = 1;
case '2', handles.Leg_L2.Value = 1;
case '3', handles.Leg_L3.Value = 1;
case '4', handles.Leg_R1.Value = 1;
case '5', handles.Leg_R2.Value = 1;
case '6', handles.Leg_R3.Value = 1;
case '7', handles.Leg_L4.Value = 1;
case '8', handles.Leg_R4.Value = 1;
case 'home', handles.GoToDropdown.Value = 1; GoToDropdown_Callback(hObject, eventdata, handles);
case 'end', handles.GoToDropdown.Value = last; GoToDropdown_Callback(hObject, eventdata, handles);
case 'uparrow', handles.ChooseDisplay.Value = max(handles.ChooseDisplay.Value-1,1);
ChooseDisplay_Callback(hObject, eventdata, handles);
case 'downarrow', handles.ChooseDisplay.Value = min(handles.ChooseDisplay.Value+1, length(handles.ChooseDisplay.String));
ChooseDisplay_Callback(hObject, eventdata, handles);
end
if(strcmp(handles.nextframe.Enable,'on'))
switch eventdata.Key
case 'leftarrow',
try
prevframe_Callback(hObject, eventdata, handles);
catch
end
case 'rightarrow',
try
nextframe_Callback(hObject, eventdata, handles);
catch
end
end
end
% --- Executes on slider movement.
function ImageSizeSlider_Callback(hObject, eventdata, handles)
% hObject handle to ImageSizeSlider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.ImageSize.String = num2str(hObject.Value);
function ImageSize_Callback(hObject, eventdata, handles)
% hObject handle to ImageSize (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ImageSize as text
% str2double(get(hObject,'String')) returns contents of ImageSize as a double
handles.ImageSizeSlider.Value = str2num(hObject.String);
% --- Executes on button press in ResetImageSize.
function ResetImageSize_Callback(hObject, eventdata, handles)
% hObject handle to ResetImageSize (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
bodylength = str2num(handles.BodyLength.String);
if(bodylength>0)
handles.ImageSizeSlider.Value = round(128/bodylength*11*2)/2;
handles.ImageSize.String = num2str(round(128/bodylength*11*2)/2);
else
handles.ImageSizeSlider.Value = 11;
handles.ImageSize.String = num2str(11);
end
%% --- Executes when user attempts to close figMain.
function figMain_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figMain (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Construct a questdlg with three options
hMainGui = getappdata(0, 'hMainGui');
choice = questdlg('Are you sure?', ...
'FLLIT', ...
'Save and Exit', 'Exit without Saving', 'Cancel', 'Cancel');
% Handle response
switch choice
case 'Save and Exit'
if(~isempty(getappdata(hMainGui, 'trajectory')))
data_dir = getappdata(hMainGui, 'data_dir');
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
output_dir = ['./Results/SegmentedImages' sub_dir '/'];
trajectory = getappdata(hMainGui, 'trajectory');
norm_trajectory = getappdata(hMainGui, 'norm_trajectory');
CoM = getappdata(hMainGui, 'CoM');
save([output_dir 'CoM.mat'],'CoM');
save([output_dir 'trajectory.mat'],'trajectory');
save([output_dir 'norm_trajectory.mat'],'norm_trajectory');
csvwrite([output_dir 'CoM.csv'],CoM);
csvwrite([output_dir 'trajectory.csv'],trajectory);
csvwrite([output_dir 'norm_trajectory.csv'],norm_trajectory);
display('Saving... Exiting...');
else
display('Nothing to save! Exiting...');
end
T = timerfind;
if (~isempty(T))
stop(T);
delete(T);
end
clear T
delete(hObject);
case 'Exit without Saving'
display('Exiting...');
T = timerfind;
if (~isempty(T))
stop(T);
delete(T);
end
clear T
delete(hObject);
case 'Cancel'
return;
end
% --- Executes on button press in Foreground.
function Foreground_Callback(hObject, eventdata, handles)
% hObject handle to Foreground (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
data_dir = getappdata(hMainGui, 'data_dir');
set(handles.Text_Display, 'String', 'Starting foreground extraction.');
pause(1);
handles.axes1 = gcf;
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
data_dir = ['./Data' sub_dir '/'];
output_dir = ['./Results/SegmentedImages' sub_dir '/'];
if(~exist(output_dir))
mkdir(output_dir);
end
img_list = load_img_list(data_dir);
I = imread([data_dir img_list(1).name]);
if(~exist([data_dir 'Background/Background.png']) || handles.OverrideBackground.Value==1)
[~,~,ref_img,~] = video2background(data_dir, sub_dir);
if(~exist([data_dir 'Background']))
mkdir([data_dir 'Background'])
end
imwrite(uint8(ref_img),[data_dir 'Background/Background.png'], 'png');
else
ref_img = double(imread([data_dir 'Background/Background.png']));
end
imshow(uint8(ref_img));
set(handles.Text_Display, 'String', 'This is the background averaged over the dataset.');
pause(2);
if(length(handles.ChooseDisplay.String)<2)
handles.ChooseDisplay.String{2} = 'ROI';
end
handles.ChooseDisplay.Value = 2;
foreground_thres = handles.ForegroundSlider.Value;
set(handles.Text_Display, 'String', 'Extracting the region of interest.');
for i = 1 : length(img_list)
I = imread([data_dir img_list(i).name]);
I = double(I);
roi_img = (max(ref_img - I(:,:,1),0) ./ ref_img) > foreground_thres;
roi_img = bwareaopen(roi_img, 200);
handles.GoToDropdown.Value = i;
img_output = repmat(I/255,[1 1 3]);
img_output(:,:,3) = img_output(:,:,3) + roi_img;
imshow(img_output);
pause(0.01);
imwrite(roi_img,[output_dir 'roi_' num2str(i) '.png'],'png');
end
% --- Executes on button press in ViewBackground.
function ViewBackground_Callback(hObject, eventdata, handles)
% hObject handle to ViewBackground (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hMainGui = getappdata(0, 'hMainGui');
data_dir = getappdata(hMainGui, 'data_dir');
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
data_dir = ['./Data' sub_dir '/'];
if (~exist([data_dir 'Background/Background.png']))
set(handles.Text_Display, 'String', 'No valid Background/Background.png found.');
else
ref_img = imread([data_dir 'Background/Background.png']);
imshow(ref_img)
set(handles.Text_Display, 'String', 'Loaded Background/Background.png as background');
end
|
github
|
BII-wushuang/FLLIT-master
|
connectify.m
|
.m
|
FLLIT-master/src/connectify.m
| 2,905 |
utf_8
|
31614bbf2f02d96c33f38684ed9b3eb9
|
function Image = connectify(img, imroi, imseg)
%CONNECTIFY Find the disconnected components and group them leg-wise.
% Convert the pixel level segmentation result to an object level.
se1 = strel('disk',5);
se2 = strel('disk',0);
% Morphological operations to estimate the body of the fly
imbody = imerode(imroi,se1);
imbody = imdilate(imbody,se1);
% %figure, imshow(imfuse(imroi,imbody));
if (0)
imsk_old = bwmorph(img,'skel',Inf)*255;
imsk_new = bwmorph(skeleton(img) > 10, 'skel', Inf) * 255;
montage_image(:,:,1,1) = imsk_old;
montage_image(:,:,1,2) = imsk_new;
figure, montage(montage_image);
end
connComp = bwconncomp(img);
nRegions = connComp.NumObjects;
% Get information on the segmentation's centroid, medial axis with its
% end points and junctions. This will then be used to
% identify whether regions must be connected or not!
for cc = 1:nRegions
legpixels = connComp.PixelIdxList{cc};
[I,J] = ind2sub(size(img),legpixels);
connComp.centroid{cc} = [mean(I) mean(J)];
imleg = zeros(size(img));
imleg(legpixels) = 1;
[skr,rad] = skeleton(imleg);
imsk = bwmorph(skr > 10,'skel',Inf);
% Skeleton analysis: Get the end points.
[dmap,exy,jxy] = anaskel(imsk);
connComp.exy{cc} = exy;
connComp.jxy{cc} = jxy;
connComp.medialAxis{cc} = find(imsk > 0);
end
distThresh = 10; %17.5
PT1 = [];
PT2 = [];
for i = 1:nRegions
for j = i+1:nRegions
exyI = connComp.exy{i};
exyJ = connComp.exy{j};
[p1_,p2_] = checkToConnect(exyI,exyJ,distThresh);
PT1 = [PT1 p1_];
PT2 = [PT2 p2_];
end
end
Image = img;
npoints = size(PT1,2);
for i = 1:npoints
x = [PT1(1,i) PT2(1,i)];
y = [PT1(2,i) PT2(2,i)];
Image = func_DrawLine(Image,y(1),x(1),y(2),x(2),1);
%X = PT1(1,i):PT2(1,i);
%Y = round(interp1(x,y,X));
%ind = sub2ind(size(Image),Y,X);
%Image(ind) = 255;
end
end
function [pt1,pt2] = checkToConnect(exyI,exyJ,distThresh)
pt1 = [];
pt2 = [];
nendpoints_i = length(exyI(1,:));
for k = 1:nendpoints_i
A = bsxfun(@minus,exyJ,exyI(:,k));
distances = sqrt(sum(A.^2));
idx = find(distances < distThresh);
for i = 1:length(idx)
% exyJ(:,idx(i)) and exyI(:,k) are close endpoints of some two medial
% axis. Now must enforce directionality constraint
probableLeg1 = exyI(:,k) - exyI(:,~(k-1)+1);
probableLeg1 = probableLeg1./norm(probableLeg1);
%probableLeg2 = exyJ(:,~(idx(i)-1)+1) - exyJ(:,idx(i));
probableJoin = exyJ(:,idx(i)) - exyI(:,k);
probableJoin = - (probableJoin./norm(probableJoin));
theta = acosd(probableLeg1' * probableJoin);
if (theta > 120) %|| (theta < 30)
% If this also holds, then mark this point
pt1 = [pt1 exyI(:,k)];
pt2 = [pt2 exyJ(:,idx(i))];
end
end
end
end
|
github
|
BII-wushuang/FLLIT-master
|
Segmentation_Base.m
|
.m
|
FLLIT-master/src/Segmentation_Base.m
| 1,141 |
utf_8
|
ad553607debd1a8254b7acf918d2c9e1
|
%Classifier for leg segmentation
function Segmentation_Base (data_dir)
if(nargin<1)
data_dir = uigetdir('./Data');
end
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
data_dir = ['./Data' sub_dir '/'];
output_dir = ['./Results/SegmentedImages' sub_dir '/'];
if(~exist(output_dir))
mkdir(output_dir);
end
[thres, ~,~,ref_img,~] = video2background(data_dir, sub_dir);
img_list = load_img_list(data_dir);
for i_img = 1 : length(img_list)
I = imread([data_dir img_list(i_img).name]);
I = double(I);
I = padarray(I,[20 20],'replicate');
roi_img = (max(ref_img - I(:,:,1),0) ./ ref_img) > thres;
[pos_img,~,~] = leg_segment(I,ref_img,thres);
%pos_img = (filter_small_comp(pos_img,15) - imroi)>0.1;
show_img_output = repmat(double(I)/255,[1 1 3]);
show_img_output(:,:,1) = show_img_output(:,:,1) + pos_img;
imwrite(imcrop(show_img_output,[21 21 size(I,2)-41 size(I,1)-41]),[output_dir 'img_' num2str(i_img) '.png'],'png');
imwrite(imcrop(roi_img,[21 21 size(I,2)-41 size(I,1)-41]),[output_dir 'roi_' num2str(i_img) '.png'],'png');
end
end
|
github
|
BII-wushuang/FLLIT-master
|
clean_skeleton.m
|
.m
|
FLLIT-master/src/clean_skeleton.m
| 1,995 |
utf_8
|
a56e0b53522559dc4596367baa437d66
|
% A function to clean skeletons.
%
function [bw_body,bw_junction,img]=clean_skeleton(seg)
%thin process
img=bwmorph(seg,'skel','Inf');
%img=bwmorph(img,'spur');
% count the neighbours of the skeletons
neighbour_count=imfilter(uint8(img),ones(3));
bw_body=neighbour_count<=3 & img;
bw_junction=neighbour_count>3 & img;
bw_ends=neighbour_count<=2 & img;
%find the terminal segments
bw_ends=imreconstruct(bw_ends,bw_body);
CC = bwconncomp(bw_ends);
numPixels = cellfun(@numel,CC.PixelIdxList);
[idx]=find(numPixels<3);
while ~isempty(idx)
spur_length=2;
% Remove the terminal segments if they are too short
bw_body(bw_ends & ~bwareaopen(bw_ends, spur_length)) = false;
img=(bw_body+bw_junction)>0;
% Thin the binary image
img = bwmorph(img, 'skel', Inf);
%img=bwmorph(img,'spur');
neighbour_count = imfilter(uint8(img), ones(3));
bw_body = neighbour_count <=3 & img;
bw_junction = neighbour_count >3 & img;
bw_ends = neighbour_count <=2 & img;
% Find the terminal segments - i.e. those containing end points
bw_ends = imreconstruct(bw_ends, bw_body);
CC = bwconncomp(bw_ends);
numPixels = cellfun(@numel,CC.PixelIdxList);
[idx]=find(numPixels<2);
end
img=(bw_body+bw_junction)>0;
img_no_soma=img;
%new_img_thin_wo_nu=bwmorph(new_img_thin_wo_nu,'spur');
neighbour_count = imfilter(uint8(img_no_soma), ones(3));
bw_body = neighbour_count <=3 & img_no_soma;
%figure,imshow(bw_body)
bw_junction = neighbour_count >3 & img_no_soma;
% This is for removing small segments in between two junctions.
bw_ends = neighbour_count <=2 & img_no_soma;
% Find the terminal segments - i.e. those containing end points
bw_ends = imreconstruct(bw_ends, bw_body);
bw_non_terminal=bw_body.*~(bw_ends); % non terminals
CC = bwconncomp(bw_non_terminal);
numPixels = cellfun(@numel,CC.PixelIdxList);
[idx]=find(numPixels<2);
for jj=1:length(idx)
bw_junction(CC.PixelIdxList{idx(jj)})=true;
bw_body(CC.PixelIdxList{idx(jj)})=false;
end
end
|
github
|
BII-wushuang/FLLIT-master
|
uipickfiles.m
|
.m
|
FLLIT-master/src/uipickfiles.m
| 48,144 |
utf_8
|
a2c259c89144d8e1e2ce065bad663669
|
function out = uipickfiles(varargin)
%uipickfiles: GUI program to select files and/or folders.
%
% Syntax:
% files = uipickfiles('PropertyName',PropertyValue,...)
%
% The current folder can be changed by operating in the file navigator:
% double-clicking on a folder in the list or pressing Enter to move further
% down the tree, using the popup menu, clicking the up arrow button or
% pressing Backspace to move up the tree, typing a path in the box to move
% to any folder or right-clicking (control-click on Mac) on the path box to
% revisit a previously-visited folder. These folders are listed in order
% of when they were last visited (most recent at the top) and the list is
% saved between calls to uipickfiles. The list can be cleared or its
% maximum length changed with the items at the bottom of the menu.
% (Windows only: To go to a UNC-named resource you will have to type the
% UNC name in the path box, but all such visited resources will be
% remembered and listed along with the mapped drives.) The items in the
% file navigator can be sorted by name, modification date or size by
% clicking on the headers, though neither date nor size are displayed. All
% folders have zero size.
%
% Files can be added to the list by double-clicking or selecting files
% (non-contiguous selections are possible with the control key) and
% pressing the Add button. Control-F will select all the files listed in
% the navigator while control-A will select everything (Command instead of
% Control on the Mac). Since double-clicking a folder will open it,
% folders can be added only by selecting them and pressing the Add button.
% Files/folders in the list can be removed or re-ordered. Recall button
% will insert into the Selected Files list whatever files were returned the
% last time uipickfiles was run. When finished, a press of the Done button
% will return the full paths to the selected items in a cell array,
% structure array or character array. If the Cancel button or the escape
% key is pressed then zero is returned.
%
% The figure can be moved and resized in the usual way and this position is
% saved and used for subsequent calls to uipickfiles. The default position
% can be restored by double-clicking in a vacant region of the figure.
%
% The following optional property/value pairs can be specified as arguments
% to control the indicated behavior:
%
% Property Value
% ---------- ----------------------------------------------------------
% FilterSpec String to specify starting folder and/or file filter.
% Ex: 'C:\bin' will start up in that folder. '*.txt'
% will list only files ending in '.txt'. 'c:\bin\*.txt' will
% do both. Default is to start up in the current folder and
% list all files. Can be changed with the GUI.
%
% REFilter String containing a regular expression used to filter the
% file list. Ex: '\.m$|\.mat$' will list files ending in
% '.m' and '.mat'. Default is empty string. Can be used
% with FilterSpec and both filters are applied. Can be
% changed with the GUI.
%
% REDirs Logical flag indicating whether to apply the regular
% expression filter to folder names. Default is false which
% means that all folders are listed. Can be changed with the
% GUI.
%
% Type Two-column cell array where the first column contains file
% filters and the second column contains descriptions. If
% this property is specified an additional popup menu will
% appear below the File Filter and selecting an item will put
% that item into the File Filter. By default, the first item
% will be entered into the File Filter. For example,
% { '*.m', 'M-files' ;
% '*.mat', 'MAT-files' }.
% Can also be a cell vector of file filter strings in which
% case the descriptions will be the same as the file filters
% themselves.
% Must be a cell array even if there is only one entry.
%
% Prompt String containing a prompt appearing in the title bar of
% the figure. Default is 'Select files'.
%
% NumFiles Scalar or vector specifying number of files that must be
% selected. A scalar specifies an exact value; a two-element
% vector can be used to specify a range, [min max]. The
% function will not return unless the specified number of
% files have been chosen. Default is [] which accepts any
% number of files.
%
% Append Cell array of strings, structure array or char array
% containing a previously returned output from uipickfiles.
% Used to start up program with some entries in the Selected
% Files list. Any included files that no longer exist will
% not appear. Default is empty cell array, {}.
%
% Output String specifying the data type of the output: 'cell',
% 'struct' or 'char'. Specifying 'cell' produces a cell
% array of strings, the strings containing the full paths of
% the chosen files. 'Struct' returns a structure array like
% the result of the dir function except that the 'name' field
% contains a full path instead of just the file name. 'Char'
% returns a character array of the full paths. This is most
% useful when you have just one file and want it in a string
% instead of a cell array containing just one string. The
% default is 'cell'.
%
% All properties and values are case-insensitive and need only be
% unambiguous. For example,
%
% files = uipickfiles('num',1,'out','ch')
%
% is valid usage.
% Version: 1.15, 2 March 2012
% Author: Douglas M. Schwarz
% Email: dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
% Real_email = regexprep(Email,{'=','*'},{'@','.'})
% Copyright (c) 2007, Douglas M. Schwarz
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% * Redistributions of source code must retain the above copyright notice, this
% list of conditions and the following disclaimer.
%
% * Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
% FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
% SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
% OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
% Define properties and set default values.
prop.filterspec = [pwd '/Data'];
prop.refilter = '';
prop.redirs = false;
prop.type = {};
prop.prompt = 'Select data folder';
prop.numfiles = [];
prop.append = [];
prop.output = 'cell';
% Process inputs and set prop fields.
prop = parsepropval(prop,varargin{:});
% Validate FilterSpec property.
if isempty(prop.filterspec)
prop.filterspec = '*';
end
if ~ischar(prop.filterspec)
error('FilterSpec property must contain a string.')
end
% Validate REFilter property.
if ~ischar(prop.refilter)
error('REFilter property must contain a string.')
end
% Validate REDirs property.
if ~isscalar(prop.redirs)
error('REDirs property must contain a scalar.')
end
% Validate Type property.
if isempty(prop.type)
elseif iscellstr(prop.type) && isscalar(prop.type)
prop.type = repmat(prop.type(:),1,2);
elseif iscellstr(prop.type) && size(prop.type,2) == 2
else
error(['Type property must be empty or a cellstr vector or ',...
'a 2-column cellstr matrix.'])
end
% Validate Prompt property.
if ~ischar(prop.prompt)
error('Prompt property must contain a string.')
end
% Validate NumFiles property.
if numel(prop.numfiles) > 2 || any(prop.numfiles < 0)
error('NumFiles must be empty, a scalar or two-element vector.')
end
prop.numfiles = unique(prop.numfiles);
if isequal(prop.numfiles,1)
numstr = 'Select exactly 1 data folder.';
elseif length(prop.numfiles) == 1
numstr = sprintf('Select exactly %d items.',prop.numfiles);
else
numstr = sprintf('Select %d to %d items.',prop.numfiles);
end
% Validate Append property and initialize pick data.
if isstruct(prop.append) && isfield(prop.append,'name')
prop.append = {prop.append.name};
elseif ischar(prop.append)
prop.append = cellstr(prop.append);
end
if isempty(prop.append)
file_picks = {};
full_file_picks = {};
dir_picks = dir(' '); % Create empty directory structure.
elseif iscellstr(prop.append) && isvector(prop.append)
num_items = length(prop.append);
file_picks = cell(1,num_items);
full_file_picks = cell(1,num_items);
dir_fn = fieldnames(dir(' '));
dir_picks = repmat(cell2struct(cell(length(dir_fn),1),dir_fn(:)),...
num_items,1);
for item = 1:num_items
if exist(prop.append{item},'dir') && ...
~any(strcmp(full_file_picks,prop.append{item}))
full_file_picks{item} = prop.append{item};
[unused,fn,ext] = fileparts(prop.append{item});
file_picks{item} = [fn,ext];
temp = dir(fullfile(prop.append{item},'..'));
if ispc || ismac
thisdir = strcmpi({temp.name},[fn,ext]);
else
thisdir = strcmp({temp.name},[fn,ext]);
end
dir_picks(item) = temp(thisdir);
dir_picks(item).name = prop.append{item};
elseif exist(prop.append{item},'file') && ...
~any(strcmp(full_file_picks,prop.append{item}))
full_file_picks{item} = prop.append{item};
[unused,fn,ext] = fileparts(prop.append{item});
file_picks{item} = [fn,ext];
dir_picks(item) = dir(prop.append{item});
dir_picks(item).name = prop.append{item};
else
continue
end
end
% Remove items which no longer exist.
missing = cellfun(@isempty,full_file_picks);
full_file_picks(missing) = [];
file_picks(missing) = [];
dir_picks(missing) = [];
else
error('Append must be a cell, struct or char array.')
end
% Validate Output property.
legal_outputs = {'cell','struct','char'};
out_idx = find(strncmpi(prop.output,legal_outputs,length(prop.output)));
if length(out_idx) == 1
prop.output = legal_outputs{out_idx};
else
error(['Value of ''Output'' property, ''%s'', is illegal or '...
'ambiguous.'],prop.output)
end
% Set style preference for display of folders.
% 1 => folder icon before and filesep after
% 2 => bullet before and filesep after
% 3 => filesep after only
folder_style_pref = 1;
fsdata = set_folder_style(folder_style_pref);
% Initialize file lists.
if exist(prop.filterspec,'dir')
current_dir = prop.filterspec;
filter = '*';
else
[current_dir,f,e] = fileparts(prop.filterspec);
filter = [f,e];
end
if isempty(current_dir)
current_dir = pwd;
end
if isempty(filter)
filter = '*';
end
re_filter = prop.refilter;
full_filter = fullfile(current_dir,filter);
network_volumes = {};
[path_cell,new_network_vol] = path2cell(current_dir);
if exist(new_network_vol,'dir')
network_volumes = unique([network_volumes,{new_network_vol}]);
end
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,[1 0 0]));
filenames = {fdir.name}';
filenames = annotate_file_names(filenames,fdir,fsdata);
% Initialize some data.
show_full_path = false;
nodupes = true;
% Get history preferences and set history.
history = getpref('uipickfiles','history',...
struct('name',current_dir,'time',now));
default_history_size = 15;
history_size = getpref('uipickfiles','history_size',default_history_size);
history = update_history(history,current_dir,now,history_size);
% Get figure position preference and create figure.
gray = get(0,'DefaultUIControlBackgroundColor');
if ispref('uipickfiles','figure_position');
fig_pos = getpref('uipickfiles','figure_position');
fig = figure('Position',fig_pos,...
'Color',gray,...
'MenuBar','none',...
'WindowStyle','modal',...
'Resize','on',...
'NumberTitle','off',...
'Name',prop.prompt,...
'IntegerHandle','off',...
'CloseRequestFcn',@cancel,...
'ButtonDownFcn',@reset_figure_size,...
'KeyPressFcn',@keypressmisc,...
'Visible','off');
else
fig_pos = [0 0 740 494];
fig = figure('Position',fig_pos,...
'Color',gray,...
'MenuBar','none',...
'WindowStyle','modal',...
'Resize','on',...
'NumberTitle','off',...
'Name',prop.prompt,...
'IntegerHandle','off',...
'CloseRequestFcn',@cancel,...
'CreateFcn',{@movegui,'center'},...
'ButtonDownFcn',@reset_figure_size,...
'KeyPressFcn',@keypressmisc,...
'Visible','off');
end
% Set system-dependent items.
if ismac
set(fig,'DefaultUIControlFontName','Lucida Grande')
set(fig,'DefaultUIControlFontSize',9)
sort_ctrl_size = 8;
mod_key = 'command';
action = 'Control-click';
elseif ispc
set(fig,'DefaultUIControlFontName','Tahoma')
set(fig,'DefaultUIControlFontSize',8)
sort_ctrl_size = 7;
mod_key = 'control';
action = 'Right-click';
else
sort_ctrl_size = get(fig,'DefaultUIControlFontSize') - 1;
mod_key = 'control';
action = 'Right-click';
end
% Create uicontrols.
frame1 = uicontrol('Style','frame',...
'Position',[255 260 110 70]);
frame2 = uicontrol('Style','frame',...
'Position',[275 135 110 100]);
navlist = uicontrol('Style','listbox',...
'Position',[10 10 250 320],...
'String',filenames,...
'Value',[],...
'BackgroundColor','w',...
'Callback',@clicknav,...
'KeyPressFcn',@keypressnav,...
'Max',2);
tri_up = repmat([1 1 1 1 0 1 1 1 1;1 1 1 0 0 0 1 1 1;1 1 0 0 0 0 0 1 1;...
1 0 0 0 0 0 0 0 1],[1 1 3]);
tri_up(tri_up == 1) = NaN;
tri_down = tri_up(end:-1:1,:,:);
tri_null = NaN(4,9,3);
tri_icon = {tri_down,tri_null,tri_up};
sort_state = [1 0 0];
last_sort_state = [1 1 1];
sort_cb = zeros(1,3);
sort_cb(1) = uicontrol('Style','checkbox',...
'Position',[15 331 70 15],...
'String','Name',...
'FontSize',sort_ctrl_size,...
'Value',sort_state(1),...
'CData',tri_icon{sort_state(1)+2},...
'KeyPressFcn',@keypressmisc,...
'Callback',{@sort_type,1});
sort_cb(2) = uicontrol('Style','checkbox',...
'Position',[85 331 70 15],...
'String','Date',...
'FontSize',sort_ctrl_size,...
'Value',sort_state(2),...
'CData',tri_icon{sort_state(2)+2},...
'KeyPressFcn',@keypressmisc,...
'Callback',{@sort_type,2});
sort_cb(3) = uicontrol('Style','checkbox',...
'Position',[155 331 70 15],...
'String','Size',...
'FontSize',sort_ctrl_size,...
'Value',sort_state(3),...
'CData',tri_icon{sort_state(3)+2},...
'KeyPressFcn',@keypressmisc,...
'Callback',{@sort_type,3});
pickslist = uicontrol('Style','listbox',...
'Position',[380 10 350 320],...
'String',file_picks,...
'BackgroundColor','w',...
'Callback',@clickpicks,...
'KeyPressFcn',@keypresslist,...
'Max',2,...
'Value',[]);
openbut = uicontrol('Style','pushbutton',...
'Position',[270 300 80 20],...
'String','Open',...
'Enable','off',...
'KeyPressFcn',@keypressmisc,...
'Callback',@open);
arrow = [ ...
' 1 ';
' 10 ';
' 10 ';
'000000000000';
' 10 ';
' 10 ';
' 1 '];
cmap = NaN(128,3);
cmap(double('10'),:) = [0.5 0.5 0.5;0 0 0];
arrow_im = NaN(7,76,3);
arrow_im(:,45:56,:) = ind2rgb(double(arrow),cmap);
addbut = uicontrol('Style','pushbutton',...
'Position',[270 270 80 20],...
'String','Add ',...
'Enable','off',...
'CData',arrow_im,...
'KeyPressFcn',@keypressmisc,...
'Callback',@add);
removebut = uicontrol('Style','pushbutton',...
'Position',[290 205 80 20],...
'String','Remove',...
'Enable','off',...
'KeyPressFcn',@keypressmisc,...
'Callback',@remove);
moveupbut = uicontrol('Style','pushbutton',...
'Position',[290 175 80 20],...
'String','Move Up',...
'Enable','off',...
'KeyPressFcn',@keypressmisc,...
'Callback',@moveup);
movedownbut = uicontrol('Style','pushbutton',...
'Position',[290 145 80 20],...
'String','Move Down',...
'Enable','off',...
'KeyPressFcn',@keypressmisc,...
'Callback',@movedown);
dir_popup = uicontrol('Style','popupmenu',...
'Position',[10 350 225 20],...
'BackgroundColor','w',...
'String',path_cell,...
'Value',length(path_cell),...
'KeyPressFcn',@keypressmisc,...
'Callback',@dirpopup);
uparrow = [ ...
' 0 ';
' 000 ';
'00000 ';
' 0 ';
' 0 ';
' 0 ';
' 000000'];
cmap = NaN(128,3);
cmap(double('0'),:) = [0 0 0];
uparrow_im = ind2rgb(double(uparrow),cmap);
up_dir_but = uicontrol('Style','pushbutton',...
'Position',[240 350 20 20],...
'CData',uparrow_im,...
'KeyPressFcn',@keypressmisc,...
'Callback',@dir_up_one,...
'ToolTip','Go to parent folder');
if length(path_cell) > 1
set(up_dir_but','Enable','on')
else
set(up_dir_but','Enable','off')
end
hist_cm = uicontextmenu;
pathbox = uicontrol('Style','edit',...
'Position',[10 375 250 26],...
'BackgroundColor','w',...
'String',current_dir,...
'HorizontalAlignment','left',...
'TooltipString',[action,' to display folder history'],...
'KeyPressFcn',@keypressmisc,...
'Callback',@change_path,...
'UIContextMenu',hist_cm);
label1 = uicontrol('Style','text',...
'Position',[10 401 250 16],...
'String','Current Folder',...
'HorizontalAlignment','center',...
'TooltipString',[action,' to display folder history'],...
'UIContextMenu',hist_cm);
hist_menus = [];
make_history_cm()
label2 = uicontrol('Style','text',...
'Position',[10 440+36 80 17],...
'String','File Filter',...
'HorizontalAlignment','left');
label3 = uicontrol('Style','text',...
'Position',[100 440+36 160 17],...
'String','Reg. Exp. Filter',...
'HorizontalAlignment','left');
showallfiles = uicontrol('Style','checkbox',...
'Position',[270 420+32 110 20],...
'String','Show All Files',...
'Value',0,...
'HorizontalAlignment','left',...
'KeyPressFcn',@keypressmisc,...
'Callback',@togglefilter);
refilterdirs = uicontrol('Style','checkbox',...
'Position',[270 420+10 100 20],...
'String','RE Filter Dirs',...
'Value',prop.redirs,...
'HorizontalAlignment','left',...
'KeyPressFcn',@keypressmisc,...
'Callback',@toggle_refiltdirs);
filter_ed = uicontrol('Style','edit',...
'Position',[10 420+30 80 26],...
'BackgroundColor','w',...
'String',filter,...
'HorizontalAlignment','left',...
'KeyPressFcn',@keypressmisc,...
'Callback',@setfilspec);
refilter_ed = uicontrol('Style','edit',...
'Position',[100 420+30 160 26],...
'BackgroundColor','w',...
'String',re_filter,...
'HorizontalAlignment','left',...
'KeyPressFcn',@keypressmisc,...
'Callback',@setrefilter);
type_value = 1;
type_popup = uicontrol('Style','popupmenu',...
'Position',[10 422 250 20],...
'String','',...
'BackgroundColor','w',...
'Value',type_value,...
'KeyPressFcn',@keypressmisc,...
'Callback',@filter_type_callback,...
'Visible','off');
if ~isempty(prop.type)
set(filter_ed,'String',prop.type{type_value,1})
setfilspec()
set(type_popup,'String',prop.type(:,2),'Visible','on')
end
viewfullpath = uicontrol('Style','checkbox',...
'Position',[380 335 230 20],...
'String','Show full paths',...
'Value',show_full_path,...
'HorizontalAlignment','left',...
'KeyPressFcn',@keypressmisc,...
'Callback',@showfullpath);
remove_dupes = uicontrol('Style','checkbox',...
'Position',[380 360 280 20],...
'String','Remove duplicates (as per full path)',...
'Value',nodupes,...
'HorizontalAlignment','left',...
'KeyPressFcn',@keypressmisc,...
'Callback',@removedupes);
recall_button = uicontrol('Style','pushbutton',...
'Position',[665 335 65 20],...
'String','Recall',...
'KeyPressFcn',@keypressmisc,...
'Callback',@recall,...
'ToolTip','Add previously selected items');
label4 = uicontrol('Style','text',...
'Position',[380 405 350 20],...
'String','Selected data folders',...
'HorizontalAlignment','center');
done_button = uicontrol('Style','pushbutton',...
'Position',[280 80 80 30],...
'String','Done',...
'KeyPressFcn',@keypressmisc,...
'Callback',@done);
cancel_button = uicontrol('Style','pushbutton',...
'Position',[280 30 80 30],...
'String','Cancel',...
'KeyPressFcn',@keypressmisc,...
'Callback',@cancel);
% If necessary, add warning about number of items to be selected.
num_files_warn = uicontrol('Style','text',...
'Position',[380 385 350 16],...
'String',numstr,...
'ForegroundColor',[0.8 0 0],...
'HorizontalAlignment','center',...
'Visible','off');
if ~isempty(prop.numfiles)
set(num_files_warn,'Visible','on')
end
resize()
% Make figure visible and hide handle.
set(fig,'HandleVisibility','off',...
'Visible','on',...
'ResizeFcn',@resize)
% Wait until figure is closed.
uiwait(fig)
% Compute desired output.
switch prop.output
case 'cell'
out = full_file_picks;
case 'struct'
out = dir_picks(:);
case 'char'
out = char(full_file_picks);
case 'cancel'
out = 0;
end
% Update history preference.
setpref('uipickfiles','history',history)
if ~isempty(full_file_picks) && ~strcmp(prop.output,'cancel')
setpref('uipickfiles','full_file_picks',full_file_picks)
end
% Update figure position preference.
setpref('uipickfiles','figure_position',fig_pos)
% ----------------- Callback nested functions ----------------
function add(varargin)
values = get(navlist,'Value');
for i = 1:length(values)
dir_pick = fdir(values(i));
pick = dir_pick.name;
pick_full = fullfile(current_dir,pick);
dir_pick.name = pick_full;
if ~nodupes || ~any(strcmp(full_file_picks,pick_full))
file_picks{end + 1} = pick; %#ok<AGROW>
full_file_picks{end + 1} = pick_full; %#ok<AGROW>
dir_picks(end + 1) = dir_pick; %#ok<AGROW>
end
end
if show_full_path
set(pickslist,'String',full_file_picks,'Value',[]);
else
set(pickslist,'String',file_picks,'Value',[]);
end
set([removebut,moveupbut,movedownbut],'Enable','off');
end
function remove(varargin)
values = get(pickslist,'Value');
file_picks(values) = [];
full_file_picks(values) = [];
dir_picks(values) = [];
top = get(pickslist,'ListboxTop');
num_above_top = sum(values < top);
top = top - num_above_top;
num_picks = length(file_picks);
new_value = min(min(values) - num_above_top,num_picks);
if num_picks == 0
new_value = [];
set([removebut,moveupbut,movedownbut],'Enable','off')
end
if show_full_path
set(pickslist,'String',full_file_picks,'Value',new_value,...
'ListboxTop',top)
else
set(pickslist,'String',file_picks,'Value',new_value,...
'ListboxTop',top)
end
end
function open(varargin)
values = get(navlist,'Value');
if fdir(values).isdir
set(fig,'pointer','watch')
drawnow
% Convert 'My Documents' to 'Documents' when necessary.
if ispc && strcmp(fdir(values).name,'My Documents')
if isempty(dir(fullfile(current_dir,fdir(values).name)))
values = find(strcmp({fdir.name},'Documents'));
end
end
current_dir = fullfile(current_dir,fdir(values).name);
history = update_history(history,current_dir,now,history_size);
make_history_cm()
full_filter = fullfile(current_dir,filter);
path_cell = path2cell(current_dir);
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,sort_state));
filenames = {fdir.name}';
filenames = annotate_file_names(filenames,fdir,fsdata);
set(dir_popup,'String',path_cell,'Value',length(path_cell))
if length(path_cell) > 1
set(up_dir_but','Enable','on')
else
set(up_dir_but','Enable','off')
end
set(pathbox,'String',current_dir)
set(navlist,'ListboxTop',1,'Value',[],'String',filenames)
set(addbut,'Enable','off')
set(openbut,'Enable','off')
set(fig,'pointer','arrow')
end
end
function clicknav(varargin)
value = get(navlist,'Value');
nval = length(value);
dbl_click_fcn = @add;
switch nval
case 0
set([addbut,openbut],'Enable','off')
case 1
set(addbut,'Enable','on');
if fdir(value).isdir
set(openbut,'Enable','on')
dbl_click_fcn = @open;
else
set(openbut,'Enable','off')
end
otherwise
set(addbut,'Enable','on')
set(openbut,'Enable','off')
end
if strcmp(get(fig,'SelectionType'),'open')
dbl_click_fcn();
end
end
function keypressmisc(h,evt) %#ok<INUSL>
if strcmp(evt.Key,'escape') && isequal(evt.Modifier,cell(1,0))
% Escape key means Cancel.
cancel()
end
end
function keypressnav(h,evt) %#ok<INUSL>
if length(path_cell) > 1 && strcmp(evt.Key,'backspace') && ...
isequal(evt.Modifier,cell(1,0))
% Backspace means go to parent folder.
dir_up_one()
elseif strcmp(evt.Key,'f') && isequal(evt.Modifier,{mod_key})
% Control-F (Command-F on Mac) means select all files.
value = find(~[fdir.isdir]);
set(navlist,'Value',value)
elseif strcmp(evt.Key,'rightarrow') && ...
isequal(evt.Modifier,cell(1,0))
% Right arrow key means select the file.
add()
elseif strcmp(evt.Key,'escape') && isequal(evt.Modifier,cell(1,0))
% Escape key means Cancel.
cancel()
end
end
function keypresslist(h,evt) %#ok<INUSL>
if strcmp(evt.Key,'backspace') && isequal(evt.Modifier,cell(1,0))
% Backspace means remove item from list.
remove()
elseif strcmp(evt.Key,'escape') && isequal(evt.Modifier,cell(1,0))
% Escape key means Cancel.
cancel()
end
end
function clickpicks(varargin)
value = get(pickslist,'Value');
if isempty(value)
set([removebut,moveupbut,movedownbut],'Enable','off')
else
set(removebut,'Enable','on')
if min(value) == 1
set(moveupbut,'Enable','off')
else
set(moveupbut,'Enable','on')
end
if max(value) == length(file_picks)
set(movedownbut,'Enable','off')
else
set(movedownbut,'Enable','on')
end
end
if strcmp(get(fig,'SelectionType'),'open')
remove();
end
end
function recall(varargin)
if ispref('uipickfiles','full_file_picks')
ffp = getpref('uipickfiles','full_file_picks');
else
ffp = {};
end
for i = 1:length(ffp)
if exist(ffp{i},'dir') && ...
(~nodupes || ~any(strcmp(full_file_picks,ffp{i})))
full_file_picks{end + 1} = ffp{i}; %#ok<AGROW>
[unused,fn,ext] = fileparts(ffp{i});
file_picks{end + 1} = [fn,ext]; %#ok<AGROW>
temp = dir(fullfile(ffp{i},'..'));
if ispc || ismac
thisdir = strcmpi({temp.name},[fn,ext]);
else
thisdir = strcmp({temp.name},[fn,ext]);
end
dir_picks(end + 1) = temp(thisdir); %#ok<AGROW>
dir_picks(end).name = ffp{i};
elseif exist(ffp{i},'file') && ...
(~nodupes || ~any(strcmp(full_file_picks,ffp{i})))
full_file_picks{end + 1} = ffp{i}; %#ok<AGROW>
[unused,fn,ext] = fileparts(ffp{i});
file_picks{end + 1} = [fn,ext]; %#ok<AGROW>
dir_picks(end + 1) = dir(ffp{i}); %#ok<AGROW>
dir_picks(end).name = ffp{i};
end
end
if show_full_path
set(pickslist,'String',full_file_picks,'Value',[]);
else
set(pickslist,'String',file_picks,'Value',[]);
end
set([removebut,moveupbut,movedownbut],'Enable','off');
end
function sort_type(h,evt,cb) %#ok<INUSL>
if sort_state(cb)
sort_state(cb) = -sort_state(cb);
last_sort_state(cb) = sort_state(cb);
else
sort_state = zeros(1,3);
sort_state(cb) = last_sort_state(cb);
end
set(sort_cb,{'CData'},tri_icon(sort_state + 2)')
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,sort_state));
filenames = {fdir.name}';
filenames = annotate_file_names(filenames,fdir,fsdata);
set(dir_popup,'String',path_cell,'Value',length(path_cell))
if length(path_cell) > 1
set(up_dir_but','Enable','on')
else
set(up_dir_but','Enable','off')
end
set(pathbox,'String',current_dir)
set(navlist,'String',filenames,'Value',[])
set(addbut,'Enable','off')
set(openbut,'Enable','off')
set(fig,'pointer','arrow')
end
function dirpopup(varargin)
value = get(dir_popup,'Value');
container = path_cell{min(value + 1,length(path_cell))};
path_cell = path_cell(1:value);
set(fig,'pointer','watch')
drawnow
if ispc && value == 1
current_dir = '';
full_filter = filter;
drives = getdrives(network_volumes);
num_drives = length(drives);
temp = tempname;
mkdir(temp)
dir_temp = dir(temp);
rmdir(temp)
fdir = repmat(dir_temp(1),num_drives,1);
[fdir.name] = deal(drives{:});
else
current_dir = cell2path(path_cell);
history = update_history(history,current_dir,now,history_size);
make_history_cm()
full_filter = fullfile(current_dir,filter);
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,sort_state));
end
filenames = {fdir.name}';
selected = find(strcmp(filenames,container));
filenames = annotate_file_names(filenames,fdir,fsdata);
set(dir_popup,'String',path_cell,'Value',length(path_cell))
if length(path_cell) > 1
set(up_dir_but','Enable','on')
else
set(up_dir_but','Enable','off')
end
set(pathbox,'String',current_dir)
set(navlist,'String',filenames,'Value',selected)
set(addbut,'Enable','off')
set(fig,'pointer','arrow')
end
function dir_up_one(varargin)
value = length(path_cell) - 1;
container = path_cell{value + 1};
path_cell = path_cell(1:value);
set(fig,'pointer','watch')
drawnow
if ispc && value == 1
current_dir = '';
full_filter = filter;
drives = getdrives(network_volumes);
num_drives = length(drives);
temp = tempname;
mkdir(temp)
dir_temp = dir(temp);
rmdir(temp)
fdir = repmat(dir_temp(1),num_drives,1);
[fdir.name] = deal(drives{:});
else
current_dir = cell2path(path_cell);
history = update_history(history,current_dir,now,history_size);
make_history_cm()
full_filter = fullfile(current_dir,filter);
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,sort_state));
end
filenames = {fdir.name}';
selected = find(strcmp(filenames,container));
filenames = annotate_file_names(filenames,fdir,fsdata);
set(dir_popup,'String',path_cell,'Value',length(path_cell))
if length(path_cell) > 1
set(up_dir_but','Enable','on')
else
set(up_dir_but','Enable','off')
end
set(pathbox,'String',current_dir)
set(navlist,'String',filenames,'Value',selected)
set(addbut,'Enable','off')
set(fig,'pointer','arrow')
end
function change_path(varargin)
set(fig,'pointer','watch')
drawnow
proposed_path = get(pathbox,'String');
% Process any folders named '..'.
proposed_path_cell = path2cell(proposed_path);
ddots = strcmp(proposed_path_cell,'..');
ddots(find(ddots) - 1) = true;
proposed_path_cell(ddots) = [];
proposed_path = cell2path(proposed_path_cell);
% Check for existance of folder.
if ~exist(proposed_path,'dir')
set(fig,'pointer','arrow')
uiwait(errordlg(['Folder "',proposed_path,...
'" does not exist.'],'','modal'))
return
end
current_dir = proposed_path;
history = update_history(history,current_dir,now,history_size);
make_history_cm()
full_filter = fullfile(current_dir,filter);
[path_cell,new_network_vol] = path2cell(current_dir);
if exist(new_network_vol,'dir')
network_volumes = unique([network_volumes,{new_network_vol}]);
end
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,sort_state));
filenames = {fdir.name}';
filenames = annotate_file_names(filenames,fdir,fsdata);
set(dir_popup,'String',path_cell,'Value',length(path_cell))
if length(path_cell) > 1
set(up_dir_but','Enable','on')
else
set(up_dir_but','Enable','off')
end
set(pathbox,'String',current_dir)
set(navlist,'String',filenames,'Value',[])
set(addbut,'Enable','off')
set(openbut,'Enable','off')
set(fig,'pointer','arrow')
end
function showfullpath(varargin)
show_full_path = get(viewfullpath,'Value');
if show_full_path
set(pickslist,'String',full_file_picks)
else
set(pickslist,'String',file_picks)
end
end
function removedupes(varargin)
nodupes = get(remove_dupes,'Value');
if nodupes
num_picks = length(full_file_picks);
[unused,rev_order] = unique(full_file_picks(end:-1:1)); %#ok<SETNU>
order = sort(num_picks + 1 - rev_order);
full_file_picks = full_file_picks(order);
file_picks = file_picks(order);
dir_picks = dir_picks(order);
if show_full_path
set(pickslist,'String',full_file_picks,'Value',[])
else
set(pickslist,'String',file_picks,'Value',[])
end
set([removebut,moveupbut,movedownbut],'Enable','off')
end
end
function moveup(varargin)
value = get(pickslist,'Value');
set(removebut,'Enable','on')
n = length(file_picks);
omega = 1:n;
index = zeros(1,n);
index(value - 1) = omega(value);
index(setdiff(omega,value - 1)) = omega(setdiff(omega,value));
file_picks = file_picks(index);
full_file_picks = full_file_picks(index);
dir_picks = dir_picks(index);
value = value - 1;
if show_full_path
set(pickslist,'String',full_file_picks,'Value',value)
else
set(pickslist,'String',file_picks,'Value',value)
end
if min(value) == 1
set(moveupbut,'Enable','off')
end
set(movedownbut,'Enable','on')
end
function movedown(varargin)
value = get(pickslist,'Value');
set(removebut,'Enable','on')
n = length(file_picks);
omega = 1:n;
index = zeros(1,n);
index(value + 1) = omega(value);
index(setdiff(omega,value + 1)) = omega(setdiff(omega,value));
file_picks = file_picks(index);
full_file_picks = full_file_picks(index);
dir_picks = dir_picks(index);
value = value + 1;
if show_full_path
set(pickslist,'String',full_file_picks,'Value',value)
else
set(pickslist,'String',file_picks,'Value',value)
end
if max(value) == n
set(movedownbut,'Enable','off')
end
set(moveupbut,'Enable','on')
end
function togglefilter(varargin)
set(fig,'pointer','watch')
drawnow
value = get(showallfiles,'Value');
if value
filter = '*';
re_filter = '';
set([filter_ed,refilter_ed],'Enable','off')
else
filter = get(filter_ed,'String');
re_filter = get(refilter_ed,'String');
set([filter_ed,refilter_ed],'Enable','on')
end
full_filter = fullfile(current_dir,filter);
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,sort_state));
filenames = {fdir.name}';
filenames = annotate_file_names(filenames,fdir,fsdata);
set(navlist,'String',filenames,'Value',[])
set(addbut,'Enable','off')
set(fig,'pointer','arrow')
end
function toggle_refiltdirs(varargin)
set(fig,'pointer','watch')
drawnow
value = get(refilterdirs,'Value');
prop.redirs = value;
full_filter = fullfile(current_dir,filter);
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,sort_state));
filenames = {fdir.name}';
filenames = annotate_file_names(filenames,fdir,fsdata);
set(navlist,'String',filenames,'Value',[])
set(addbut,'Enable','off')
set(fig,'pointer','arrow')
end
function setfilspec(varargin)
set(fig,'pointer','watch')
drawnow
filter = get(filter_ed,'String');
if isempty(filter)
filter = '*';
set(filter_ed,'String',filter)
end
% Process file spec if a subdirectory was included.
[p,f,e] = fileparts(filter);
if ~isempty(p)
newpath = fullfile(current_dir,p,'');
set(pathbox,'String',newpath)
filter = [f,e];
if isempty(filter)
filter = '*';
end
set(filter_ed,'String',filter)
change_path();
end
full_filter = fullfile(current_dir,filter);
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,sort_state));
filenames = {fdir.name}';
filenames = annotate_file_names(filenames,fdir,fsdata);
set(navlist,'String',filenames,'Value',[])
set(addbut,'Enable','off')
set(fig,'pointer','arrow')
end
function setrefilter(varargin)
set(fig,'pointer','watch')
drawnow
re_filter = get(refilter_ed,'String');
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,sort_state));
filenames = {fdir.name}';
filenames = annotate_file_names(filenames,fdir,fsdata);
set(navlist,'String',filenames,'Value',[])
set(addbut,'Enable','off')
set(fig,'pointer','arrow')
end
function filter_type_callback(varargin)
type_value = get(type_popup,'Value');
set(filter_ed,'String',prop.type{type_value,1})
setfilspec()
end
function done(varargin)
% Optional shortcut: click on a file and press 'Done'.
% if isempty(full_file_picks) && strcmp(get(addbut,'Enable'),'on')
% add();
% end
numfiles = length(full_file_picks);
if ~isempty(prop.numfiles)
if numfiles < prop.numfiles(1)
msg = {'Too few items selected.',numstr};
uiwait(errordlg(msg,'','modal'))
return
elseif numfiles > prop.numfiles(end)
msg = {'Too many items selected.',numstr};
uiwait(errordlg(msg,'','modal'))
return
end
end
fig_pos = get(fig,'Position');
delete(fig)
end
function cancel(varargin)
prop.output = 'cancel';
fig_pos = get(fig,'Position');
delete(fig)
end
function history_cb(varargin)
set(fig,'pointer','watch')
drawnow
current_dir = history(varargin{3}).name;
history = update_history(history,current_dir,now,history_size);
make_history_cm()
full_filter = fullfile(current_dir,filter);
path_cell = path2cell(current_dir);
fdir = filtered_dir(full_filter,re_filter,prop.redirs,...
@(x)file_sort(x,sort_state));
filenames = {fdir.name}';
filenames = annotate_file_names(filenames,fdir,fsdata);
set(dir_popup,'String',path_cell,'Value',length(path_cell))
if length(path_cell) > 1
set(up_dir_but','Enable','on')
else
set(up_dir_but','Enable','off')
end
set(pathbox,'String',current_dir)
set(navlist,'ListboxTop',1,'Value',[],'String',filenames)
set(addbut,'Enable','off')
set(openbut,'Enable','off')
set(fig,'pointer','arrow')
end
function clear_history(varargin)
history = update_history(history(1),'',[],history_size);
make_history_cm()
end
function set_history_size(varargin)
result_cell = inputdlg('Number of Recent Folders:','',1,...
{sprintf('%g',history_size)});
if isempty(result_cell)
return
end
result = sscanf(result_cell{1},'%f');
if isempty(result) || result < 1
return
end
history_size = result;
history = update_history(history,'',[],history_size);
make_history_cm()
setpref('uipickfiles','history_size',history_size)
end
function resize(varargin)
% Get current figure size.
P = 'Position';
pos = get(fig,P);
w = pos(3); % figure width in pixels
h = pos(4); % figure height in pixels
% Enforce minimum figure size.
w = max(w,564);
h = max(h,443);
if any(pos(3:4) < [w h])
pos(3:4) = [w h];
set(fig,P,pos)
end
% Change positions of all uicontrols based on the current figure
% width and height.
navw_pckw = round([1 1;-350 250]\[w-140;0]);
navw = navw_pckw(1);
pckw = navw_pckw(2);
navp = [10 10 navw h-174];
pckp = [w-10-pckw 10 pckw h-174];
set(navlist,P,navp)
set(pickslist,P,pckp)
set(frame1,P,[navw+5 h-234 110 70])
set(openbut,P,[navw+20 h-194 80 20])
set(addbut,P,[navw+20 h-224 80 20])
frame2y = round((h-234 + 110 - 100)/2);
set(frame2,P,[w-pckw-115 frame2y 110 100])
set(removebut,P,[w-pckw-100 frame2y+70 80 20])
set(moveupbut,P,[w-pckw-100 frame2y+40 80 20])
set(movedownbut,P,[w-pckw-100 frame2y+10 80 20])
set(done_button,P,[navw+30 80 80 30])
set(cancel_button,P,[navw+30 30 80 30])
set(sort_cb(1),P,[15 h-163 70 15])
set(sort_cb(2),P,[85 h-163 70 15])
set(sort_cb(3),P,[155 h-163 70 15])
set(dir_popup,P,[10 h-144 navw-25 20])
set(up_dir_but,P,[navw-10 h-144 20 20])
set(pathbox,P,[10 h-119 navw 26])
set(label1,P,[10 h-93 navw 16])
set(viewfullpath,P,[pckp(1) h-159 230 20])
set(remove_dupes,P,[pckp(1) h-134 280 20])
set(recall_button,P,[w-75 h-159 65 20])
set(label4,P,[w-10-pckw h-89 pckw 20])
set(num_files_warn,P,[w-10-pckw h-109 pckw 16])
set(label2,P,[10 h-18 80 17])
set(label3,P,[100 h-18 160 17])
set(showallfiles,P,[270 h-42 110 20])
set(refilterdirs,P,[270 h-64 100 20])
set(filter_ed,P,[10 h-44 80 26])
set(refilter_ed,P,[100 h-44 160 26])
set(type_popup,P,[10 h-72 250 20])
end
function reset_figure_size(varargin)
if strcmp(get(fig,'SelectionType'),'open')
root_units = get(0,'units');
screen_size = get(0,'ScreenSize');
set(0,'Units',root_units)
hw = [740 494];
pos = [round((screen_size(3:4) - hw - [0 26])/2),hw];
set(fig,'Position',pos)
resize()
end
end
% ------------------ Other nested functions ------------------
function make_history_cm
% Make context menu for history.
if ~isempty(hist_menus)
delete(hist_menus)
end
num_hist = length(history);
hist_menus = zeros(1,num_hist+2);
for i = 1:num_hist
hist_menus(i) = uimenu(hist_cm,'Label',history(i).name,...
'Callback',{@history_cb,i});
end
hist_menus(num_hist+1) = uimenu(hist_cm,...
'Label','Clear Menu',...
'Separator','on',...
'Callback',@clear_history);
hist_menus(num_hist+2) = uimenu(hist_cm,'Label',...
sprintf('Set Number of Recent Folders (%d) ...',history_size),...
'Callback',@set_history_size);
end
end
% -------------------- Subfunctions --------------------
function [c,network_vol] = path2cell(p)
% Turns a path string into a cell array of path elements.
if ispc
p = strrep(p,'/','\');
c1 = regexp(p,'(^\\\\[^\\]+\\[^\\]+)|(^[A-Za-z]+:)|[^\\]+','match');
vol = c1{1};
c = [{'My Computer'};c1(:)];
if strncmp(vol,'\\',2)
network_vol = vol;
else
network_vol = '';
end
else
c = textscan(p,'%s','delimiter','/');
c = [{filesep};c{1}(2:end)];
network_vol = '';
end
end
% --------------------
function p = cell2path(c)
% Turns a cell array of path elements into a path string.
if ispc
p = fullfile(c{2:end},'');
else
p = fullfile(c{:},'');
end
end
% --------------------
function d = filtered_dir(full_filter,re_filter,filter_both,sort_fcn)
% Like dir, but applies filters and sorting.
p = fileparts(full_filter);
if isempty(p) && full_filter(1) == '/'
p = '/';
end
if exist(full_filter,'dir')
dfiles = dir(' ');
else
dfiles = dir(full_filter);
end
if ~isempty(dfiles)
dfiles([dfiles.isdir]) = [];
end
ddir = dir(p);
ddir = ddir([ddir.isdir]);
[unused,index0] = sort(lower({ddir.name})); %#ok<ASGLU>
ddir = ddir(index0);
ddir(strcmp({ddir.name},'.') | strcmp({ddir.name},'..')) = [];
% Additional regular expression filter.
if nargin > 1 && ~isempty(re_filter)
if ispc || ismac
no_match = cellfun('isempty',regexpi({dfiles.name},re_filter));
else
no_match = cellfun('isempty',regexp({dfiles.name},re_filter));
end
dfiles(no_match) = [];
end
if filter_both
if nargin > 1 && ~isempty(re_filter)
if ispc || ismac
no_match = cellfun('isempty',regexpi({ddir.name},re_filter));
else
no_match = cellfun('isempty',regexp({ddir.name},re_filter));
end
ddir(no_match) = [];
end
end
% Set navigator style:
% 1 => list all folders before all files, case-insensitive sorting
% 2 => mix files and folders, case-insensitive sorting
% 3 => list all folders before all files, case-sensitive sorting
nav_style = 1;
switch nav_style
case 1
[unused,index1] = sort_fcn(dfiles); %#ok<ASGLU>
[unused,index2] = sort_fcn(ddir); %#ok<ASGLU>
d = [ddir(index2);dfiles(index1)];
case 2
d = [dfiles;ddir];
[unused,index] = sort(lower({d.name})); %#ok<ASGLU>
d = d(index);
case 3
[unused,index1] = sort({dfiles.name}); %#ok<ASGLU>
[unused,index2] = sort({ddir.name}); %#ok<ASGLU>
d = [ddir(index2);dfiles(index1)];
end
end
% --------------------
function [files_sorted,index] = file_sort(files,sort_state)
switch find(sort_state)
case 1
[files_sorted,index] = sort(lower({files.name}));
if sort_state(1) < 0
files_sorted = files_sorted(end:-1:1);
index = index(end:-1:1);
end
case 2
if sort_state(2) > 0
[files_sorted,index] = sort([files.datenum]);
else
[files_sorted,index] = sort([files.datenum],'descend');
end
case 3
if sort_state(3) > 0
[files_sorted,index] = sort([files.bytes]);
else
[files_sorted,index] = sort([files.bytes],'descend');
end
end
end
% --------------------
function drives = getdrives(other_drives)
% Returns a cell array of drive names on Windows.
letters = char('A':'Z');
num_letters = length(letters);
drives = cell(1,num_letters);
for i = 1:num_letters
if exist([letters(i),':\'],'dir');
drives{i} = [letters(i),':'];
end
end
drives(cellfun('isempty',drives)) = [];
if nargin > 0 && iscellstr(other_drives)
drives = [drives,unique(other_drives)];
end
end
% --------------------
function filenames = annotate_file_names(filenames,dir_listing,fsdata)
% Adds a trailing filesep character to folder names and, optionally,
% prepends a folder icon or bullet symbol.
for i = 1:length(filenames)
if dir_listing(i).isdir
filenames{i} = sprintf('%s%s%s%s',fsdata.pre,filenames{i},...
fsdata.filesep,fsdata.post);
end
end
end
% --------------------
function history = update_history(history,current_dir,time,history_size)
if ~isempty(current_dir)
% Insert or move current_dir to the top of the history.
% If current_dir already appears in the history list, delete it.
match = strcmp({history.name},current_dir);
history(match) = [];
% Prepend history with (current_dir,time).
history = [struct('name',current_dir,'time',time),history];
end
% Trim history to keep at most <history_size> newest entries.
history = history(1:min(history_size,end));
end
% --------------------
function success = generate_folder_icon(icon_path)
% Black = 1, manila color = 2, transparent = 3.
im = [ ...
3 3 3 1 1 1 1 3 3 3 3 3;
3 3 1 2 2 2 2 1 3 3 3 3;
3 1 1 1 1 1 1 1 1 1 1 3;
1 2 2 2 2 2 2 2 2 2 2 1;
1 2 2 2 2 2 2 2 2 2 2 1;
1 2 2 2 2 2 2 2 2 2 2 1;
1 2 2 2 2 2 2 2 2 2 2 1;
1 2 2 2 2 2 2 2 2 2 2 1;
1 2 2 2 2 2 2 2 2 2 2 1;
1 1 1 1 1 1 1 1 1 1 1 1];
cmap = [0 0 0;255 220 130;255 255 255]/255;
fid = fopen(icon_path,'w');
if fid > 0
fclose(fid);
imwrite(im,cmap,icon_path,'Transparency',[1 1 0])
end
success = exist(icon_path,'file');
end
% --------------------
function fsdata = set_folder_style(folder_style_pref)
% Set style to preference.
fsdata.style = folder_style_pref;
% If style = 1, check to make sure icon image file exists. If it doesn't,
% try to create it. If that fails set style = 2.
if fsdata.style == 1
icon_path = fullfile(prefdir,'uipickfiles_folder_icon.png');
if ~exist(icon_path,'file')
success = generate_folder_icon(icon_path);
if ~success
fsdata.style = 2;
end
end
end
% Set pre and post fields.
if fsdata.style == 1
icon_url = ['file://localhost/',...
strrep(strrep(icon_path,':','|'),'\','/')];
fsdata.pre = sprintf('<html><img src="%s"> ',icon_url);
fsdata.post = '</html>';
elseif fsdata.style == 2
fsdata.pre = '<html><b>•</b> ';
fsdata.post = '</html>';
elseif fsdata.style == 3
fsdata.pre = '';
fsdata.post = '';
end
fsdata.filesep = filesep;
end
% --------------------
function prop = parsepropval(prop,varargin)
% Parse property/value pairs and return a structure.
properties = fieldnames(prop);
arg_index = 1;
while arg_index <= length(varargin)
arg = varargin{arg_index};
if ischar(arg)
prop_index = match_property(arg,properties);
prop.(properties{prop_index}) = varargin{arg_index + 1};
arg_index = arg_index + 2;
elseif isstruct(arg)
arg_fn = fieldnames(arg);
for i = 1:length(arg_fn)
prop_index = match_property(arg_fn{i},properties);
prop.(properties{prop_index}) = arg.(arg_fn{i});
end
arg_index = arg_index + 1;
else
error(['Properties must be specified by property/value pairs',...
' or structures.'])
end
end
end
% --------------------
function prop_index = match_property(arg,properties)
% Utility function for parsepropval.
prop_index = find(strcmpi(arg,properties));
if isempty(prop_index)
prop_index = find(strncmpi(arg,properties,length(arg)));
end
if length(prop_index) ~= 1
error('Property ''%s'' does not exist or is ambiguous.',arg)
end
end
|
github
|
BII-wushuang/FLLIT-master
|
Tracking_Base.m
|
.m
|
FLLIT-master/src/Tracking_Base.m
| 8,496 |
utf_8
|
72f608bee2e36e1c5b5872785e7da70c
|
% A very simple tracker based on the hungarian linker method
% Outputs tip positions and identities of individual legs
function Tracking_Base (data_dir)
nLegs = 6; %preassume there are 6 legs
%% Section 1: locate image folder and create output folder
if (nargin < 1)
data_dir = uigetdir('./Data');
end
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
seg_dir = ['./Results/SegmentedImages' sub_dir '/'];
data_dir = ['./Data' sub_dir '/'];
img_list = load_img_list(data_dir);
output_dir = ['./Results/Tracking' sub_dir '/'];
if(~exist(output_dir))
mkdir(output_dir);
end
%% End of section 1
%% Section 2:
se = strel('disk',4);
% maximal movement of legs in between frames
max_distance = 20;
trajectory = [];
norm_trajectory = [];
CoM = [];
end_frame = length(dir([seg_dir '*.png']))/2;
for i = 1: end_frame
clear connComp;
% Load necessary images
Im = (imread([seg_dir 'img_' num2str(i) '.png']));
Imroi = imread([seg_dir 'roi_' num2str(i) '.png']);
% Fix image/segmentation irregularities
Imwork = double(Im(:,:,1) == 255) .* Imroi;
connComp = bwconncomp(Imwork);
if (connComp.NumObjects == 6 && min(cellfun(@length,connComp.PixelIdxList)) > 35)
Imroi = imerode(Imroi,se);
[locY,locX] = find(Imroi > 0);
[centre_of_mass,theta] = findCoM(locX,locY);
locX = locX - centre_of_mass(1);
locY = locY - centre_of_mass(2);
points = [cosd(theta) sind(theta); -sind(theta) cosd(theta)]* [locX'; locY'];
%Attempt to ensure that the head is in the positive
%y-direction by comparing which side has more number of
%pixel points
if (length(find(points(2,:) > 0))< length(find(points(2,:) < 0)))
theta = mod(theta + 180,360);
end
for cc = 1:nLegs
legpixels = connComp.PixelIdxList{cc};
imleg = zeros(size(Imwork));
imleg(legpixels) = 1;
[skr,~] = skeleton(imleg);
skr_start = 3;
[~,exy,~] = anaskel(bwmorph(skr > skr_start,'skel',Inf));
% while (length(exy)>2)
% skr_start = skr_start+1;
% [~,exy,~] = anaskel(bwmorph(skr > skr_start,'skel',Inf));
% end
imgX = exy(1,:) - centre_of_mass(1);
imgY = exy(2,:) - centre_of_mass(2);
normpoints = [cosd(theta) sind(theta); -sind(theta) cosd(theta)]* [imgX; imgY];
[~,tipidx]=max(min(pdist2(points',normpoints','euclidean')));
for j = 1:2
raw_normtips(cc,j) = normpoints(j,tipidx);
raw_tips(cc,j) = exy(j,tipidx);
end
end
leftlegs_idx = find(raw_normtips(:,1)<0);
if(length(leftlegs_idx)~=3)
continue;
end
rightlegs_idx = find(raw_normtips(:,1)>=0);
[~,left_sort] = sort(raw_normtips(leftlegs_idx,2));
leg_counter = 0;
for kk = 1 :3
trajectory(i, kk, :) = raw_tips(leftlegs_idx(left_sort(kk-leg_counter)),:);
norm_trajectory(i, kk, :) = raw_normtips(leftlegs_idx(left_sort(kk-leg_counter)),:);
end
leg_counter = 0;
[~,right_sort] = sort(raw_normtips(rightlegs_idx,2));
for kk = 1 :3
trajectory(i, kk+3, :) = raw_tips(rightlegs_idx(right_sort(kk-leg_counter)),:);
norm_trajectory(i, kk+3, :) = raw_normtips(rightlegs_idx(right_sort(kk-leg_counter)),:);
end
CoM(i, :) = [centre_of_mass, theta];
start_frame = i;
fprintf('Tracking automatically initiated on frame %d for dataset %s\n', i, sub_dir);
for k = i-1 : -1 : 1
Im = (imread([seg_dir 'img_' num2str(k) '.png']));
Imroi = imread([seg_dir 'roi_' num2str(k) '.png']);
% Fix image/segmentation irregularities
Imwork = double(Im(:,:,1) == 255) .* Imroi;
Imwork = Imwork - (bwdist(imerode(Imroi,se))<10);
[locY,locX] = find(imerode(Imroi,se) > 0);
%Centre_of_Mass
[centre_of_mass,theta] = findCoM(locX,locY);
if (abs(theta - CoM(k+1,3)) > 90 && abs(theta - CoM(k+1,3)) < 270)
theta = mod(theta + 180,360);
end
CoM(k, :) = [centre_of_mass, theta];
[raw_tips, raw_normtips] = findtips(Imwork, Imroi, locX, locY, centre_of_mass, theta);
x_t1 = raw_normtips;
x_t0 = reshape(norm_trajectory(k+1,:),[nLegs 2]);
target_indices = hungarianlinker(x_t0, x_t1, max_distance);
for kk = 1:length(target_indices)
if (target_indices(kk) > 0)
norm_trajectory(k, kk, :) = raw_normtips(target_indices(kk),:);
trajectory(k, kk, :) = raw_tips(target_indices(kk),:);
else
norm_trajectory(k, kk, :) = 0;
trajectory(k, kk, :) = 0;
end
end
leftoveridx = find(hungarianlinker(raw_normtips, x_t0, max_distance)==-1);
x_t1 = raw_normtips(leftoveridx,:);
x_t2 = raw_tips(leftoveridx,:);
last_seen_tips = reshape(norm_trajectory(k,:),[nLegs 2]);
unassigned_idx = find(last_seen_tips(:,1) == 0);
for kk = 1:length(unassigned_idx)
idx = find(norm_trajectory(1:i,unassigned_idx(kk),1),1,'last');
last_seen_tips(unassigned_idx(kk),:) = reshape(norm_trajectory(idx,unassigned_idx(kk),:), [1 2]);
end
if (~isempty(unassigned_idx) && ~isempty(x_t1))
C = hungarianlinker(last_seen_tips(unassigned_idx,:), x_t1, 1.25*max_distance);
for l = 1:length(C)
if (C(l) ~= -1)
norm_trajectory(k,unassigned_idx(l), :) = x_t1(C(l), :);
trajectory(k,unassigned_idx(l), :) = x_t2(C(l), :);
end
end
end
end
break
else
continue;
end
end
skip = 1;
for i = start_frame+1 : skip : end_frame
if (mod(i,50) == 1)
fprintf('Tracking progress: frame %d for dataset %s\n', i, sub_dir);
end
% Load necessary images
Im = (imread([seg_dir 'img_' num2str(i) '.png']));
Imroi = imread([seg_dir 'roi_' num2str(i) '.png']);
% Fix image/segmentation irregularities
Imwork = double(Im(:,:,1) == 255) .* Imroi;
Imwork = Imwork - (bwdist(imerode(Imroi,se))<10);
[locY,locX] = find(imerode(Imroi,se) > 0);
%Centre_of_Mass
[centre_of_mass,theta] = findCoM(locX,locY);
if (abs(theta - CoM(i-1,3)) > 90 && abs(theta - CoM(i-1,3)) < 270)
theta = mod(theta + 180,360);
end
CoM(i, :) = [centre_of_mass, theta];
[raw_tips, raw_normtips] = findtips(Imwork, Imroi, locX, locY, centre_of_mass, theta);
x_t1 = raw_normtips;
x_t0 = reshape(norm_trajectory(i-1,:),[nLegs 2]);
target_indices = hungarianlinker(x_t0, x_t1, max_distance);
for kk = 1:length(target_indices)
if (target_indices(kk) > 0)
norm_trajectory(i, kk, :) = raw_normtips(target_indices(kk),:);
trajectory(i, kk, :) = raw_tips(target_indices(kk),:);
end
end
leftoveridx = find(hungarianlinker(raw_normtips, x_t0, max_distance)==-1);
x_t1 = raw_normtips(leftoveridx,:);
x_t2 = raw_tips(leftoveridx,:);
last_seen_tips = reshape(norm_trajectory(i,:),[6 2]);
unassigned_idx = find(last_seen_tips(:,1) == 0);
for kk = 1:length(unassigned_idx)
idx = find(norm_trajectory(:,unassigned_idx(kk),1),1,'last');
last_seen_tips(unassigned_idx(kk),:) = reshape(norm_trajectory(idx,unassigned_idx(kk),:), [1 2]);
end
if (~isempty(unassigned_idx) && ~isempty(x_t1))
C = hungarianlinker(last_seen_tips(unassigned_idx,:), x_t1, max_distance);
for l = 1:length(C)
if (C(l) ~= -1)
norm_trajectory(i,unassigned_idx(l), :) = x_t1(C(l), :);
trajectory(i,unassigned_idx(l), :) = x_t2(C(l), :);
end
end
end
end
save([output_dir 'CoM.mat'],'CoM');
save([output_dir 'trajectory.mat'],'trajectory');
save([output_dir 'norm_trajectory.mat'],'norm_trajectory');
csvwrite([output_dir 'CoM.csv'],CoM);
csvwrite([output_dir 'trajectory.csv'],trajectory);
csvwrite([output_dir 'norm_trajectory.csv'],norm_trajectory);
end
|
github
|
BII-wushuang/FLLIT-master
|
findmissing.m
|
.m
|
FLLIT-master/src/findmissing.m
| 1,352 |
utf_8
|
cd60672044a321bbf585c163a0b5d667
|
function findmissing()
data_dir = uipickfiles('FilterSpec',[pwd '/Results/Tracking']);
fileID = fopen('missing_tips.csv','w');
fprintf(fileID,'%s \t %s \t %s \t %s \t %s \t %s \t %s \t %s', 'Dataset', '#frames', 'L1', 'L2', 'L3', 'L4', 'L5', 'L6');
fprintf(fileID,'\n');
fclose(fileID);
for i = 1 : length(data_dir)
ProcessFolder(data_dir{i});
end
end
function ProcessFolder(data_dir)
pos_bs = strfind(data_dir,'Tracking');
sub_dir = data_dir(pos_bs(end)+length('Tracking'):length(data_dir));
if(exist(data_dir) && isempty(dir([data_dir '/trajectory.mat'])) )
dir_fn = dir(data_dir);
for i_dir = 1:length(dir_fn)-2
ProcessFolder([data_dir '/' dir_fn(i_dir+2).name]);
pause(1);
end
else
data_dir = ['./Results/Tracking' sub_dir];
data_name_pos = strfind(data_dir,'/');
data_name = data_dir(data_name_pos(end)+1:end);
load([data_dir '/trajectory.mat']);
output{1} = data_name;
output{2} = length(trajectory);
for j =1:6
output{j+2} = length(find(trajectory(:,j,1)==0));
end
fileID = fopen('missing_tips.csv','a');
formatSpec = '%s \t %d \t %d \t %d \t %d \t %d \t %d \t %d \t %d';
fprintf(fileID,formatSpec,output{:});
fprintf(fileID,'\n');
fclose(fileID);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
Video_base.m
|
.m
|
FLLIT-master/src/Video_base.m
| 6,558 |
utf_8
|
bc69c4af23e5170754e8fcda84c9abc9
|
%Plot the trajectory of the fly's legs
function Video(data_dir,fps,skip,startframe,endframe,bodylength)
pos_bs = strfind(data_dir,'Data');
sub_dir = data_dir(pos_bs(end)+length('Data'):length(data_dir));
data_dir = [pwd '/Data' sub_dir '/'];
if(~isempty(dir([data_dir '*.tif'])))
img_list = dir([data_dir '*.tif']);
else
img_list = dir([data_dir '*.bmp']);
end
load(['./Results/Tracking/' sub_dir '/trajectory.mat']);
load(['./Results/Tracking/' sub_dir '/norm_trajectory.mat']);
load(['./Results/Tracking/' sub_dir '/CoM.mat']);
nlegs = size(trajectory,2);
if (nlegs == 6)
legs_id = {'L1', 'L2', 'L3', 'R1', 'R2', 'R3'};
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1];
else
legs_id = {'L1', 'L2', 'L3', 'L4', 'R1', 'R2', 'R3', 'R4'};
trajectory = trajectory(:,[1 2 3 7 4 5 6 8],:);
norm_trajectory = norm_trajectory(:,[1 2 3 7 4 5 6 8],:);
colors = [1 0 0; 0 1 0; 0 0 1; 1 1 0; 0 1 1; 1 0 1; 1 0.5 0; 1 0 0.5];
end
start = zeros(nlegs,1);
for j = 1:nlegs;
start(j) = find(trajectory(:,j,1),1);
end
startf = max(start);
endf = length(CoM);
for j =1:size(trajectory,2)
nonzero = find(norm_trajectory(:,j,1));
for i = startf : endf
if (trajectory(i,j,1) ~= 0)
x(i,j) = trajectory(i,j,1);
y(i,j) = trajectory(i,j,2);
nx(i,j) = norm_trajectory(i,j,1);
ny(i,j) = norm_trajectory(i,j,2);
else
previdx = nonzero(find(nonzero<i, 1));
nextidx = nonzero(find(nonzero>i, 1));
if(isempty(previdx))
x(i,j) = trajectory(nextidx,j,1);
y(i,j) = trajectory(nextidx,j,2);
nx(i,j) = norm_trajectory(nextidx,j,1);
ny(i,j) = norm_trajectory(nextidx,j,2);
elseif (~isempty(nextidx))
x(i,j) = trajectory(previdx,j,1) + (i-previdx)/(nextidx-previdx) * (trajectory(nextidx,j,1) - trajectory(previdx,j,1));
y(i,j) = trajectory(previdx,j,2) + (i-previdx)/(nextidx-previdx) * (trajectory(nextidx,j,2) - trajectory(previdx,j,2));
nx(i,j) = norm_trajectory(previdx,j,1) + (i-previdx)/(nextidx-previdx) * (norm_trajectory(nextidx,j,1) - norm_trajectory(previdx,j,1));
ny(i,j) = norm_trajectory(previdx,j,2) + (i-previdx)/(nextidx-previdx) * (norm_trajectory(nextidx,j,2) - norm_trajectory(previdx,j,2));
else
x(i,j) = x(i-1,j);
y(i,j) = y(i-1,j);
nx(i,j) = nx(i-1,j);
ny(i,j) = ny(i-1,j);
end
end
end
end
for i = startf : endf
if (i == startf)
dist(i) = 0;
else
dist(i) = dist(i-1) + (CoM(i,1) - CoM(i-1,1))*sind(CoM(i-1,3)) + (CoM(i,2) - CoM(i-1,2))*-cosd(CoM(i-1,3));
end
end
if(isempty(strfind(sub_dir, '/')))
pos_bs = strfind(sub_dir, '\');
else
pos_bs = strfind(sub_dir, '/');
end
Vtitle = sub_dir(pos_bs(end)+1:end);
fig = figure('doublebuffer','off','Visible','off');
set(fig,'Units','pixels','Position',[1 1 1920 1080]);
set(0,'CurrentFigure',fig);
f = waitbar(0,'0.00%','Name','Processing Video...',...
'CreateCancelBtn','setappdata(gcbf,''canceling'',1)');
setappdata(f,'canceling',0);
counter = 0;
ori_dir = pwd;
cd(['./Results/Tracking' sub_dir]);
mkdir('video_tmp');
for i = startframe : skip : endframe
% Check for clicked Cancel button
if getappdata(f,'canceling')
break
end
counter = counter+1;
if mod(i,50) == 0
fprintf('Processing frame %d\n',i);
end
waitbar(i/endframe,f,sprintf('%2.2f%%', i/endframe*100))
t = startframe : skip : i;
nt = t;
set(0,'CurrentFigure',fig);
img = imread([data_dir img_list(i).name]);
hold on
subplot(4,4,[2:3 6:7])
imshow(img);
axis square
hold off
img_norm = imtranslate(img, [255 - CoM(i,1), 255 - CoM(i,2)]);
img_norm = imrotate(img_norm, CoM(i,3));
img_norm = imcrop(img_norm, [size(img_norm,1)/2-150 size(img_norm,2)/2-150 300 300]);
hold on
subplot(4,4,[10:11 14:15])
imshow(img_norm);
axis square
hold off
hold on
% Superposed trajectory with fly
subplot(4,4,[2:3 6:7])
for j = 1: size(trajectory,2)
p(j) = plot (x(t,j), y(t,j));
end
scatter(CoM(i,1)+sind(CoM(i,3))*.157*bodylength,CoM(i,2)-cosd(CoM(i,3))*.157*bodylength,'w*');
title(Vtitle,'Interpreter', 'none');
axis([0 512 0 512]);
axis square
set(gca,'Ydir','reverse')
hold on
% Superposed trajectory with fly in normalised plane
subplot(4,4,[10:11 14:15])
scatter(150,150-0.157*bodylength,'w*');
for j = 1: size(trajectory,2)
np(j) = plot (150+nx(t,j), 150+ny(t,j));
end
title('Leg motion in normalised plane');
axis square
% CoM trajectory in x-y plane
subplot(4,4,[1 5])
plot (CoM(t,1), 512-CoM(t,2));
title('CoM trajectory in x-y plane');
axis([0 512 0 512]);
axis square
% Forward displacement of fly
subplot(4,4,[4 8])
plot(nt, dist(t));
title('Forward displacement (direction it is heading)');
xlabel('time (ms)');
ylabel('displacement (pixels)');
axis square
% Vertical displacement of legs
subplot(4,4,[9 13])
npy = plot (nt, -ny(t,1:size(trajectory,2)));
title('Vertical displacement of legs');
xlabel('time (ms)');
ylabel('displacement (pixels)');
axis square
set(gca,'Color',[0.5 0.5 0.5]);
% Lateral displacement of legs
subplot(4,4,[12 16])
npx = plot (nt, nx(t,1: size(trajectory,2)));
title('Lateral displacement of legs');
xlabel('time (ms)');
ylabel('displacement (pixels)');
axis square
set(gca,'Color',[0.5 0.5 0.5]);
hold off
for j = 1 : size(trajectory,2)
p(j).Color = [colors(j,1) colors(j,2) colors(j,3)];
p(j).LineStyle = '--';
np(j).Color = [colors(j,1) colors(j,2) colors(j,3)];
np(j).LineStyle = '--';
npx(j).Color = [colors(j,1) colors(j,2) colors(j,3)];
npy(j).Color = [colors(j,1) colors(j,2) colors(j,3)];
end
% drawnow
img = getframe(fig);
imwrite(img.cdata, sprintf('video_tmp/%04d.png',counter));
end
[status,cmdout] = system(['ffmpeg -i video_tmp/%04d.png -r ' num2str(fps) ' -y Video.mp4']);
if (status~=0)
fid = fopen('VideoErrMsg.txt','w');
fprintf(fid,'%s\n',cmdout);
fclose(fid);
else
rmdir('video_tmp', 's');
end
cd(ori_dir);
delete(f)
% myVideo = VideoWriter(['./Results/Tracking' sub_dir '/Video.mp4'], 'MPEG-4');
|
github
|
BII-wushuang/FLLIT-master
|
munkres.m
|
.m
|
FLLIT-master/src/munkres.m
| 8,302 |
utf_8
|
05adcef4b6504b76b07ca6f59e869d20
|
function [assignment,cost] = munkres(costMat)
% MUNKRES Munkres (Hungarian) Algorithm for Linear Assignment Problem.
%
% [ASSIGN,COST] = munkres(COSTMAT) returns the optimal column indices,
% ASSIGN assigned to each row and the minimum COST based on the assignment
% problem represented by the COSTMAT, where the (i,j)th element represents the cost to assign the jth
% job to the ith worker.
%
% Partial assignment: This code can identify a partial assignment is a full
% assignment is not feasible. For a partial assignment, there are some
% zero elements in the returning assignment vector, which indicate
% un-assigned tasks. The cost returned only contains the cost of partially
% assigned tasks.
% This is vectorized implementation of the algorithm. It is the fastest
% among all Matlab implementations of the algorithm.
% Examples
% Example 1: a 5 x 5 example
%{
[assignment,cost] = munkres(magic(5));
disp(assignment); % 3 2 1 5 4
disp(cost); %15
%}
% Example 2: 400 x 400 random data
%{
n=400;
A=rand(n);
tic
[a,b]=munkres(A);
toc % about 2 seconds
%}
% Example 3: rectangular assignment with inf costs
%{
A=rand(10,7);
A(A>0.7)=Inf;
[a,b]=munkres(A);
%}
% Example 4: an example of partial assignment
%{
A = [1 3 Inf; Inf Inf 5; Inf Inf 0.5];
[a,b]=munkres(A)
%}
% a = [1 0 3]
% b = 1.5
% Reference:
% "Munkres' Assignment Algorithm, Modified for Rectangular Matrices",
% http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html
% version 2.3 by Yi Cao at Cranfield University on 11th September 2011
% Copyright (c) 2009, Yi Cao
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% * Redistributions of source code must retain the above copyright notice, this
% list of conditions and the following disclaimer.
%
% * Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
% FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
% SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
% OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
assignment = zeros(1,size(costMat,1));
cost = 0;
validMat = costMat == costMat & costMat < Inf;
bigM = 10^(ceil(log10(sum(costMat(validMat))))+1);
costMat(~validMat) = bigM;
% costMat(costMat~=costMat)=Inf;
% validMat = costMat<Inf;
validCol = any(validMat,1);
validRow = any(validMat,2);
nRows = sum(validRow);
nCols = sum(validCol);
n = max(nRows,nCols);
if ~n
return
end
maxv=10*max(costMat(validMat));
dMat = zeros(n) + maxv;
dMat(1:nRows,1:nCols) = costMat(validRow,validCol);
%*************************************************
% Munkres' Assignment Algorithm starts here
%*************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STEP 1: Subtract the row minimum from each row.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
minR = min(dMat,[],2);
minC = min(bsxfun(@minus, dMat, minR));
%**************************************************************************
% STEP 2: Find a zero of dMat. If there are no starred zeros in its
% column or row start the zero. Repeat for each zero
%**************************************************************************
zP = dMat == bsxfun(@plus, minC, minR);
starZ = zeros(n,1);
while any(zP(:))
[r,c]=find(zP,1);
starZ(r)=c;
zP(r,:)=false;
zP(:,c)=false;
end
while 1
%**************************************************************************
% STEP 3: Cover each column with a starred zero. If all the columns are
% covered then the matching is maximum
%**************************************************************************
if all(starZ>0)
break
end
coverColumn = false(1,n);
coverColumn(starZ(starZ>0))=true;
coverRow = false(n,1);
primeZ = zeros(n,1);
[rIdx, cIdx] = find(dMat(~coverRow,~coverColumn)==bsxfun(@plus,minR(~coverRow),minC(~coverColumn)));
while 1
%**************************************************************************
% STEP 4: Find a noncovered zero and prime it. If there is no starred
% zero in the row containing this primed zero, Go to Step 5.
% Otherwise, cover this row and uncover the column containing
% the starred zero. Continue in this manner until there are no
% uncovered zeros left. Save the smallest uncovered value and
% Go to Step 6.
%**************************************************************************
cR = find(~coverRow);
cC = find(~coverColumn);
rIdx = cR(rIdx);
cIdx = cC(cIdx);
Step = 6;
while ~isempty(cIdx)
uZr = rIdx(1);
uZc = cIdx(1);
primeZ(uZr) = uZc;
stz = starZ(uZr);
if ~stz
Step = 5;
break;
end
coverRow(uZr) = true;
coverColumn(stz) = false;
z = rIdx==uZr;
rIdx(z) = [];
cIdx(z) = [];
cR = find(~coverRow);
z = dMat(~coverRow,stz) == minR(~coverRow) + minC(stz);
rIdx = [rIdx(:);cR(z)];
cIdx = [cIdx(:);stz(ones(sum(z),1))];
end
if Step == 6
% *************************************************************************
% STEP 6: Add the minimum uncovered value to every element of each covered
% row, and subtract it from every element of each uncovered column.
% Return to Step 4 without altering any stars, primes, or covered lines.
%**************************************************************************
[minval,rIdx,cIdx]=outerplus(dMat(~coverRow,~coverColumn),minR(~coverRow),minC(~coverColumn));
minC(~coverColumn) = minC(~coverColumn) + minval;
minR(coverRow) = minR(coverRow) - minval;
else
break
end
end
%**************************************************************************
% STEP 5:
% Construct a series of alternating primed and starred zeros as
% follows:
% Let Z0 represent the uncovered primed zero found in Step 4.
% Let Z1 denote the starred zero in the column of Z0 (if any).
% Let Z2 denote the primed zero in the row of Z1 (there will always
% be one). Continue until the series terminates at a primed zero
% that has no starred zero in its column. Unstar each starred
% zero of the series, star each primed zero of the series, erase
% all primes and uncover every line in the matrix. Return to Step 3.
%**************************************************************************
rowZ1 = find(starZ==uZc);
starZ(uZr)=uZc;
while rowZ1>0
starZ(rowZ1)=0;
uZc = primeZ(rowZ1);
uZr = rowZ1;
rowZ1 = find(starZ==uZc);
starZ(uZr)=uZc;
end
end
% Cost of assignment
rowIdx = find(validRow);
colIdx = find(validCol);
starZ = starZ(1:nRows);
vIdx = starZ <= nCols;
assignment(rowIdx(vIdx)) = colIdx(starZ(vIdx));
pass = assignment(assignment>0);
pass(~diag(validMat(assignment>0,pass))) = 0;
assignment(assignment>0) = pass;
cost = trace(costMat(assignment>0,assignment(assignment>0)));
function [minval,rIdx,cIdx]=outerplus(M,x,y)
ny=size(M,2);
minval=inf;
for c=1:ny
M(:,c)=M(:,c)-(x+y(c));
minval = min(minval,min(M(:,c)));
end
[rIdx,cIdx]=find(M==minval);
|
github
|
BII-wushuang/FLLIT-master
|
pdftops.m
|
.m
|
FLLIT-master/src/Export-Fig/pdftops.m
| 5,994 |
utf_8
|
24eb803667c83c8a28424c979311652b
|
function varargout = pdftops(cmd)
%PDFTOPS Calls a local pdftops executable with the input command
%
% Example:
% [status result] = pdftops(cmd)
%
% Attempts to locate a pdftops executable, finally asking the user to
% specify the directory pdftops was installed into. The resulting path is
% stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have pdftops (from the Xpdf package)
% installed on your system. You can download this from:
% http://www.foolabs.com/xpdf
%
% IN:
% cmd - Command string to be passed into pdftops (e.g. '-help').
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from pdftops.
% Copyright: Oliver Woodford, 2009-2010
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path under linux.
% 23/01/2014 - Add full path to pdftops.txt in warning.
% 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation
% 02/05/2016 - Added possible error explanation suggested by Michael Pacer (issue #137)
% 02/05/2016 - Search additional possible paths suggested by Jonas Stein (issue #147)
% 03/05/2016 - Display the specific error message if pdftops fails for some reason (issue #148)
% Call pdftops
[varargout{1:nargout}] = system([xpdf_command(xpdf_path()) cmd]);
end
function path_ = xpdf_path
% Return a valid path
% Start with the currently set path
path_ = user_string('pdftops');
% Check the path works
if check_xpdf_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = 'pdftops.exe';
else
bin = 'pdftops';
end
if check_store_xpdf_path(bin)
path_ = bin;
return
end
% Search the obvious places
if ispc
paths = {'C:\Program Files\xpdf\pdftops.exe', 'C:\Program Files (x86)\xpdf\pdftops.exe'};
else
paths = {'/usr/bin/pdftops', '/usr/local/bin/pdftops'};
end
for a = 1:numel(paths)
path_ = paths{a};
if check_store_xpdf_path(path_)
return
end
end
% Ask the user to enter the path
errMsg1 = 'Pdftops not found. Please locate the program, or install xpdf-tools from ';
url1 = 'http://foolabs.com/xpdf';
fprintf(2, '%s\n', [errMsg1 '<a href="matlab:web(''-browser'',''' url1 ''');">' url1 '</a>']);
errMsg1 = [errMsg1 url1];
%if strncmp(computer,'MAC',3) % Is a Mac
% % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title
% uiwait(warndlg(errMsg1))
%end
% Provide an alternative possible explanation as per issue #137
errMsg2 = 'If you have pdftops installed, perhaps Matlab is shaddowing it as described in ';
url2 = 'https://github.com/altmany/export_fig/issues/137';
fprintf(2, '%s\n', [errMsg2 '<a href="matlab:web(''-browser'',''' url2 ''');">issue #137</a>']);
errMsg2 = [errMsg2 url1];
state = 0;
while 1
if state
option1 = 'Install pdftops';
else
option1 = 'Issue #137';
end
answer = questdlg({errMsg1,'',errMsg2},'Pdftops error',option1,'Locate pdftops','Cancel','Cancel');
drawnow; % prevent a Matlab hang: http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem
switch answer
case 'Install pdftops'
web('-browser',url1);
case 'Issue #137'
web('-browser',url2);
state = 1;
case 'Locate pdftops'
base = uigetdir('/', errMsg1);
if isequal(base, 0)
% User hit cancel or closed window
break
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
path_ = [base bin_dir{a} bin];
if exist(path_, 'file') == 2
break
end
end
if check_store_xpdf_path(path_)
return
end
otherwise % User hit Cancel or closed window
break
end
end
error('pdftops executable not found.');
end
function good = check_store_xpdf_path(path_)
% Check the path is valid
good = check_xpdf_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('pdftops', path_)
warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
return
end
end
function good = check_xpdf_path(path_)
% Check the path is valid
[good, message] = system([xpdf_command(path_) '-h']); %#ok<ASGLU>
% system returns good = 1 even when the command runs
% Look for something distinct in the help text
good = ~isempty(strfind(message, 'PostScript'));
% Display the error message if the pdftops executable exists but fails for some reason
if ~good && exist(path_,'file') % file exists but generates an error
fprintf('Error running %s:\n', path_);
fprintf(2,'%s\n\n',message);
end
end
function cmd = xpdf_command(path_)
% Initialize any required system calls before calling ghostscript
% TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
shell_cmd = '';
if isunix
% Avoids an error on Linux with outdated MATLAB lib files
% R20XXa/bin/glnxa64/libtiff.so.X
% R20XXa/sys/os/glnxa64/libstdc++.so.X
shell_cmd = 'export LD_LIBRARY_PATH=""; ';
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';
end
% Construct the command string
cmd = sprintf('%s"%s" ', shell_cmd, path_);
end
|
github
|
BII-wushuang/FLLIT-master
|
crop_borders.m
|
.m
|
FLLIT-master/src/Export-Fig/crop_borders.m
| 4,976 |
utf_8
|
c814ff486afb188464069b51e4b5ed8a
|
function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding, crop_amounts)
%CROP_BORDERS Crop the borders of an image or stack of images
%
% [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])
%
%IN:
% A - HxWxCxN stack of images.
% bcol - Cx1 background colour vector.
% padding - scalar indicating how much padding to have in relation to
% the cropped-image-size (0<=padding<=1). Default: 0
% crop_amounts - 4-element vector of crop amounts: [top,right,bottom,left]
% where NaN/Inf indicate auto-cropping, 0 means no cropping,
% and any other value mean cropping in pixel amounts.
%
%OUT:
% B - JxKxCxN cropped stack of images.
% vA - coordinates in A that contain the cropped image
% vB - coordinates in B where the cropped version of A is placed
% bb_rel - relative bounding box (used for eps-cropping)
%{
% 06/03/15: Improved image cropping thanks to Oscar Hartogensis
% 08/06/15: Fixed issue #76: case of transparent figure bgcolor
% 21/02/16: Enabled specifying non-automated crop amounts
% 04/04/16: Fix per Luiz Carvalho for old Matlab releases
% 23/10/16: Fixed issue #175: there used to be a 1px minimal padding in case of crop, now removed
%}
if nargin < 3
padding = 0;
end
if nargin < 4
crop_amounts = nan(1,4); % =auto-cropping
end
crop_amounts(end+1:4) = NaN; % fill missing values with NaN
[h, w, c, n] = size(A);
if isempty(bcol) % case of transparent bgcolor
bcol = A(ceil(end/2),1,:,1);
end
if isscalar(bcol)
bcol = bcol(ones(c, 1));
end
% Crop margin from left
if ~isfinite(crop_amounts(4))
bail = false;
for l = 1:w
for a = 1:c
if ~all(col(A(:,l,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
l = 1 + abs(crop_amounts(4));
end
% Crop margin from right
if ~isfinite(crop_amounts(2))
bcol = A(ceil(end/2),w,:,1);
bail = false;
for r = w:-1:l
for a = 1:c
if ~all(col(A(:,r,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
r = w - abs(crop_amounts(2));
end
% Crop margin from top
if ~isfinite(crop_amounts(1))
bcol = A(1,ceil(end/2),:,1);
bail = false;
for t = 1:h
for a = 1:c
if ~all(col(A(t,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
t = 1 + abs(crop_amounts(1));
end
% Crop margin from bottom
bcol = A(h,ceil(end/2),:,1);
if ~isfinite(crop_amounts(3))
bail = false;
for b = h:-1:t
for a = 1:c
if ~all(col(A(b,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
b = h - abs(crop_amounts(3));
end
if padding == 0 % no padding
% Issue #175: there used to be a 1px minimal padding in case of crop, now removed
%{
if ~isequal([t b l r], [1 h 1 w]) % Check if we're actually croppping
padding = 1; % Leave one boundary pixel to avoid bleeding on resize
bcol(:) = nan; % make the 1px padding transparent
end
%}
elseif abs(padding) < 1 % pad value is a relative fraction of image size
padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING
else % pad value is in units of 1/72" points
padding = round(padding); % fix cases of non-integer pad value
end
if padding > 0 % extra padding
% Create an empty image, containing the background color, that has the
% cropped image size plus the padded border
B = repmat(bcol,[(b-t)+1+padding*2,(r-l)+1+padding*2,1,n]); % Fix per Luiz Carvalho
% vA - coordinates in A that contain the cropped image
vA = [t b l r];
% vB - coordinates in B where the cropped version of A will be placed
vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];
% Place the original image in the empty image
B(vB(1):vB(2), vB(3):vB(4), :, :) = A(vA(1):vA(2), vA(3):vA(4), :, :);
A = B;
else % extra cropping
vA = [t-padding b+padding l-padding r+padding];
A = A(vA(1):vA(2), vA(3):vA(4), :, :);
vB = [NaN NaN NaN NaN];
end
% For EPS cropping, determine the relative BoundingBox - bb_rel
bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];
end
function A = col(A)
A = A(:);
end
|
github
|
BII-wushuang/FLLIT-master
|
isolate_axes.m
|
.m
|
FLLIT-master/src/Export-Fig/isolate_axes.m
| 4,721 |
utf_8
|
253cd7b7d8fc7cb00d0cc55926f32de5
|
function fh = isolate_axes(ah, vis)
%ISOLATE_AXES Isolate the specified axes in a figure on their own
%
% Examples:
% fh = isolate_axes(ah)
% fh = isolate_axes(ah, vis)
%
% This function will create a new figure containing the axes/uipanels
% specified, and also their associated legends and colorbars. The objects
% specified must all be in the same figure, but they will generally only be
% a subset of the objects in the figure.
%
% IN:
% ah - An array of axes and uipanel handles, which must come from the
% same figure.
% vis - A boolean indicating whether the new figure should be visible.
% Default: false.
%
% OUT:
% fh - The handle of the created figure.
% Copyright (C) Oliver Woodford 2011-2013
% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
% 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio
% for pointing out that the function is also used in export_fig.m
% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it
% 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!)
% 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting
% 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro
% on FEX page as a comment on 24-Apr-2014); standardized indentation & help section
% 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2
% Make sure we have an array of handles
if ~all(ishandle(ah))
error('ah must be an array of handles');
end
% Check that the handles are all for axes or uipanels, and are all in the same figure
fh = ancestor(ah(1), 'figure');
nAx = numel(ah);
for a = 1:nAx
if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
error('All handles must be axes or uipanel handles.');
end
if ~isequal(ancestor(ah(a), 'figure'), fh)
error('Axes must all come from the same figure.');
end
end
% Tag the objects so we can find them in the copy
old_tag = get(ah, 'Tag');
if nAx == 1
old_tag = {old_tag};
end
set(ah, 'Tag', 'ObjectToCopy');
% Create a new figure exactly the same as the old one
fh = copyfig(fh); %copyobj(fh, 0);
if nargin < 2 || ~vis
set(fh, 'Visible', 'off');
end
% Reset the object tags
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Find the objects to save
ah = findall(fh, 'Tag', 'ObjectToCopy');
if numel(ah) ~= nAx
close(fh);
error('Incorrect number of objects found.');
end
% Set the axes tags to what they should be
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Keep any legends and colorbars which overlap the subplots
% Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we
% don't test for the type, only the tag (hopefully nobody but Matlab uses them!)
lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar');
nLeg = numel(lh);
if nLeg > 0
set([ah(:); lh(:)], 'Units', 'normalized');
try
ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property
catch
ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition
end
if nAx > 1
ax_pos = cell2mat(ax_pos(:));
end
ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
try
leg_pos = get(lh, 'OuterPosition');
catch
leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1
end
if nLeg > 1;
leg_pos = cell2mat(leg_pos);
end
leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
ax_pos = shiftdim(ax_pos, -1);
% Overlap test
M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
ah = [ah; lh(any(M, 2))];
end
% Get all the objects in the figure
axs = findall(fh);
% Delete everything except for the input objects and associated items
delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
end
function ah = allchildren(ah)
ah = findall(ah);
if iscell(ah)
ah = cell2mat(ah);
end
ah = ah(:);
end
function ph = allancestors(ah)
ph = [];
for a = 1:numel(ah)
h = get(ah(a), 'parent');
while h ~= 0
ph = [ph; h];
h = get(h, 'parent');
end
end
end
|
github
|
BII-wushuang/FLLIT-master
|
im2gif.m
|
.m
|
FLLIT-master/src/Export-Fig/im2gif.m
| 6,048 |
utf_8
|
5a7437140f8d013158a195de1e372737
|
%IM2GIF Convert a multiframe image to an animated GIF file
%
% Examples:
% im2gif infile
% im2gif infile outfile
% im2gif(A, outfile)
% im2gif(..., '-nocrop')
% im2gif(..., '-nodither')
% im2gif(..., '-ncolors', n)
% im2gif(..., '-loops', n)
% im2gif(..., '-delay', n)
%
% This function converts a multiframe image to an animated GIF.
%
% To create an animation from a series of figures, export to a multiframe
% TIFF file using export_fig, then convert to a GIF, as follows:
%
% for a = 2 .^ (3:6)
% peaks(a);
% export_fig test.tif -nocrop -append
% end
% im2gif('test.tif', '-delay', 0.5);
%
%IN:
% infile - string containing the name of the input image.
% outfile - string containing the name of the output image (must have the
% .gif extension). Default: infile, with .gif extension.
% A - HxWxCxN array of input images, stacked along fourth dimension, to
% be converted to gif.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -nodither - option indicating that dithering is not to be used when
% converting the image.
% -ncolors - option pair, the value of which indicates the maximum number
% of colors the GIF can have. This can also be a quantization
% tolerance, between 0 and 1. Default/maximum: 256.
% -loops - option pair, the value of which gives the number of times the
% animation is to be looped. Default: 65535.
% -delay - option pair, the value of which gives the time, in seconds,
% between frames. Default: 1/15.
% Copyright (C) Oliver Woodford 2011
function im2gif(A, varargin)
% Parse the input arguments
[A, options] = parse_args(A, varargin{:});
if options.crop ~= 0
% Crop
A = crop_borders(A, A(ceil(end/2),1,:,1));
end
% Convert to indexed image
[h, w, c, n] = size(A);
A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
map = unique(reshape(A, h*w*n, c), 'rows');
if size(map, 1) > 256
dither_str = {'dither', 'nodither'};
dither_str = dither_str{1+(options.dither==0)};
if options.ncolors <= 1
[B, map] = rgb2ind(A, options.ncolors, dither_str);
if size(map, 1) > 256
[B, map] = rgb2ind(A, 256, dither_str);
end
else
[B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
end
else
if max(map(:)) > 1
map = double(map) / 255;
A = double(A) / 255;
end
B = rgb2ind(im2double(A), map);
end
B = reshape(B, h, w, 1, n);
% Bug fix to rgb2ind
map(B(1)+1,:) = im2double(A(1,1,:));
% Save as a gif
imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
end
%% Parse the input arguments
function [A, options] = parse_args(A, varargin)
% Set the defaults
options = struct('outfile', '', ...
'dither', true, ...
'crop', true, ...
'ncolors', 256, ...
'loops', 65535, ...
'delay', 1/15);
% Go through the arguments
a = 0;
n = numel(varargin);
while a < n
a = a + 1;
if ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
opt = lower(varargin{a}(2:end));
switch opt
case 'nocrop'
options.crop = false;
case 'nodither'
options.dither = false;
otherwise
if ~isfield(options, opt)
error('Option %s not recognized', varargin{a});
end
a = a + 1;
if ischar(varargin{a}) && ~ischar(options.(opt))
options.(opt) = str2double(varargin{a});
else
options.(opt) = varargin{a};
end
end
else
options.outfile = varargin{a};
end
end
end
if isempty(options.outfile)
if ~ischar(A)
error('No output filename given.');
end
% Generate the output filename from the input filename
[path, outfile] = fileparts(A);
options.outfile = fullfile(path, [outfile '.gif']);
end
if ischar(A)
% Read in the image
A = imread_rgb(A);
end
end
%% Read image to uint8 rgb array
function [A, alpha] = imread_rgb(name)
% Get file info
info = imfinfo(name);
% Special case formats
switch lower(info(1).Format)
case 'gif'
[A, map] = imread(name, 'frames', 'all');
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
A = permute(A, [1 2 5 4 3]);
end
case {'tif', 'tiff'}
A = cell(numel(info), 1);
for a = 1:numel(A)
[A{a}, map] = imread(name, 'Index', a, 'Info', info);
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
end
if size(A{a}, 3) == 4
% TIFF in CMYK colourspace - convert to RGB
if isfloat(A{a})
A{a} = A{a} * 255;
else
A{a} = single(A{a});
end
A{a} = 255 - A{a};
A{a}(:,:,4) = A{a}(:,:,4) / 255;
A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
end
end
A = cat(4, A{:});
otherwise
[A, map, alpha] = imread(name);
A = A(:,:,:,1); % Keep only first frame of multi-frame files
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
elseif size(A, 3) == 4
% Assume 4th channel is an alpha matte
alpha = A(:,:,4);
A = A(:,:,1:3);
end
end
end
|
github
|
BII-wushuang/FLLIT-master
|
read_write_entire_textfile.m
|
.m
|
FLLIT-master/src/Export-Fig/read_write_entire_textfile.m
| 924 |
utf_8
|
779e56972f5d9778c40dee98ddbd677e
|
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory
%
% Read or write an entire text file to/from memory, without leaving the
% file open if an error occurs.
%
% Reading:
% fstrm = read_write_entire_textfile(fname)
% Writing:
% read_write_entire_textfile(fname, fstrm)
%
%IN:
% fname - Pathname of text file to be read in.
% fstrm - String to be written to the file, including carriage returns.
%
%OUT:
% fstrm - String read from the file. If an fstrm input is given the
% output is the same as that input.
function fstrm = read_write_entire_textfile(fname, fstrm)
modes = {'rt', 'wt'};
writing = nargin > 1;
fh = fopen(fname, modes{1+writing});
if fh == -1
error('Unable to open file %s.', fname);
end
try
if writing
fwrite(fh, fstrm, 'char*1');
else
fstrm = fread(fh, '*char')';
end
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
|
github
|
BII-wushuang/FLLIT-master
|
pdf2eps.m
|
.m
|
FLLIT-master/src/Export-Fig/pdf2eps.m
| 1,471 |
utf_8
|
a1f41f0c7713c73886a2323e53ed982b
|
%PDF2EPS Convert a pdf file to eps format using pdftops
%
% Examples:
% pdf2eps source dest
%
% This function converts a pdf file to eps format.
%
% This function requires that you have pdftops, from the Xpdf suite of
% functions, installed on your system. This can be downloaded from:
% http://www.foolabs.com/xpdf
%
%IN:
% source - filename of the source pdf file to convert. The filename is
% assumed to already have the extension ".pdf".
% dest - filename of the destination eps file. The filename is assumed to
% already have the extension ".eps".
% Copyright (C) Oliver Woodford 2009-2010
% Thanks to Aldebaro Klautau for reporting a bug when saving to
% non-existant directories.
function pdf2eps(source, dest)
% Construct the options string for pdftops
options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
% Convert to eps using pdftops
[status, message] = pdftops(options);
% Check for error
if status
% Report error
if isempty(message)
error('Unable to generate eps. Check destination directory is writable.');
else
error(message);
end
end
% Fix the DSC error created by pdftops
fid = fopen(dest, 'r+');
if fid == -1
% Cannot open the file
return
end
fgetl(fid); % Get the first line
str = fgetl(fid); % Get the second line
if strcmp(str(1:min(13, end)), '% Produced by')
fseek(fid, -numel(str)-1, 'cof');
fwrite(fid, '%'); % Turn ' ' into '%'
end
fclose(fid);
end
|
github
|
BII-wushuang/FLLIT-master
|
print2array.m
|
.m
|
FLLIT-master/src/Export-Fig/print2array.m
| 10,117 |
utf_8
|
826905ad12ce0de461386980b4aae89b
|
function [A, bcol] = print2array(fig, res, renderer, gs_options)
%PRINT2ARRAY Exports a figure to an image array
%
% Examples:
% A = print2array
% A = print2array(figure_handle)
% A = print2array(figure_handle, resolution)
% A = print2array(figure_handle, resolution, renderer)
% A = print2array(figure_handle, resolution, renderer, gs_options)
% [A bcol] = print2array(...)
%
% This function outputs a bitmap image of the given figure, at the desired
% resolution.
%
% If renderer is '-painters' then ghostcript needs to be installed. This
% can be downloaded from: http://www.ghostscript.com
%
% IN:
% figure_handle - The handle of the figure to be exported. Default: gcf.
% resolution - Resolution of the output, as a factor of screen
% resolution. Default: 1.
% renderer - string containing the renderer paramater to be passed to
% print. Default: '-opengl'.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
%
% OUT:
% A - MxNx3 uint8 image of the figure.
% bcol - 1x3 uint8 vector of the background color
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
%{
% 05/09/11: Set EraseModes to normal when using opengl or zbuffer
% renderers. Thanks to Pawel Kocieniewski for reporting the issue.
% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it.
% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size
% and erasemode settings. Makes it a bit slower, but more reliable.
% Thanks to Phil Trinh and Meelis Lootus for reporting the issues.
% 09/12/11: Pass font path to ghostscript.
% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
% Ken Campbell for reporting it.
% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it.
% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
% reporting the issue.
% 26/02/15: If temp dir is not writable, use the current folder for temp
% EPS/TIF files (Javier Paredes)
% 27/02/15: Display suggested workarounds to internal print() error (issue #16)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation
% 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func)
% 07/07/15: Fixed issue #83: use numeric handles in HG1
% 11/12/16: Fixed cropping issue reported by Harry D.
%}
% Generate default input arguments, if needed
if nargin < 2
res = 1;
if nargin < 1
fig = gcf;
end
end
% Warn if output is large
old_mode = get(fig, 'Units');
set(fig, 'Units', 'pixels');
px = get(fig, 'Position');
set(fig, 'Units', old_mode);
npx = prod(px(3:4)*res)/1e6;
if npx > 30
% 30M pixels or larger!
warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
end
% Retrieve the background colour
bcol = get(fig, 'Color');
% Set the resolution parameter
res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
% Generate temporary file name
tmp_nam = [tempname '.tif'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam); % cleanup
isTempDirOk = true;
catch
% Temp dir is not writable, so use the current folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = pwd;
tmp_nam = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 3 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
else
gs_options = '';
end
if nargin > 2 && strcmp(renderer, '-painters')
% First try to print directly to tif file
try
% Print the file into a temporary TIF file and read it into array A
[A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);
if err, rethrow(ex); end
catch % error - try to print to EPS and then using Ghostscript to TIF
% Print to eps file
if isTempDirOk
tmp_eps = [tempname '.eps'];
else
tmp_eps = fullfile(fpath,[fname '.eps']);
end
print2eps(tmp_eps, fig, 0, renderer, '-loose');
try
% Initialize the command to export to tiff using ghostscript
cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
% Set the font path
fp = font_path();
if ~isempty(fp)
cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
end
% Add the filenames
cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options];
% Execute the ghostscript command
ghostscript(cmd_str);
catch me
% Delete the intermediate file
delete(tmp_eps);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_eps);
% Read in the generated bitmap
A = imread(tmp_nam);
% Delete the temporary bitmap file
delete(tmp_nam);
end
% Set border pixels to the correct colour
if isequal(bcol, 'none')
bcol = [];
elseif isequal(bcol, [1 1 1])
bcol = uint8([255 255 255]);
else
for l = 1:size(A, 2)
if ~all(reshape(A(:,l,:) == 255, [], 1))
break;
end
end
for r = size(A, 2):-1:l
if ~all(reshape(A(:,r,:) == 255, [], 1))
break;
end
end
for t = 1:size(A, 1)
if ~all(reshape(A(t,:,:) == 255, [], 1))
break;
end
end
for b = size(A, 1):-1:t
if ~all(reshape(A(b,:,:) == 255, [], 1))
break;
end
end
bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
for c = 1:size(A, 3)
A(:,[1:l-1, r+1:end],c) = bcol(c);
A([1:t-1, b+1:end],:,c) = bcol(c);
end
end
else
if nargin < 3
renderer = '-opengl';
end
% Print the file into a temporary TIF file and read it into array A
[A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);
% Throw any error that occurred
if err
% Display suggested workarounds to internal print() error (issue #16)
fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n');
rethrow(ex);
end
% Set the background color
if isequal(bcol, 'none')
bcol = [];
else
bcol = bcol * 255;
if isequal(bcol, round(bcol))
bcol = uint8(bcol);
else
bcol = squeeze(A(1,1,:));
end
end
end
% Check the output size is correct
if isequal(res, round(res))
px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below
if ~isequal(size(A), px)
% Correct the output size
A = A(1:min(end,px(1)),1:min(end,px(2)),:);
end
end
end
% Function to create a TIF image of the figure and read it into an array
function [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam)
err = false;
ex = [];
% Temporarily set the paper size
old_pos_mode = get(fig, 'PaperPositionMode');
old_orientation = get(fig, 'PaperOrientation');
set(fig, 'PaperPositionMode','auto', 'PaperOrientation','portrait');
try
% Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function)
fp = []; % in case we get an error below
fp = findall(fig, 'Type','patch', 'LineWidth',0.75);
set(fp, 'LineWidth',0.5);
% Fix issue #83: use numeric handles in HG1
if ~using_hg2(fig), fig = double(fig); end
% Print to tiff file
print(fig, renderer, res_str, '-dtiff', tmp_nam);
% Read in the printed file
A = imread(tmp_nam);
% Delete the temporary file
delete(tmp_nam);
catch ex
err = true;
end
set(fp, 'LineWidth',0.75); % restore original figure appearance
% Reset the paper size
set(fig, 'PaperPositionMode',old_pos_mode, 'PaperOrientation',old_orientation);
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github
|
BII-wushuang/FLLIT-master
|
append_pdfs.m
|
.m
|
FLLIT-master/src/Export-Fig/append_pdfs.m
| 2,678 |
utf_8
|
949c7c4ec3f5af6ff23099f17b1dfd79
|
%APPEND_PDFS Appends/concatenates multiple PDF files
%
% Example:
% append_pdfs(output, input1, input2, ...)
% append_pdfs(output, input_list{:})
% append_pdfs test.pdf temp1.pdf temp2.pdf
%
% This function appends multiple PDF files to an existing PDF file, or
% concatenates them into a PDF file if the output file doesn't yet exist.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% IN:
% output - string of output file name (including the extension, .pdf).
% If it exists it is appended to; if not, it is created.
% input1 - string of an input file name (including the extension, .pdf).
% All input files are appended in order.
% input_list - cell array list of input file name strings. All input
% files are appended in order.
% Copyright: Oliver Woodford, 2011
% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
% one go is much faster than appending them one at a time.
% Thanks to Michael Teo for reporting the issue of a too long command line.
% Issue resolved on 5/5/2011, by passing gs a command file.
% Thanks to Martin Wittmann for pointing out the quality issue when
% appending multiple bitmaps.
% Issue resolved (to best of my ability) 1/6/2011, using the prepress
% setting
% 26/02/15: If temp dir is not writable, use the output folder for temp
% files when appending (Javier Paredes); sanity check of inputs
function append_pdfs(varargin)
if nargin < 2, return; end % sanity check
% Are we appending or creating a new file
append = exist(varargin{1}, 'file') == 2;
output = [tempname '.pdf'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(output,'w');
fwrite(fid,1);
fclose(fid);
delete(output);
isTempDirOk = true;
catch
% Temp dir is not writable, so use the output folder
[dummy,fname,fext] = fileparts(output); %#ok<ASGLU>
fpath = fileparts(varargin{1});
output = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
if ~append
output = varargin{1};
varargin = varargin(2:end);
end
% Create the command file
if isTempDirOk
cmdfile = [tempname '.txt'];
else
cmdfile = fullfile(fpath,[fname '.txt']);
end
fh = fopen(cmdfile, 'w');
fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
fprintf(fh, ' "%s"', varargin{:});
fclose(fh);
% Call ghostscript
ghostscript(['@"' cmdfile '"']);
% Delete the command file
delete(cmdfile);
% Rename the file if needed
if append
movefile(output, varargin{1});
end
end
|
github
|
BII-wushuang/FLLIT-master
|
using_hg2.m
|
.m
|
FLLIT-master/src/Export-Fig/using_hg2.m
| 1,064 |
utf_8
|
a1883d15c4304cd0ac406c117e3047ea
|
%USING_HG2 Determine if the HG2 graphics engine is used
%
% tf = using_hg2(fig)
%
%IN:
% fig - handle to the figure in question.
%
%OUT:
% tf - boolean indicating whether the HG2 graphics engine is being used
% (true) or not (false).
% 19/06/2015 - Suppress warning in R2015b; cache result for improved performance
% 06/06/2016 - Fixed issue #156 (bad return value in R2016b)
function tf = using_hg2(fig)
persistent tf_cached
if isempty(tf_cached)
try
if nargin < 1, fig = figure('visible','off'); end
oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval');
try
% This generates a [supressed] warning in R2015b:
tf = ~graphicsversion(fig, 'handlegraphics');
catch
tf = ~verLessThan('matlab','8.4'); % =R2014b
end
warning(oldWarn);
catch
tf = false;
end
if nargin < 1, delete(fig); end
tf_cached = tf;
else
tf = tf_cached;
end
end
|
github
|
BII-wushuang/FLLIT-master
|
eps2pdf.m
|
.m
|
FLLIT-master/src/Export-Fig/eps2pdf.m
| 8,602 |
utf_8
|
a52a68e75e8696267fb74733d396a237
|
function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%EPS2PDF Convert an eps file to pdf format using ghostscript
%
% Examples:
% eps2pdf source dest
% eps2pdf(source, dest, crop)
% eps2pdf(source, dest, crop, append)
% eps2pdf(source, dest, crop, append, gray)
% eps2pdf(source, dest, crop, append, gray, quality)
% eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% Inputs:
% source - filename of the source eps file to convert. The filename is
% assumed to already have the extension ".eps".
% dest - filename of the destination pdf file. The filename is assumed
% to already have the extension ".pdf".
% crop - boolean indicating whether to crop the borders off the pdf.
% Default: true.
% append - boolean indicating whether the eps should be appended to the
% end of the pdf as a new page (if the pdf exists already).
% Default: false.
% gray - boolean indicating whether the output pdf should be grayscale
% or not. Default: false.
% quality - scalar indicating the level of image bitmap quality to
% output. A larger value gives a higher quality. quality > 100
% gives lossless output. Default: ghostscript prepress default.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-
% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629
% Thank you to Fabio Viola for pointing out compression artifacts, leading
% to the quality setting.
% Thank you to Scott for pointing out the subsampling of very small images,
% which was fixed for lossless compression settings.
% 9/12/2011 Pass font path to ghostscript.
% 26/02/15: If temp dir is not writable, use the dest folder for temp
% destination files (Javier Paredes)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
% some /findfont errors according to James Rankin, FEX Comment 23/01/15)
% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
% 20/03/17: Added informational message in case of GS croak (issue #186)
% Intialise the options string for ghostscript
options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
% Set crop option
if nargin < 3 || crop
options = [options ' -dEPSCrop'];
end
% Set the font path
fp = font_path();
if ~isempty(fp)
options = [options ' -sFONTPATH="' fp '"'];
end
% Set the grayscale option
if nargin > 4 && gray
options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
end
% Set the bitmap quality
if nargin > 5 && ~isempty(quality)
options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
if quality > 100
options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
else
options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
v = 1 + (quality < 80);
quality = 1 - quality / 100;
s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
end
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 6 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
options = [options gs_options];
end
% Check if the output file exists
if nargin > 3 && append && exist(dest, 'file') == 2
% File exists - append current figure to the end
tmp_nam = tempname;
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam);
catch
% Temp dir is not writable, so use the dest folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = fileparts(dest);
tmp_nam = fullfile(fpath,[fname fext]);
end
% Copy the file
copyfile(dest, tmp_nam);
% Add the output file names
options = [options ' -f "' tmp_nam '" "' source '"'];
try
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
catch me
% Delete the intermediate file
delete(tmp_nam);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_nam);
else
% File doesn't exist or should be over-written
% Add the output file names
options = [options ' -f "' source '"'];
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
end
% Check for error
if status
% Retry without the -sFONTPATH= option (this might solve some GS
% /findfont errors according to James Rankin, FEX Comment 23/01/15)
orig_options = options;
if ~isempty(fp)
options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
status = ghostscript(options);
if ~status, return; end % hurray! (no error)
end
% Report error
if isempty(message)
error('Unable to generate pdf. Check destination directory is writable.');
elseif ~isempty(strfind(message,'/typecheck in /findfont'))
% Suggest a workaround for issue #41 (missing font path)
font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
fpath = fileparts(mfilename('fullpath'));
gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file);
error('export_fig error');
else
fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest);
if ~isempty(gs_options)
fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options);
end
fprintf(2, ' or maybe you have another gs executable in your system''s path\n');
fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
error(message);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github
|
BII-wushuang/FLLIT-master
|
export_fig.m
|
.m
|
FLLIT-master/src/Export-Fig/export_fig.m
| 63,939 |
utf_8
|
d501f71f10a1918328c0e9d450cd1ed3
|
function [imageData, alpha] = export_fig(varargin)
%EXPORT_FIG Exports figures in a publication-quality format
%
% Examples:
% imageData = export_fig
% [imageData, alpha] = export_fig
% export_fig filename
% export_fig filename -format1 -format2
% export_fig ... -nocrop
% export_fig ... -c[<val>,<val>,<val>,<val>]
% export_fig ... -transparent
% export_fig ... -native
% export_fig ... -m<val>
% export_fig ... -r<val>
% export_fig ... -a<val>
% export_fig ... -q<val>
% export_fig ... -p<val>
% export_fig ... -d<gs_option>
% export_fig ... -depsc
% export_fig ... -<renderer>
% export_fig ... -<colorspace>
% export_fig ... -append
% export_fig ... -bookmark
% export_fig ... -clipboard
% export_fig ... -update
% export_fig ... -nofontswap
% export_fig ... -font_space <char>
% export_fig ... -linecaps
% export_fig ... -noinvert
% export_fig(..., handle)
%
% This function saves a figure or single axes to one or more vector and/or
% bitmap file formats, and/or outputs a rasterized version to the workspace,
% with the following properties:
% - Figure/axes reproduced as it appears on screen
% - Cropped borders (optional)
% - Embedded fonts (vector formats)
% - Improved line and grid line styles
% - Anti-aliased graphics (bitmap formats)
% - Render images at native resolution (optional for bitmap formats)
% - Transparent background supported (pdf, eps, png, tiff)
% - Semi-transparent patch objects supported (png, tiff)
% - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)
% - Variable image compression, including lossless (pdf, eps, jpg)
% - Optional rounded line-caps (pdf, eps)
% - Optionally append to file (pdf, tiff)
% - Vector formats: pdf, eps
% - Bitmap formats: png, tiff, jpg, bmp, export to workspace
%
% This function is especially suited to exporting figures for use in
% publications and presentations, because of the high quality and
% portability of media produced.
%
% Note that the background color and figure dimensions are reproduced
% (the latter approximately, and ignoring cropping & magnification) in the
% output file. For transparent background (and semi-transparent patch
% objects), use the -transparent option or set the figure 'Color' property
% to 'none'. To make axes transparent set the axes 'Color' property to
% 'none'. PDF, EPS, TIF & PNG are the only formats that support a transparent
% background; only TIF & PNG formats support transparency of patch objects.
%
% The choice of renderer (opengl, zbuffer or painters) has a large impact
% on the quality of output. The default value (opengl for bitmaps, painters
% for vector formats) generally gives good results, but if you aren't
% satisfied then try another renderer. Notes: 1) For vector formats (EPS,
% PDF), only painters generates vector graphics. 2) For bitmaps, only
% opengl can render transparent patch objects correctly. 3) For bitmaps,
% only painters will correctly scale line dash and dot lengths when
% magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when
% using painters.
%
% When exporting to vector format (PDF & EPS) and bitmap format using the
% painters renderer, this function requires that ghostscript is installed
% on your system. You can download this from:
% http://www.ghostscript.com
% When exporting to eps it additionally requires pdftops, from the Xpdf
% suite of functions. You can download this from:
% http://www.foolabs.com/xpdf
%
% Inputs:
% filename - string containing the name (optionally including full or
% relative path) of the file the figure is to be saved as. If
% a path is not specified, the figure is saved in the current
% directory. If no name and no output arguments are specified,
% the default name, 'export_fig_out', is used. If neither a
% file extension nor a format are specified, a ".png" is added
% and the figure saved in that format.
% -format1, -format2, etc. - strings containing the extensions of the
% file formats the figure is to be saved as.
% Valid options are: '-pdf', '-eps', '-png',
% '-tif', '-jpg' and '-bmp'. All combinations
% of formats are valid.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -c[<val>,<val>,<val>,<val>] - option indicating crop amounts. Must be
% a 4-element vector of numeric values: [top,right,bottom,left]
% where NaN/Inf indicate auto-cropping, 0 means no cropping,
% and any other value mean cropping in pixel amounts.
% -transparent - option indicating that the figure background is to be
% made transparent (png, pdf, tif and eps output only).
% -m<val> - option where val indicates the factor to magnify the
% on-screen figure pixel dimensions by when generating bitmap
% outputs (does not affect vector formats). Default: '-m1'.
% -r<val> - option val indicates the resolution (in pixels per inch) to
% export bitmap and vector outputs at, keeping the dimensions
% of the on-screen figure. Default: '-r864' (for vector output
% only). Note that the -m option overides the -r option for
% bitmap outputs only.
% -native - option indicating that the output resolution (when outputting
% a bitmap format) should be such that the vertical resolution
% of the first suitable image found in the figure is at the
% native resolution of that image. To specify a particular
% image to use, give it the tag 'export_fig_native'. Notes:
% This overrides any value set with the -m and -r options. It
% also assumes that the image is displayed front-to-parallel
% with the screen. The output resolution is approximate and
% should not be relied upon. Anti-aliasing can have adverse
% effects on image quality (disable with the -a1 option).
% -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to
% use for bitmap outputs. '-a1' means no anti-
% aliasing; '-a4' is the maximum amount (default).
% -<renderer> - option to force a particular renderer (painters, opengl or
% zbuffer). Default value: opengl for bitmap formats or
% figures with patches and/or transparent annotations;
% painters for vector formats without patches/transparencies.
% -<colorspace> - option indicating which colorspace color figures should
% be saved in: RGB (default), CMYK or gray. CMYK is only
% supported in pdf, eps and tiff output.
% -q<val> - option to vary bitmap image quality (in pdf, eps and jpg
% files only). Larger val, in the range 0-100, gives higher
% quality/lower compression. val > 100 gives lossless
% compression. Default: '-q95' for jpg, ghostscript prepress
% default for pdf & eps. Note: lossless compression can
% sometimes give a smaller file size than the default lossy
% compression, depending on the type of images.
% -p<val> - option to pad a border of width val to exported files, where
% val is either a relative size with respect to cropped image
% size (i.e. p=0.01 adds a 1% border). For EPS & PDF formats,
% val can also be integer in units of 1/72" points (abs(val)>1).
% val can be positive (padding) or negative (extra cropping).
% If used, the -nocrop flag will be ignored, i.e. the image will
% always be cropped and then padded. Default: 0 (i.e. no padding).
% -append - option indicating that if the file (pdfs only) already
% exists, the figure is to be appended as a new page, instead
% of being overwritten (default).
% -bookmark - option to indicate that a bookmark with the name of the
% figure is to be created in the output file (pdf only).
% -clipboard - option to save output as an image on the system clipboard.
% Note: background transparency is not preserved in clipboard
% -d<gs_option> - option to indicate a ghostscript setting. For example,
% -dMaxBitmap=0 or -dNoOutputFonts (Ghostscript 9.15+).
% -depsc - option to use EPS level-3 rather than the default level-2 print
% device. This solves some bugs with Matlab's default -depsc2 device
% such as discolored subplot lines on images (vector formats only).
% -update - option to download and install the latest version of export_fig
% -nofontswap - option to avoid font swapping. Font swapping is automatically
% done in vector formats (only): 11 standard Matlab fonts are
% replaced by the original figure fonts. This option prevents this.
% -font_space <char> - option to set a spacer character for font-names that
% contain spaces, used by EPS/PDF. Default: ''
% -linecaps - option to create rounded line-caps (vector formats only).
% -noinvert - option to avoid setting figure's InvertHardcopy property to
% 'off' during output (this solves some problems of empty outputs).
% handle - The handle of the figure, axes or uipanels (can be an array of
% handles, but the objects must be in the same figure) to be
% saved. Default: gcf.
%
% Outputs:
% imageData - MxNxC uint8 image array of the exported image.
% alpha - MxN single array of alphamatte values in the range [0,1],
% for the case when the background is transparent.
%
% Some helpful examples and tips can be found at:
% https://github.com/altmany/export_fig
%
% See also PRINT, SAVEAS, ScreenCapture (on the Matlab File Exchange)
%{
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
% The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG
% (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782).
% The idea for using pdftops came from the MATLAB newsgroup (id: 168171).
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928).
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id:
% 20979).
% The idea of appending figures in pdfs came from Matt C in comments on the
% FEX (id: 23629)
% Thanks to Roland Martin for pointing out the colour MATLAB
% bug/feature with colorbar axes and transparent backgrounds.
% Thanks also to Andrew Matthews for describing a bug to do with the figure
% size changing in -nodisplay mode. I couldn't reproduce it, but included a
% fix anyway.
% Thanks to Tammy Threadgill for reporting a bug where an axes is not
% isolated from gui objects.
%}
%{
% 23/02/12: Ensure that axes limits don't change during printing
% 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for reporting it).
% 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling bookmarking of figures in pdf files.
% 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep tick marks fixed.
% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it.
% 25/09/13: Add support for changing resolution in vector formats. Thanks to Jan Jaap Meijer for suggesting it.
% 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner for suggesting it.
% 24/02/15: Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual'
% 25/02/15: Fix issue #4 (using HG2 on R2014a and earlier)
% 25/02/15: Fix issue #21 (bold TeX axes labels/titles in R2014b)
% 26/02/15: If temp dir is not writable, use the user-specified folder for temporary EPS/PDF files (Javier Paredes)
% 27/02/15: Modified repository URL from github.com/ojwoodford to /altmany
% Indented main function
% Added top-level try-catch block to display useful workarounds
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 06/03/15: Improved image padding & cropping thanks to Oscar Hartogensis
% 26/03/15: Fixed issue #49 (bug with transparent grayscale images); fixed out-of-memory issue
% 26/03/15: Fixed issue #42: non-normalized annotations on HG1
% 26/03/15: Fixed issue #46: Ghostscript crash if figure units <> pixels
% 27/03/15: Fixed issue #39: bad export of transparent annotations/patches
% 28/03/15: Fixed issue #50: error on some Matlab versions with the fix for issue #42
% 29/03/15: Fixed issue #33: bugs in Matlab's print() function with -cmyk
% 29/03/15: Improved processing of input args (accept space between param name & value, related to issue #51)
% 30/03/15: When exporting *.fig files, then saveas *.fig if figure is open, otherwise export the specified fig file
% 30/03/15: Fixed edge case bug introduced yesterday (commit #ae1755bd2e11dc4e99b95a7681f6e211b3fa9358)
% 09/04/15: Consolidated header comment sections; initialize output vars only if requested (nargout>0)
% 14/04/15: Workaround for issue #45: lines in image subplots are exported in invalid color
% 15/04/15: Fixed edge-case in parsing input parameters; fixed help section to show the -depsc option (issue #45)
% 21/04/15: Bug fix: Ghostscript croaks on % chars in output PDF file (reported by Sven on FEX page, 15-Jul-2014)
% 22/04/15: Bug fix: Pdftops croaks on relative paths (reported by Tintin Milou on FEX page, 19-Jan-2015)
% 04/05/15: Merged fix #63 (Kevin Mattheus Moerman): prevent tick-label changes during export
% 07/05/15: Partial fix for issue #65: PDF export used painters rather than opengl renderer (thanks Nguyenr)
% 08/05/15: Fixed issue #65: bad PDF append since commit #e9f3cdf 21/04/15 (thanks Robert Nguyen)
% 12/05/15: Fixed issue #67: exponent labels cropped in export, since fix #63 (04/05/15)
% 28/05/15: Fixed issue #69: set non-bold label font only if the string contains symbols (\beta etc.), followup to issue #21
% 29/05/15: Added informative error message in case user requested SVG output (issue #72)
% 09/06/15: Fixed issue #58: -transparent removed anti-aliasing when exporting to PNG
% 19/06/15: Added -update option to download and install the latest version of export_fig
% 07/07/15: Added -nofontswap option to avoid font-swapping in EPS/PDF
% 16/07/15: Fixed problem with anti-aliasing on old Matlab releases
% 11/09/15: Fixed issue #103: magnification must never become negative; also fixed reported error msg in parsing input params
% 26/09/15: Alert if trying to export transparent patches/areas to non-PNG outputs (issue #108)
% 04/10/15: Do not suggest workarounds for certain errors that have already been handled previously
% 01/11/15: Fixed issue #112: use same renderer in print2eps as export_fig (thanks to Jesús Pestana Puerta)
% 10/11/15: Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
% 19/11/15: Fixed clipboard export in R2015b (thanks to Dan K via FEX)
% 21/02/16: Added -c option for indicating specific crop amounts (idea by Cedric Noordam on FEX)
% 08/05/16: Added message about possible error reason when groot.Units~=pixels (issue #149)
% 17/05/16: Fixed case of image YData containing more than 2 elements (issue #151)
% 08/08/16: Enabled exporting transparency to TIF, in addition to PNG/PDF (issue #168)
% 11/12/16: Added alert in case of error creating output PDF/EPS file (issue #179)
% 13/12/16: Minor fix to the commit for issue #179 from 2 days ago
% 22/03/17: Fixed issue #187: only set manual ticks when no exponent is present
% 09/04/17: Added -linecaps option (idea by Baron Finer, issue #192)
% 15/09/17: Fixed issue #205: incorrect tick-labels when Ticks number don't match the TickLabels number
% 15/09/17: Fixed issue #210: initialize alpha map to ones instead of zeros when -transparent is not used
% 18/09/17: Added -font_space option to replace font-name spaces in EPS/PDF (workaround for issue #194)
% 18/09/17: Added -noinvert option to solve some export problems with some graphic cards (workaround for issue #197)
% 08/11/17: Fixed issue #220: exponent is removed in HG1 when TickMode is 'manual' (internal Matlab bug)
% 08/11/17: Fixed issue #221: alert if the requested folder does not exist
%}
if nargout
[imageData, alpha] = deal([]);
end
hadError = false;
displaySuggestedWorkarounds = true;
% Ensure the figure is rendered correctly _now_ so that properties like axes limits are up-to-date
drawnow;
pause(0.05); % this solves timing issues with Java Swing's EDT (http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem)
% Parse the input arguments
fig = get(0, 'CurrentFigure');
[fig, options] = parse_args(nargout, fig, varargin{:});
% Ensure that we have a figure handle
if isequal(fig,-1)
return; % silent bail-out
elseif isempty(fig)
error('No figure found');
end
% Isolate the subplot, if it is one
cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'}));
if cls
% Given handles of one or more axes, so isolate them from the rest
fig = isolate_axes(fig);
else
% Check we have a figure
if ~isequal(get(fig, 'Type'), 'figure')
error('Handle must be that of a figure, axes or uipanel');
end
% Get the old InvertHardcopy mode
old_mode = get(fig, 'InvertHardcopy');
end
% Hack the font units where necessary (due to a font rendering bug in print?).
% This may not work perfectly in all cases.
% Also it can change the figure layout if reverted, so use a copy.
magnify = options.magnify * options.aa_factor;
if isbitmap(options) && magnify ~= 1
fontu = findall(fig, 'FontUnits', 'normalized');
if ~isempty(fontu)
% Some normalized font units found
if ~cls
fig = copyfig(fig);
set(fig, 'Visible', 'off');
fontu = findall(fig, 'FontUnits', 'normalized');
cls = true;
end
set(fontu, 'FontUnits', 'points');
end
end
try
% MATLAB "feature": axes limits and tick marks can change when printing
Hlims = findall(fig, 'Type', 'axes');
if ~cls
% Record the old axes limit and tick modes
Xlims = make_cell(get(Hlims, 'XLimMode'));
Ylims = make_cell(get(Hlims, 'YLimMode'));
Zlims = make_cell(get(Hlims, 'ZLimMode'));
Xtick = make_cell(get(Hlims, 'XTickMode'));
Ytick = make_cell(get(Hlims, 'YTickMode'));
Ztick = make_cell(get(Hlims, 'ZTickMode'));
Xlabel = make_cell(get(Hlims, 'XTickLabelMode'));
Ylabel = make_cell(get(Hlims, 'YTickLabelMode'));
Zlabel = make_cell(get(Hlims, 'ZTickLabelMode'));
end
% Set all axes limit and tick modes to manual, so the limits and ticks can't change
% Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual'
set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual');
set_tick_mode(Hlims, 'X');
set_tick_mode(Hlims, 'Y');
if ~using_hg2(fig)
set(Hlims,'ZLimMode', 'manual');
set_tick_mode(Hlims, 'Z');
end
catch
% ignore - fix issue #4 (using HG2 on R2014a and earlier)
end
% Fix issue #21 (bold TeX axes labels/titles in R2014b when exporting to EPS/PDF)
try
if using_hg2(fig) && isvector(options)
% Set the FontWeight of axes labels/titles to 'normal'
% Fix issue #69: set non-bold font only if the string contains symbols (\beta etc.)
texLabels = findall(fig, 'type','text', 'FontWeight','bold');
symbolIdx = ~cellfun('isempty',strfind({texLabels.String},'\'));
set(texLabels(symbolIdx), 'FontWeight','normal');
end
catch
% ignore
end
% Fix issue #42: non-normalized annotations on HG1 (internal Matlab bug)
annotationHandles = [];
try
if ~using_hg2(fig)
annotationHandles = findall(fig,'Type','hggroup','-and','-property','Units','-and','-not','Units','norm');
try % suggested by Jesús Pestana Puerta (jespestana) 30/9/2015
originalUnits = get(annotationHandles,'Units');
set(annotationHandles,'Units','norm');
catch
end
end
catch
% should never happen, but ignore in any case - issue #50
end
% Fix issue #46: Ghostscript crash if figure units <> pixels
oldFigUnits = get(fig,'Units');
set(fig,'Units','pixels');
% Set to print exactly what is there
if options.invert_hardcopy
set(fig, 'InvertHardcopy', 'off');
end
% Set the renderer
switch options.renderer
case 1
renderer = '-opengl';
case 2
renderer = '-zbuffer';
case 3
renderer = '-painters';
otherwise
renderer = '-opengl'; % Default for bitmaps
end
% Handle transparent patches
hasTransparency = ~isempty(findall(fig,'-property','FaceAlpha','-and','-not','FaceAlpha',1));
hasPatches = ~isempty(findall(fig,'type','patch'));
if hasTransparency
% Alert if trying to export transparent patches/areas to non-supported outputs (issue #108)
% http://www.mathworks.com/matlabcentral/answers/265265-can-export_fig-or-else-draw-vector-graphics-with-transparent-surfaces
% TODO - use transparency when exporting to PDF by not passing via print2eps
msg = 'export_fig currently supports transparent patches/areas only in PNG output. ';
if options.pdf
warning('export_fig:transparency', '%s\nTo export transparent patches/areas to PDF, use the print command:\n print(gcf, ''-dpdf'', ''%s.pdf'');', msg, options.name);
elseif ~options.png && ~options.tif % issue #168
warning('export_fig:transparency', '%s\nTo export the transparency correctly, try using the ScreenCapture utility on the Matlab File Exchange: http://bit.ly/1QFrBip', msg);
end
end
try
% Do the bitmap formats first
if isbitmap(options)
if abs(options.bb_padding) > 1
displaySuggestedWorkarounds = false;
error('For bitmap output (png,jpg,tif,bmp) the padding value (-p) must be between -1<p<1')
end
% Get the background colour
if options.transparent && (options.png || options.alpha)
% Get out an alpha channel
% MATLAB "feature": black colorbar axes can change to white and vice versa!
hCB = findall(fig, 'Type','axes', 'Tag','Colorbar');
if isempty(hCB)
yCol = [];
xCol = [];
else
yCol = get(hCB, 'YColor');
xCol = get(hCB, 'XColor');
if iscell(yCol)
yCol = cell2mat(yCol);
xCol = cell2mat(xCol);
end
yCol = sum(yCol, 2);
xCol = sum(xCol, 2);
end
% MATLAB "feature": apparently figure size can change when changing
% colour in -nodisplay mode
pos = get(fig, 'Position');
% Set the background colour to black, and set size in case it was
% changed internally
tcol = get(fig, 'Color');
set(fig, 'Color', 'k', 'Position', pos);
% Correct the colorbar axes colours
set(hCB(yCol==0), 'YColor', [0 0 0]);
set(hCB(xCol==0), 'XColor', [0 0 0]);
% The following code might cause out-of-memory errors
try
% Print large version to array
B = print2array(fig, magnify, renderer);
% Downscale the image
B = downsize(single(B), options.aa_factor);
catch
% This is more conservative in memory, but kills transparency (issue #58)
B = single(print2array(fig, magnify/options.aa_factor, renderer));
end
% Set background to white (and set size)
set(fig, 'Color', 'w', 'Position', pos);
% Correct the colorbar axes colours
set(hCB(yCol==3), 'YColor', [1 1 1]);
set(hCB(xCol==3), 'XColor', [1 1 1]);
% The following code might cause out-of-memory errors
try
% Print large version to array
A = print2array(fig, magnify, renderer);
% Downscale the image
A = downsize(single(A), options.aa_factor);
catch
% This is more conservative in memory, but kills transparency (issue #58)
A = single(print2array(fig, magnify/options.aa_factor, renderer));
end
% Set the background colour (and size) back to normal
set(fig, 'Color', tcol, 'Position', pos);
% Compute the alpha map
alpha = round(sum(B - A, 3)) / (255 * 3) + 1;
A = alpha;
A(A==0) = 1;
A = B ./ A(:,:,[1 1 1]);
clear B
% Convert to greyscale
if options.colourspace == 2
A = rgb2grey(A);
end
A = uint8(A);
% Crop the background
if options.crop
%[alpha, v] = crop_borders(alpha, 0, 1, options.crop_amounts);
%A = A(v(1):v(2),v(3):v(4),:);
[alpha, vA, vB] = crop_borders(alpha, 0, options.bb_padding, options.crop_amounts);
if ~any(isnan(vB)) % positive padding
B = repmat(uint8(zeros(1,1,size(A,3))),size(alpha));
B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :); % ADDED BY OH
A = B;
else % negative padding
A = A(vA(1):vA(2), vA(3):vA(4), :);
end
end
if options.png
% Compute the resolution
res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
% Save the png
imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
% Clear the png bit
options.png = false;
end
% Return only one channel for greyscale
if isbitmap(options)
A = check_greyscale(A);
end
if options.alpha
% Store the image
imageData = A;
% Clear the alpha bit
options.alpha = false;
end
% Get the non-alpha image
if isbitmap(options)
alph = alpha(:,:,ones(1, size(A, 3)));
A = uint8(single(A) .* alph + 255 * (1 - alph));
clear alph
end
if options.im
% Store the new image
imageData = A;
end
else
% Print large version to array
if options.transparent
% MATLAB "feature": apparently figure size can change when changing
% colour in -nodisplay mode
pos = get(fig, 'Position');
tcol = get(fig, 'Color');
set(fig, 'Color', 'w', 'Position', pos);
A = print2array(fig, magnify, renderer);
set(fig, 'Color', tcol, 'Position', pos);
tcol = 255;
else
[A, tcol] = print2array(fig, magnify, renderer);
end
% Crop the background
if options.crop
A = crop_borders(A, tcol, options.bb_padding, options.crop_amounts);
end
% Downscale the image
A = downsize(A, options.aa_factor);
if options.colourspace == 2
% Convert to greyscale
A = rgb2grey(A);
else
% Return only one channel for greyscale
A = check_greyscale(A);
end
% Outputs
if options.im
imageData = A;
end
if options.alpha
imageData = A;
alpha = ones(size(A, 1), size(A, 2), 'single');
end
end
% Save the images
if options.png
res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3;
imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res);
end
if options.bmp
imwrite(A, [options.name '.bmp']);
end
% Save jpeg with given quality
if options.jpg
quality = options.quality;
if isempty(quality)
quality = 95;
end
if quality > 100
imwrite(A, [options.name '.jpg'], 'Mode', 'lossless');
else
imwrite(A, [options.name '.jpg'], 'Quality', quality);
end
end
% Save tif images in cmyk if wanted (and possible)
if options.tif
if options.colourspace == 1 && size(A, 3) == 3
A = double(255 - A);
K = min(A, [], 3);
K_ = 255 ./ max(255 - K, 1);
C = (A(:,:,1) - K) .* K_;
M = (A(:,:,2) - K) .* K_;
Y = (A(:,:,3) - K) .* K_;
A = uint8(cat(3, C, M, Y, K));
clear C M Y K K_
end
append_mode = {'overwrite', 'append'};
imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1});
end
end
% Now do the vector formats
if isvector(options)
% Set the default renderer to painters
if ~options.renderer
if hasTransparency || hasPatches
% This is *MUCH* slower, but more accurate for patches and transparent annotations (issue #39)
renderer = '-opengl';
else
renderer = '-painters';
end
end
options.rendererStr = renderer; % fix for issue #112
% Generate some filenames
tmp_nam = [tempname '.eps'];
try
% Ensure that the temp dir is writable (Javier Paredes 30/1/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam);
isTempDirOk = true;
catch
% Temp dir is not writable, so use the user-specified folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = fileparts(options.name);
tmp_nam = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
if isTempDirOk
pdf_nam_tmp = [tempname '.pdf'];
else
pdf_nam_tmp = fullfile(fpath,[fname '.pdf']);
end
if options.pdf
pdf_nam = [options.name '.pdf'];
try copyfile(pdf_nam, pdf_nam_tmp, 'f'); catch, end % fix for issue #65
else
pdf_nam = pdf_nam_tmp;
end
% Generate the options for print
p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
if options.colourspace == 1 % CMYK
% Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option
%p2eArgs{end+1} = '-cmyk';
end
if ~options.crop
% Issue #56: due to internal bugs in Matlab's print() function, we can't use its internal cropping mechanism,
% therefore we always use '-loose' (in print2eps.m) and do our own cropping (in crop_borders)
%p2eArgs{end+1} = '-loose';
end
if any(strcmpi(varargin,'-depsc'))
% Issue #45: lines in image subplots are exported in invalid color.
% The workaround is to use the -depsc parameter instead of the default -depsc2
p2eArgs{end+1} = '-depsc';
end
try
% Generate an eps
print2eps(tmp_nam, fig, options, p2eArgs{:});
% Remove the background, if desired
if options.transparent && ~isequal(get(fig, 'Color'), 'none')
eps_remove_background(tmp_nam, 1 + using_hg2(fig));
end
% Fix colorspace to CMYK, if requested (workaround for issue #33)
if options.colourspace == 1 % CMYK
% Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option
change_rgb_to_cmyk(tmp_nam);
end
% Add a bookmark to the PDF if desired
if options.bookmark
fig_nam = get(fig, 'Name');
if isempty(fig_nam)
warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.');
end
add_bookmark(tmp_nam, fig_nam);
end
% Generate a pdf
eps2pdf(tmp_nam, pdf_nam_tmp, 1, options.append, options.colourspace==2, options.quality, options.gs_options);
% Ghostscript croaks on % chars in the output PDF file, so use tempname and then rename the file
try
% Rename the file (except if it is already the same)
% Abbie K's comment on the commit for issue #179 (#commitcomment-20173476)
if ~isequal(pdf_nam_tmp, pdf_nam)
movefile(pdf_nam_tmp, pdf_nam, 'f');
end
catch
% Alert in case of error creating output PDF/EPS file (issue #179)
if exist(pdf_nam_tmp, 'file')
error(['Could not create ' pdf_nam ' - perhaps the folder does not exist, or you do not have write permissions']);
else
error('Could not generate the intermediary EPS file.');
end
end
catch ex
% Delete the eps
delete(tmp_nam);
rethrow(ex);
end
% Delete the eps
delete(tmp_nam);
if options.eps || options.linecaps
try
% Generate an eps from the pdf
% since pdftops can't handle relative paths (e.g., '..\'), use a temp file
eps_nam_tmp = strrep(pdf_nam_tmp,'.pdf','.eps');
pdf2eps(pdf_nam, eps_nam_tmp);
% Issue #192: enable rounded line-caps
if options.linecaps
fstrm = read_write_entire_textfile(eps_nam_tmp);
fstrm = regexprep(fstrm, '[02] J', '1 J');
read_write_entire_textfile(eps_nam_tmp, fstrm);
if options.pdf
eps2pdf(eps_nam_tmp, pdf_nam, 1, options.append, options.colourspace==2, options.quality, options.gs_options);
end
end
if options.eps
movefile(eps_nam_tmp, [options.name '.eps'], 'f');
else % if options.pdf
try delete(eps_nam_tmp); catch, end
end
catch ex
if ~options.pdf
% Delete the pdf
delete(pdf_nam);
end
try delete(eps_nam_tmp); catch, end
rethrow(ex);
end
if ~options.pdf
% Delete the pdf
delete(pdf_nam);
end
end
end
% Revert the figure or close it (if requested)
if cls || options.closeFig
% Close the created figure
close(fig);
else
% Reset the hardcopy mode
set(fig, 'InvertHardcopy', old_mode);
% Reset the axes limit and tick modes
for a = 1:numel(Hlims)
try
set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a},...
'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a},...
'XTickLabelMode', Xlabel{a}, 'YTickLabelMode', Ylabel{a}, 'ZTickLabelMode', Zlabel{a});
catch
% ignore - fix issue #4 (using HG2 on R2014a and earlier)
end
end
% Revert the tex-labels font weights
try set(texLabels, 'FontWeight','bold'); catch, end
% Revert annotation units
for handleIdx = 1 : numel(annotationHandles)
try
oldUnits = originalUnits{handleIdx};
catch
oldUnits = originalUnits;
end
try set(annotationHandles(handleIdx),'Units',oldUnits); catch, end
end
% Revert figure units
set(fig,'Units',oldFigUnits);
end
% Output to clipboard (if requested)
if options.clipboard
% Delete the output file if unchanged from the default name ('export_fig_out.png')
if strcmpi(options.name,'export_fig_out')
try
fileInfo = dir('export_fig_out.png');
if ~isempty(fileInfo)
timediff = now - fileInfo.datenum;
ONE_SEC = 1/24/60/60;
if timediff < ONE_SEC
delete('export_fig_out.png');
end
end
catch
% never mind...
end
end
% Save the image in the system clipboard
% credit: Jiro Doke's IMCLIPBOARD: http://www.mathworks.com/matlabcentral/fileexchange/28708-imclipboard
try
error(javachk('awt', 'export_fig -clipboard output'));
catch
warning('export_fig -clipboard output failed: requires Java to work');
return;
end
try
% Import necessary Java classes
import java.awt.Toolkit
import java.awt.image.BufferedImage
import java.awt.datatransfer.DataFlavor
% Get System Clipboard object (java.awt.Toolkit)
cb = Toolkit.getDefaultToolkit.getSystemClipboard();
% Add java class (ImageSelection) to the path
if ~exist('ImageSelection', 'class')
javaaddpath(fileparts(which(mfilename)), '-end');
end
% Get image size
ht = size(imageData, 1);
wd = size(imageData, 2);
% Convert to Blue-Green-Red format
try
imageData2 = imageData(:, :, [3 2 1]);
catch
% Probably gray-scaled image (2D, without the 3rd [RGB] dimension)
imageData2 = imageData(:, :, [1 1 1]);
end
% Convert to 3xWxH format
imageData2 = permute(imageData2, [3, 2, 1]);
% Append Alpha data (unused - transparency is not supported in clipboard copy)
alphaData2 = uint8(permute(255*alpha,[3,2,1])); %=255*ones(1,wd,ht,'uint8')
imageData2 = cat(1, imageData2, alphaData2);
% Create image buffer
imBuffer = BufferedImage(wd, ht, BufferedImage.TYPE_INT_RGB);
imBuffer.setRGB(0, 0, wd, ht, typecast(imageData2(:), 'int32'), 0, wd);
% Create ImageSelection object from the image buffer
imSelection = ImageSelection(imBuffer);
% Set clipboard content to the image
cb.setContents(imSelection, []);
catch
warning('export_fig -clipboard output failed: %s', lasterr); %#ok<LERR>
end
end
% Don't output the data to console unless requested
if ~nargout
clear imageData alpha
end
catch err
% Display possible workarounds before the error message
if displaySuggestedWorkarounds && ~strcmpi(err.message,'export_fig error')
if ~hadError, fprintf(2, 'export_fig error. '); end
fprintf(2, 'Please ensure:\n');
fprintf(2, ' that you are using the <a href="https://github.com/altmany/export_fig/archive/master.zip">latest version</a> of export_fig\n');
if ismac
fprintf(2, ' and that you have <a href="http://pages.uoregon.edu/koch">Ghostscript</a> installed\n');
else
fprintf(2, ' and that you have <a href="http://www.ghostscript.com">Ghostscript</a> installed\n');
end
try
if options.eps
fprintf(2, ' and that you have <a href="http://www.foolabs.com/xpdf">pdftops</a> installed\n');
end
catch
% ignore - probably an error in parse_args
end
fprintf(2, ' and that you do not have <a href="matlab:which export_fig -all">multiple versions</a> of export_fig installed by mistake\n');
fprintf(2, ' and that you did not made a mistake in the <a href="matlab:help export_fig">expected input arguments</a>\n');
try
% Alert per issue #149
if ~strncmpi(get(0,'Units'),'pixel',5)
fprintf(2, ' or try to set groot''s Units property back to its default value of ''pixels'' (<a href="matlab:web(''https://github.com/altmany/export_fig/issues/149'',''-browser'');">details</a>)\n');
end
catch
% ignore - maybe an old MAtlab release
end
fprintf(2, '\nIf the problem persists, then please <a href="https://github.com/altmany/export_fig/issues">report a new issue</a>.\n\n');
end
rethrow(err)
end
end
function options = default_options()
% Default options used by export_fig
options = struct(...
'name', 'export_fig_out', ...
'crop', true, ...
'crop_amounts', nan(1,4), ... % auto-crop all 4 image sides
'transparent', false, ...
'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters
'pdf', false, ...
'eps', false, ...
'png', false, ...
'tif', false, ...
'jpg', false, ...
'bmp', false, ...
'clipboard', false, ...
'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray
'append', false, ...
'im', false, ...
'alpha', false, ...
'aa_factor', 0, ...
'bb_padding', 0, ...
'magnify', [], ...
'resolution', [], ...
'bookmark', false, ...
'closeFig', false, ...
'quality', [], ...
'update', false, ...
'fontswap', true, ...
'font_space', '', ...
'linecaps', false, ...
'invert_hardcopy', true, ...
'gs_options', {{}});
end
function [fig, options] = parse_args(nout, fig, varargin)
% Parse the input arguments
% Set the defaults
native = false; % Set resolution to native of an image
options = default_options();
options.im = (nout == 1); % user requested imageData output
options.alpha = (nout == 2); % user requested alpha output
% Go through the other arguments
skipNext = false;
for a = 1:nargin-2
if skipNext
skipNext = false;
continue;
end
if all(ishandle(varargin{a}))
fig = varargin{a};
elseif ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
switch lower(varargin{a}(2:end))
case 'nocrop'
options.crop = false;
options.crop_amounts = [0,0,0,0];
case {'trans', 'transparent'}
options.transparent = true;
case 'opengl'
options.renderer = 1;
case 'zbuffer'
options.renderer = 2;
case 'painters'
options.renderer = 3;
case 'pdf'
options.pdf = true;
case 'eps'
options.eps = true;
case 'png'
options.png = true;
case {'tif', 'tiff'}
options.tif = true;
case {'jpg', 'jpeg'}
options.jpg = true;
case 'bmp'
options.bmp = true;
case 'rgb'
options.colourspace = 0;
case 'cmyk'
options.colourspace = 1;
case {'gray', 'grey'}
options.colourspace = 2;
case {'a1', 'a2', 'a3', 'a4'}
options.aa_factor = str2double(varargin{a}(3));
case 'append'
options.append = true;
case 'bookmark'
options.bookmark = true;
case 'native'
native = true;
case 'clipboard'
options.clipboard = true;
options.im = true;
options.alpha = true;
case 'svg'
msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\n' ...
' 1. saveas(gcf,''filename.svg'')\n' ...
' 2. plot2svg utility: http://github.com/jschwizer99/plot2svg\n' ...
' 3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\n'];
error(sprintf(msg)); %#ok<SPERR>
case 'update'
% Download the latest version of export_fig into the export_fig folder
try
zipFileName = 'https://github.com/altmany/export_fig/archive/master.zip';
folderName = fileparts(which(mfilename('fullpath')));
targetFileName = fullfile(folderName, datestr(now,'yyyy-mm-dd.zip'));
urlwrite(zipFileName,targetFileName);
catch
error('Could not download %s into %s\n',zipFileName,targetFileName);
end
% Unzip the downloaded zip file in the export_fig folder
try
unzip(targetFileName,folderName);
catch
error('Could not unzip %s\n',targetFileName);
end
case 'nofontswap'
options.fontswap = false;
case 'font_space'
options.font_space = varargin{a+1};
skipNext = true;
case 'linecaps'
options.linecaps = true;
case 'noinvert'
options.invert_hardcopy = false;
otherwise
try
wasError = false;
if strcmpi(varargin{a}(1:2),'-d')
varargin{a}(2) = 'd'; % ensure lowercase 'd'
options.gs_options{end+1} = varargin{a};
elseif strcmpi(varargin{a}(1:2),'-c')
if numel(varargin{a})==2
skipNext = true;
vals = str2num(varargin{a+1}); %#ok<ST2NM>
else
vals = str2num(varargin{a}(3:end)); %#ok<ST2NM>
end
if numel(vals)~=4
wasError = true;
error('option -c cannot be parsed: must be a 4-element numeric vector');
end
options.crop_amounts = vals;
options.crop = true;
else % scalar parameter value
val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match'));
if isempty(val) || isnan(val)
% Issue #51: improved processing of input args (accept space between param name & value)
val = str2double(varargin{a+1});
if isscalar(val) && ~isnan(val)
skipNext = true;
end
end
if ~isscalar(val) || isnan(val)
wasError = true;
error('option %s is not recognised or cannot be parsed', varargin{a});
end
switch lower(varargin{a}(2))
case 'm'
% Magnification may never be negative
if val <= 0
wasError = true;
error('Bad magnification value: %g (must be positive)', val);
end
options.magnify = val;
case 'r'
options.resolution = val;
case 'q'
options.quality = max(val, 0);
case 'p'
options.bb_padding = val;
end
end
catch err
% We might have reached here by raising an intentional error
if wasError % intentional raise
rethrow(err)
else % unintentional
error(['Unrecognized export_fig input option: ''' varargin{a} '''']);
end
end
end
else
[p, options.name, ext] = fileparts(varargin{a});
if ~isempty(p)
% Issue #221: alert if the requested folder does not exist
if ~exist(p,'dir'), error(['Folder ' p ' does not exist!']); end
options.name = [p filesep options.name];
end
switch lower(ext)
case {'.tif', '.tiff'}
options.tif = true;
case {'.jpg', '.jpeg'}
options.jpg = true;
case '.png'
options.png = true;
case '.bmp'
options.bmp = true;
case '.eps'
options.eps = true;
case '.pdf'
options.pdf = true;
case '.fig'
% If no open figure, then load the specified .fig file and continue
if isempty(fig)
fig = openfig(varargin{a},'invisible');
varargin{a} = fig;
options.closeFig = true;
else
% save the current figure as the specified .fig file and exit
saveas(fig(1),varargin{a});
fig = -1;
return
end
case '.svg'
msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\n' ...
' 1. saveas(gcf,''filename.svg'')\n' ...
' 2. plot2svg utility: http://github.com/jschwizer99/plot2svg\n' ...
' 3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\n'];
error(sprintf(msg)); %#ok<SPERR>
otherwise
options.name = varargin{a};
end
end
end
end
% Quick bail-out if no figure found
if isempty(fig), return; end
% Do border padding with repsect to a cropped image
if options.bb_padding
options.crop = true;
end
% Set default anti-aliasing now we know the renderer
if options.aa_factor == 0
try isAA = strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on'); catch, isAA = false; end
options.aa_factor = 1 + 2 * (~(using_hg2(fig) && isAA) | (options.renderer == 3));
end
% Convert user dir '~' to full path
if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\')
options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end));
end
% Compute the magnification and resolution
if isempty(options.magnify)
if isempty(options.resolution)
options.magnify = 1;
options.resolution = 864;
else
options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch');
end
elseif isempty(options.resolution)
options.resolution = 864;
end
% Set the default format
if ~isvector(options) && ~isbitmap(options)
options.png = true;
end
% Check whether transparent background is wanted (old way)
if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')
options.transparent = true;
end
% If requested, set the resolution to the native vertical resolution of the
% first suitable image found
if native && isbitmap(options)
% Find a suitable image
list = findall(fig, 'Type','image', 'Tag','export_fig_native');
if isempty(list)
list = findall(fig, 'Type','image', 'Visible','on');
end
for hIm = list(:)'
% Check height is >= 2
height = size(get(hIm, 'CData'), 1);
if height < 2
continue
end
% Account for the image filling only part of the axes, or vice versa
yl = get(hIm, 'YData');
if isscalar(yl)
yl = [yl(1)-0.5 yl(1)+height+0.5];
else
yl = [min(yl), max(yl)]; % fix issue #151 (case of yl containing more than 2 elements)
if ~diff(yl)
continue
end
yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1));
end
hAx = get(hIm, 'Parent');
yl2 = get(hAx, 'YLim');
% Find the pixel height of the axes
oldUnits = get(hAx, 'Units');
set(hAx, 'Units', 'pixels');
pos = get(hAx, 'Position');
set(hAx, 'Units', oldUnits);
if ~pos(4)
continue
end
% Found a suitable image
% Account for stretch-to-fill being disabled
pbar = get(hAx, 'PlotBoxAspectRatio');
pos = min(pos(4), pbar(2)*pos(3)/pbar(1));
% Set the magnification to give native resolution
options.magnify = abs((height * diff(yl2)) / (pos * diff(yl))); % magnification must never be negative: issue #103
break
end
end
end
function A = downsize(A, factor)
% Downsample an image
if factor == 1
% Nothing to do
return
end
try
% Faster, but requires image processing toolbox
A = imresize(A, 1/factor, 'bilinear');
catch
% No image processing toolbox - resize manually
% Lowpass filter - use Gaussian as is separable, so faster
% Compute the 1d Gaussian filter
filt = (-factor-1:factor+1) / (factor * 0.6);
filt = exp(-filt .* filt);
% Normalize the filter
filt = single(filt / sum(filt));
% Filter the image
padding = floor(numel(filt) / 2);
for a = 1:size(A, 3)
A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid');
end
% Subsample
A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
end
end
function A = rgb2grey(A)
A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); % #ok<ZEROLIKE>
end
function A = check_greyscale(A)
% Check if the image is greyscale
if size(A, 3) == 3 && ...
all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ...
all(reshape(A(:,:,2) == A(:,:,3), [], 1))
A = A(:,:,1); % Save only one channel for 8-bit output
end
end
function eps_remove_background(fname, count)
% Remove the background of an eps file
% Open the file
fh = fopen(fname, 'r+');
if fh == -1
error('Not able to open file %s.', fname);
end
% Read the file line by line
while count
% Get the next line
l = fgets(fh);
if isequal(l, -1)
break; % Quit, no rectangle found
end
% Check if the line contains the background rectangle
if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1)
% Set the line to whitespace and quit
l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' ';
fseek(fh, -numel(l), 0);
fprintf(fh, l);
% Reduce the count
count = count - 1;
end
end
% Close the file
fclose(fh);
end
function b = isvector(options)
b = options.pdf || options.eps;
end
function b = isbitmap(options)
b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
end
% Helper function
function A = make_cell(A)
if ~iscell(A)
A = {A};
end
end
function add_bookmark(fname, bookmark_text)
% Adds a bookmark to the temporary EPS file after %%EndPageSetup
% Read in the file
fh = fopen(fname, 'r');
if fh == -1
error('File %s not found.', fname);
end
try
fstrm = fread(fh, '*char')';
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
% Include standard pdfmark prolog to maximize compatibility
fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse'));
% Add page bookmark
fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text));
% Write out the updated file
fh = fopen(fname, 'w');
if fh == -1
error('Unable to open %s for writing.', fname);
end
try
fwrite(fh, fstrm, 'char*1');
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
function set_tick_mode(Hlims, ax)
% Set the tick mode of linear axes to manual
% Leave log axes alone as these are tricky
M = get(Hlims, [ax 'Scale']);
if ~iscell(M)
M = {M};
end
%idx = cellfun(@(c) strcmp(c, 'linear'), M);
idx = find(strcmp(M,'linear'));
%set(Hlims(idx), [ax 'TickMode'], 'manual'); % issue #187
%set(Hlims(idx), [ax 'TickLabelMode'], 'manual'); % this hides exponent label in HG2!
for idx2 = 1 : numel(idx)
try
% Fix for issue #187 - only set manual ticks when no exponent is present
hAxes = Hlims(idx(idx2));
props = {[ax 'TickMode'],'manual', [ax 'TickLabelMode'],'manual'};
tickVals = get(hAxes,[ax 'Tick']);
tickStrs = get(hAxes,[ax 'TickLabel']);
if isempty(strtrim(hAxes.([ax 'Ruler']).SecondaryLabel.String))
% Fix for issue #205 - only set manual ticks when the Ticks number match the TickLabels number
if numel(tickVals) == numel(tickStrs)
set(hAxes, props{:}); % no exponent and matching ticks, so update both ticks and tick labels to manual
end
end
catch % probably HG1
% Fix for issue #220 - exponent is removed in HG1 when TickMode is 'manual' (internal Matlab bug)
if isequal(tickVals, str2num(tickStrs)') %#ok<ST2NM>
set(hAxes, props{:}); % revert back to old behavior
end
end
end
end
function change_rgb_to_cmyk(fname) % convert RGB => CMYK within an EPS file
% Do post-processing on the eps file
try
% Read the EPS file into memory
fstrm = read_write_entire_textfile(fname);
% Replace all gray-scale colors
fstrm = regexprep(fstrm, '\n([\d.]+) +GC\n', '\n0 0 0 ${num2str(1-str2num($1))} CC\n');
% Replace all RGB colors
fstrm = regexprep(fstrm, '\n[0.]+ +[0.]+ +[0.]+ +RC\n', '\n0 0 0 1 CC\n'); % pure black
fstrm = regexprep(fstrm, '\n([\d.]+) +([\d.]+) +([\d.]+) +RC\n', '\n${sprintf(''%.4g '',[1-[str2num($1),str2num($2),str2num($3)]/max([str2num($1),str2num($2),str2num($3)]),1-max([str2num($1),str2num($2),str2num($3)])])} CC\n');
% Overwrite the file with the modified contents
read_write_entire_textfile(fname, fstrm);
catch
% never mind - leave as is...
end
end
|
github
|
BII-wushuang/FLLIT-master
|
ghostscript.m
|
.m
|
FLLIT-master/src/Export-Fig/ghostscript.m
| 7,706 |
utf_8
|
92dbafb8d4fb243cae8716c6ecb0bbe5
|
function varargout = ghostscript(cmd)
%GHOSTSCRIPT Calls a local GhostScript executable with the input command
%
% Example:
% [status result] = ghostscript(cmd)
%
% Attempts to locate a ghostscript executable, finally asking the user to
% specify the directory ghostcript was installed into. The resulting path
% is stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have Ghostscript installed on your
% system. You can download this from: http://www.ghostscript.com
%
% IN:
% cmd - Command string to be passed into ghostscript.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from ghostscript.
% Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015-
%{
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems.
% 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
% Shaun Kline for pointing out the issue
% 04/05/11 - Thanks to David Chorlian for pointing out an alternative
% location for gs on linux.
% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
% Punnoose for highlighting the issue.
% 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
% Steinbring for proposing the fix.
% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
% for the fix.
% 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen
% Vermeer for raising the issue.
% 27/02/15 - If Ghostscript croaks, display suggested workarounds
% 30/03/15 - Improved performance by caching status of GS path check, if ok
% 14/05/15 - Clarified warning message in case GS path could not be saved
% 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74)
% 10/11/15 - Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
%}
try
% Call ghostscript
[varargout{1:nargout}] = system([gs_command(gs_path()) cmd]);
catch err
% Display possible workarounds for Ghostscript croaks
url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12
url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20
hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end
fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1);
if using_hg2
fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2);
end
fprintf('\n\n');
if ismac || isunix
url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27
fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3);
% issue #20
fpath = which(mfilename);
if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end
fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath);
end
rethrow(err);
end
end
function path_ = gs_path
% Return a valid path
% Start with the currently set path
path_ = user_string('ghostscript');
% Check the path works
if check_gs_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
else
bin = {'gs'};
end
for a = 1:numel(bin)
path_ = bin{a};
if check_store_gs_path(path_)
return
end
end
% Search the obvious places
if ispc
default_location = 'C:\Program Files\gs\';
dir_list = dir(default_location);
if isempty(dir_list)
default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems
dir_list = dir(default_location);
end
executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
ver_num = 0;
% If there are multiple versions, use the newest
for a = 1:numel(dir_list)
ver_num2 = sscanf(dir_list(a).name, 'gs%g');
if ~isempty(ver_num2) && ver_num2 > ver_num
for b = 1:numel(executable)
path2 = [default_location dir_list(a).name executable{b}];
if exist(path2, 'file') == 2
path_ = path2;
ver_num = ver_num2;
end
end
end
end
if check_store_gs_path(path_)
return
end
else
executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
for a = 1:numel(executable)
path_ = executable{a};
if check_store_gs_path(path_)
return
end
end
end
% Ask the user to enter the path
while true
if strncmp(computer, 'MAC', 3) % Is a Mac
% Give separate warning as the uigetdir dialogue box doesn't have a
% title
uiwait(warndlg('Ghostscript not found. Please locate the program.'))
end
base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
for b = 1:numel(bin)
path_ = [base bin_dir{a} bin{b}];
if exist(path_, 'file') == 2
if check_store_gs_path(path_)
return
end
end
end
end
end
if ismac
error('Ghostscript not found. Have you installed it (http://pages.uoregon.edu/koch)?');
else
error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
end
end
function good = check_store_gs_path(path_)
% Check the path is valid
good = check_gs_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('ghostscript', path_)
filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt');
warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_);
return
end
end
function good = check_gs_path(path_)
persistent isOk
if isempty(path_)
isOk = false;
elseif ~isequal(isOk,true)
% Check whether the path is valid
[status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU>
isOk = status == 0;
end
good = isOk;
end
function cmd = gs_command(path_)
% Initialize any required system calls before calling ghostscript
% TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
shell_cmd = '';
if isunix
shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07
end
% Construct the command string
cmd = sprintf('%s"%s" ', shell_cmd, path_);
end
|
github
|
BII-wushuang/FLLIT-master
|
fix_lines.m
|
.m
|
FLLIT-master/src/Export-Fig/fix_lines.m
| 6,290 |
utf_8
|
8437006b104957762090e3d875688cb6
|
%FIX_LINES Improves the line style of eps files generated by print
%
% Examples:
% fix_lines fname
% fix_lines fname fname2
% fstrm_out = fixlines(fstrm_in)
%
% This function improves the style of lines in eps files generated by
% MATLAB's print function, making them more similar to those seen on
% screen. Grid lines are also changed from a dashed style to a dotted
% style, for greater differentiation from dashed lines.
%
% The function also places embedded fonts after the postscript header, in
% versions of MATLAB which place the fonts first (R2006b and earlier), in
% order to allow programs such as Ghostscript to find the bounding box
% information.
%
%IN:
% fname - Name or path of source eps file.
% fname2 - Name or path of destination eps file. Default: same as fname.
% fstrm_in - File contents of a MATLAB-generated eps file.
%
%OUT:
% fstrm_out - Contents of the eps file with line styles fixed.
% Copyright: (C) Oliver Woodford, 2008-2014
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928)
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% Thank you to Sylvain Favrot for bringing the embedded font/bounding box
% interaction in older versions of MATLAB to my attention.
% Thank you to D Ko for bringing an error with eps files with tiff previews
% to my attention.
% Thank you to Laurence K for suggesting the check to see if the file was
% opened.
% 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+)
% 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39
function fstrm = fix_lines(fstrm, fname2)
% Issue #20: warn users if using this function in HG2 (R2014b+)
if using_hg2
warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.');
end
if nargout == 0 || nargin > 1
if nargin < 2
% Overwrite the input file
fname2 = fstrm;
end
% Read in the file
fstrm = read_write_entire_textfile(fstrm);
end
% Move any embedded fonts after the postscript header
if strcmp(fstrm(1:15), '%!PS-AdobeFont-')
% Find the start and end of the header
ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
[ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
% Put the header first
if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]);
end
end
% Make sure all line width commands come before the line style definitions,
% so that dash lengths can be based on the correct widths
% Find all line style sections
ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes!
regexp(fstrm, '[\n\r]DO[\n\r]'),...
regexp(fstrm, '[\n\r]DA[\n\r]'),...
regexp(fstrm, '[\n\r]DD[\n\r]')];
ind = sort(ind);
% Find line width commands
[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
% Go through each line style section and swap with any line width commands
% near by
b = 1;
m = numel(ind);
n = numel(ind2);
for a = 1:m
% Go forwards width commands until we pass the current line style
while b <= n && ind2(b) < ind(a)
b = b + 1;
end
if b > n
% No more width commands
break;
end
% Check we haven't gone past another line style (including SO!)
if a < m && ind2(b) > ind(a+1)
continue;
end
% Are the commands close enough to be confident we can swap them?
if (ind2(b) - ind(a)) > 8
continue;
end
% Move the line style command below the line width command
fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)];
b = b + 1;
end
% Find any grid line definitions and change to GR format
% Find the DO sections again as they may have moved
ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]'));
if ~isempty(ind)
% Find all occurrences of what are believed to be axes and grid lines
ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]'));
if ~isempty(ind2)
% Now see which DO sections come just before axes and grid lines
ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]);
ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right
ind = ind(ind2);
% Change any regions we believe to be grid lines to GR
fstrm(ind+1) = 'G';
fstrm(ind+2) = 'R';
end
end
% Define the new styles, including the new GR format
% Dot and dash lengths have two parts: a constant amount plus a line width
% variable amount. The constant amount comes after dpi2point, and the
% variable amount comes after currentlinewidth. If you want to change
% dot/dash lengths for a one particular line style only, edit the numbers
% in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and
% /GR (grid lines) lines for the style you want to change.
new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width
'/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width
'/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines
'/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines
'/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines
'/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines
'/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
% Construct the output
% This is the original (memory-intensive) code:
%first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section
%[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
%[remaining, remaining] = strtok(remaining, '%');
%fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']);
% Write the output file
if nargout == 0 || nargin > 1
read_write_entire_textfile(fname2, fstrm);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_context_v4.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_context_v4.m
| 26,156 |
utf_8
|
517c845afa1d5078668d16631157513e
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners] = train_boost_context_v3(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
weak_learners(params.wl_no).alpha = 0;
weak_learners_ctx1(params.wl_no).alpha = 0;
weak_learners_ctx2(params.wl_no).alpha = 0;
debug_flag = 1;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
current_response_ctx2 = current_response;
W_ctx1 = W;
R_ctx1 = R;
W_ctx2 = W;
R_ctx2 = R;
train_scores = zeros(params.wl_no,3);
train_scores_ctx1 = zeros(params.wl_no,3);
train_scores_ctx2 = zeros(params.wl_no,3);
n_km = 30;
ftrs_prev_ctx = [];
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
%save('tmp_ftrs.mat');
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
ctx_loc_all = zeros(size(samples_idx,1),n_ftrs2);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
if(~isempty(ctx_ftrs2_w{i_w - 1,i_img}))
ctx_loc_all(samples_idx(:,1) == i_img,:) = ctx_ftrs2_w{i_w - 1,i_img};
end
ctx_ftrs1_w{i_w - 1,i_img} = [];
ctx_ftrs2_w{i_w - 1,i_img} = [];
end
for i_prev = 1 : length(ftrs_prev_ctx)
ctx_loc_all = [ctx_loc_all, ftrs_prev_ctx{i_prev}];
end
ctx_glb = ctx_glb_all(T2_idx,:);
ctx_loc = ctx_loc_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
% t_tr = tic;
% reg_tree_l = LDARegStumpTrain(single([features,ctx_loc]),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
% for i_img = 1 : size(data.train.(ch).X,1)
%
% T2_img = samples_idx(T2_idx,1) == i_img;
%
% ctx_loc_img = ctx_loc(T2_img,:);
%
% ctx_glb_img = ctx_glb(T2_img,:);
%
% fprintf(' Training regression tree %d on learned features combined with context 1 2...\n',i_img);
%
% t_tr = tic;
% reg_tree_l{i_img} = LDARegStumpTrain(single([features(T2_img,:),...
% ctx_glb_img,ctx_loc_img]),R(T2_idx(T2_img)),W(T2_idx(T2_img)) ...
% /sum(W(T2_idx((T2_img)))),...
% uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
%
% end
fprintf(' Training regression tree on learned features combined with context 1 2...\n');
t_tr = tic;
reg_tree_l = LDARegStumpTrain(single([features,...
ctx_glb,ctx_loc]),R_ctx2(T2_idx),W_ctx2(T2_idx) ...
/sum(W_ctx2(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
[weak_learners_ctx2(i_w).kernels,weak_learners_ctx2(i_w).kernel_params,weak_learners_ctx2(i_w).reg_tree,...
weak_learners_ctx2(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_l,kernels,kernel_params);
ctx2_list = weak_learners_ctx2(i_w).ctx_list;
ctx2_list(ctx2_list < ncf_g + 1) = [];
ctx2_list = ctx2_list - ncf_g;
tmp_kmc = [];
tmp_ltree = [];
for i_km = 1 : length(ctx2_list)
tmp_kmc(i_km,:) = kmc_ctx_c2(ctx2_list(i_km),:);
tmp_ltree(i_km) = tleaf_ctx_c2(ctx2_list(i_km));
end
weak_learners_ctx2(i_w).kmc = tmp_kmc;
weak_learners_ctx2(i_w).ltree = tmp_ltree;
% ctx2_list = ctx2_list - ncf_g;
weak_learners_ctx2(i_w).ctx2_list = ctx2_list;
ctx_combine = [ctx_glb_all, ctx_loc_all];
for i_ctx = 1 : length(weak_learners_ctx2(i_w).ctx_list)
ctx2_list_1 = weak_learners_ctx2(i_w).ctx_list;
ftrs_prev_ctx{end + 1} = ctx_combine(:,ctx2_list_1(i_ctx));
end
clear ctx_combine;
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
ctx_glb_all = [ctx_glb_all, ctx_loc_all];
clear ctx_loc_all;
features_ctx2 = ctx_glb_all(:,weak_learners_ctx2(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx2(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),...
weak_learners_ctx2(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx2(i_w).kernels(idxs),...
weak_learners_ctx2(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx2 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx2 = LDARegStumpPredict(...
weak_learners_ctx2(i_w).reg_tree,single([features, features_ctx2]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 features_ctx2 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
fprintf(' Finding alpha 2 through line search...\n');
t_alp = tic;
alpha_ctx2 = mexLineSearch(current_response_ctx2,cached_responses_ctx2,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx2,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
alpha_ctx2 = alpha_ctx2 * params.shrinkage_factor;
current_response_ctx2 = current_response_ctx2 + alpha_ctx2*cached_responses_ctx2;
W_ctx2 = compute_wi(current_response_ctx2);
R_ctx2 = compute_ri(current_response_ctx2);
weak_learners_ctx2(i_w).alpha = alpha_ctx2;
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum((current_response_ctx2>0)~=(labels>0))/length(labels);
fprintf(' Ctx2 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx2));
train_scores_ctx2(i_w,1) = 100*MR;
train_scores_ctx2(i_w,2) = compute_loss(current_response_ctx2);
train_scores_ctx2(i_w,3) = alpha_ctx2;
end
save('train_scores_sav_v3.mat','train_scores','train_scores_ctx1','train_scores_ctx2');
if(i_w > 0)
% collect th colour value of the sample data
samp_rgb = zeros(size(samples_idx,1),3);
for i_img = 1 : size(data.train.(ch).X,1)
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
posi_samp = sub2ind(size(I(:,:,1)),samp_idx_img(:,2),samp_idx_img(:,3));
I = reshape(I,[],3);
samp_rgb(samples_idx == i_img,:) = I(posi_samp,:);
end
wltree = weak_learners(i_w).reg_tree;
[~,samp_lf] = predict_idx_wl(data,params,samples_idx,weak_learners(i_w));
lf_hist = histc(samp_lf,1:length(wltree));
lf_hist = lf_hist(1:length(wltree));
lf_hist = lf_hist / sum(lf_hist);
[lfn,lf_id] = sort(lf_hist,'descend');
lf_id(lfn < 0.3) = [];
lfn(lfn < 0.3) = [];
% for i_lf = 1 : length(lf_id)
%
% [~,ctx_km_c{i_lf}] = kmeans(samp_rgb(samp_lf == lf_id(i_lf),:),n_km,'EmptyAction','singleton');
%
% end
%
for i_n = 1 : length(wltree)
bkg_ftrs2{i_n} = [];
%bkg_idxs{i_n} = [];
end
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
if(debug_flag)
if(mod(i_img,7) == 1)
leaf_img_prev{i_img} = leaf_image;
end
end
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
%context_img = zeros(size(leaf_image));
% cxt_idx = 1;
n_leaf = 0;
ctx_c1 = [];
ctx_c2 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
if(length(n_idx) / n_samp_img > 0.2)
I_2D = reshape(I,[],3);
n_idx = downsample(n_idx,200);
bkg_ftrs2{i_n} = [ bkg_ftrs2{i_n}; I_2D(n_idx,:)];
end
end
end
% contx_list{i_w,i_img} = ctx_c2;
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
% ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
ctx_ftrs1(ctx_ftrs1 < 0.1) = 5000;
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
weak_learners_ctx1(i_w + 1).ctx_c1 = ctx_c1;
weak_learners_ctx1(i_w + 1).ctx_c1 = ctx_c1;
n_km = 30;
ctx_c2 = [];
clear ftrs_kmc_c2;
kmc_ctx_c2 = [];
tleaf_ctx_c2 = [];
for i_n = 1 : length(wltree)
if(~isempty(bkg_ftrs2{i_n}))
tStart = tic;
[~,ftrs_kmc_tmp] = kmeans(bkg_ftrs2{i_n},n_km,'EmptyAction','singleton');
t1 = toc(tStart);
fprintf('Clustering the context ftrs 2 took %d seconds', t1);
ctx_c2(end + 1 : end + n_km) = (100 * i_n) + (1:n_km);
ftrs_kmc{i_w,i_n} = ftrs_kmc_tmp;
kmc_ctx_c2(end + 1: end + n_km,:) = ftrs_kmc_tmp;
tleaf_ctx_c2(end + 1: end + n_km,:) = i_n;
else
ftrs_kmc{i_w,i_n} = {};
end
end
weak_learners_ctx2(i_w + 1).ctx_c2 = ctx_c2;
n_ftrs2 = length(ctx_c2);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_ftrs2_w{i_w,i_img} = [];
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
ftrs2_img = zeros(size(leaf_image));
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
for i_n = 1 : length(wltree)
if(~isempty(ftrs_kmc{i_w,i_n}))
ftrs2_img_tmp = ftrs_c2_img(X,ftrs_kmc{i_w,i_n});
ftrs2_img = (i_n * 100 + ftrs2_img_tmp) .* (leaf_image == i_n);
end
end
for i_ctx = 1 : length(ctx_c2)
tStart = tic;
lf_ctx = (ftrs2_img == ctx_c2(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs2(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs2(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
ctx_ftrs2(ctx_ftrs2 < 0.1) = 5000;
ctx_ftrs2_w{i_w,i_img} = ctx_ftrs2;
% clear ctx_ftrs2;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_admm_lat_fix.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_admm_lat_fix.m
| 4,714 |
utf_8
|
eda4fdfab5dc7b3892e6ad9bd1a84b50
|
% use the mask distance as well as the main branch distance
% collect the latent label
% eavluate the effect of auto context
% includes the latent label
% discard the kernel features and adopts the new admm features
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_admm] = train_admm_lat_fix(params,data,samples_idx)
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ac = current_response;
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
X = data.train.imgs.X(:,data.train.imgs.idxs);
features_admm = collect_admm_ftrs(X,samples_idx);
features_admm1 = collect_admm_ftrs1(X,samples_idx);
features_admm = [features_admm,features_admm1];
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
i_ch = 1;
ch = 'imgs';
sub_ch_no = data.train.imgs.sub_ch_no;
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression...
(params,params.(ch),X(:,i_s),1 : sub_ch_no,samples_idx(T1_idx,1:3),R(T1_idx),W(T1_idx),i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
end
for i_s = 1 : sub_ch_no
if(isfield(params,'n_kb'))
kernels{i_ch}{i_s} = kernels{i_ch}{i_s}(1:params.n_kb);
kernel_params{i_ch}{i_s} = kernel_params{i_ch}{i_s}(1:params.n_kb);
end
end
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
[weak_learners_admm(i_w).kernels,weak_learners_admm(i_w).kernel_params,...
weak_learners_admm(i_w).reg_tree, weak_learners_admm(i_w).ctx_list]...
= train_kernel_gb_ctx(X,kernels,kernel_params,params,features_admm,...
samples_idx,W_ctx,R_ctx);
cached_responses_ctx = evaluate_weak_learners_ctx(X,params,features_admm,samples_idx,weak_learners_admm(i_w));
weak_learners_admm(i_w).alpha = search_alpha(current_response_ctx,cached_responses_ctx,labels,params);
current_response_ctx = current_response_ctx + weak_learners_admm(i_w).alpha * cached_responses_ctx;
W_ctx = compute_wi(current_response_ctx);
R_ctx = compute_ri(current_response_ctx);
train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx,labels,wgt_samp,compute_loss);
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree, weak_learners(i_w).ctx_list]...
= train_kernel_gb_ctx(X,kernels,kernel_params,params,[],...
samples_idx,W,R);
cached_responses = evaluate_weak_learners_ctx(X,params,[],samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_admm','weak_learners');
save([params.codename '_train_scores_sav.mat'],'train_scores_ctx','train_scores');
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_ctx_ac.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_ctx_ac.m
| 5,940 |
utf_8
|
b79ed0d183f4ecd4875b7cac7501df6c
|
% use the mask distance as well as the main branch distance
% eavluate the effect of auto context
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx,weak_learners_ac] = train_boost_ctx_ac(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ac = current_response;
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
% load the training images
X = data.train.imgs.X(:,data.train.imgs.idxs);
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W,R);
cached_responses = evaluate_weak_learners(X,params,samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
%%%%%% train the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
if(i_w > 1)
% in this step, apply the auto context feature learning
X_ac = X;
for i_img = 1 : size(X,1)
X_ac{i_img,size(X,2) + 1} = ac_ftrs{i_img};
end
[weak_learners_ac(i_w).kernels,weak_learners_ac(i_w).kernel_params,...
weak_learners_ac(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W_ac,R_ac);
cached_responses_ac = evaluate_weak_learners(X_ac,params,samples_idx,weak_learners_ac(i_w));
weak_learners_ac(i_w).alpha = search_alpha(current_response_ac,cached_responses_ac,labels,params);
current_response_ac = current_response_ac + weak_learners_ac(i_w).alpha * cached_responses_ac;
W_ac = compute_wi(current_response_ac);
R_ac = compute_ri(current_response_ac);
train_scores_ac(i_w,:) = weak_learner_scores(current_response_ac,labels,wgt_samp,compute_loss);
else
for i_img = 1 : size(X,1)
ac_ftrs{i_img} = zeros(size(X{i_img,1}));
end
end
%%%%%% Complete training the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
%%%%%%%%%%%% start training the ctx augmented weak learners%%%%%%%%%
if(i_w > 1)
% load the global context features
[weak_learners_ctx(i_w).kernels,weak_learners_ctx(i_w).kernel_params,...
weak_learners_ctx(i_w).reg_tree, weak_learners_ctx(i_w).ctx_list]...
= train_kernel_boost_ctx(X,params,ctx_glb_all,...
samples_idx,T1_idx,T2_idx,W_ctx,R_ctx);
cached_responses_ctx = evaluate_weak_learners_ctx(X,params,ctx_glb_all,samples_idx,weak_learners_ctx(i_w));
weak_learners_ctx(i_w).alpha = search_alpha(current_response_ctx,cached_responses_ctx,labels,params);
current_response_ctx = current_response_ctx + weak_learners_ctx(i_w).alpha * cached_responses_ctx;
W_ctx = compute_wi(current_response_ctx);
R_ctx = compute_ri(current_response_ctx);
train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx','weak_learners','weak_learners_ac');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx','train_scores_ac');
end
%%%% complete training the global context feature weak learners
% collect the global features as well as auto context features, be aware
% of the global features, they are only prepared for the next round, so
% this part should be behind the context and auto context learning
[ctx_glb_all,ac_ftrs] = collect_global_ctx(X,data.train.masks,...
params,weak_learners(i_w),samples_idx,ac_ftrs);
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_general_v2.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_general_v2.m
| 6,136 |
utf_8
|
1010bed3cb1e38df54bdffd912ad6ee4
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners] = train_boost_general_v2(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
weak_learners(params.wl_no).alpha = 0;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores = zeros(params.wl_no,3);
tmp_sav_fn = sprintf('weak_learners_%s.mat',date);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree] = remove_useless_filters(reg_tree,kernels,kernel_params);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
save(tmp_sav_fn,'train_scores','weak_learners');
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_context_HRF.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_context_HRF.m
| 29,371 |
utf_8
|
4bc94478de61653c0df23f8a47a4c38d
|
% use the mask distance as well as the main branch distance
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx1] = train_boost_context_HRF(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
% weak_learners(params.wl_no).alpha = 0;
%
% weak_learners_ctx1(params.wl_no).alpha = 0;
%
% weak_learners_ctx2(params.wl_no).alpha = 0;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
% current_response_ctx2 = current_response;
W_ctx1 = W;
R_ctx1 = R;
% W_ctx2 = W;
%
% R_ctx2 = R;
%train_scores = zeros(params.wl_no,3);
%train_scores_ctx1 = zeros(params.wl_no,3);
%train_scores_ctx2 = zeros(params.wl_no,3);
n_km = 30;
% assign the weight for each individual data point
wgt_samp = zeros(size(samples_idx,1),1);
for i_img = 1 : length(data.train.gts.X)
gt_img = data.train.gts.X{i_img};
dist_gt = bwdist(gt_img);
idx_img = (samples_idx(:,1) == i_img);
samp_idx_img_2D = samples_idx(idx_img,2:3);
samp_idx_img_1D = sub2ind(size(gt_img),samp_idx_img_2D(:,1),samp_idx_img_2D(:,2));
wgt_img = dist_gt(samp_idx_img_1D);
wgt_img(wgt_img > 7) = 7;
wgt_img = wgt_img/ 7;
wgt_img(dist_gt(samp_idx_img_1D) < 0.3) = 1;
wgt_samp(idx_img) = wgt_img;
end
W = W .* wgt_samp;
W_ctx1 = W_ctx1 .* wgt_samp;
% W_ctx2 = W_ctx2 .* wgt_samp;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
% save('tmp_ftrs.mat');
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
% ctx_loc_all = zeros(size(samples_idx,1),n_ftrs2);
% save('tmp_ftrs.mat');
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
% if(isempty(ctx_ftrs2_w{i_w - 1,i_img}))
%
% save('empty_flag_sav.mat', ctx_ftrs2_w);
%
% %ctx_loc_all(samples_idx(:,1) == i_img,:) = ones(sum(samples_idx(:,1) == i_img),n_km) * 5000;
%
% else
% ctx_loc_all(samples_idx(:,1) == i_img,:) = ctx_ftrs2_w{i_w - 1,i_img};
% end
ctx_ftrs1_w{i_w - 1,i_img} = [];
% ctx_ftrs2_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
% ctx_loc = ctx_loc_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
if(isfield(params,'ctx1_tree_depth'))
tree_d_g = params.ctx1_tree_depth;
else
tree_d_g = params.tree_depth;
end
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(tree_d_g));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
% t_tr = tic;
% reg_tree_l = LDARegStumpTrain(single([features,ctx_loc]),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
% for i_img = 1 : size(data.train.(ch).X,1)
%
% T2_img = samples_idx(T2_idx,1) == i_img;
%
% ctx_loc_img = ctx_loc(T2_img,:);
%
% ctx_glb_img = ctx_glb(T2_img,:);
%
% fprintf(' Training regression tree %d on learned features combined with context 1 2...\n',i_img);
%
% t_tr = tic;
% reg_tree_l{i_img} = LDARegStumpTrain(single([features(T2_img,:),...
% ctx_glb_img,ctx_loc_img]),R(T2_idx(T2_img)),W(T2_idx(T2_img)) ...
% /sum(W(T2_idx((T2_img)))),...
% uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
%
% end
% fprintf(' Training regression tree on learned features combined with context 1 2...\n');
%
% t_tr = tic;
%
% if(isfield(params,'ctx2_tree_depth'))
%
% tree_d_l = params.ctx2_tree_depth;
%
% else
%
% tree_d_l = params.tree_depth;
%
% end
%
% reg_tree_l = LDARegStumpTrain(single([features,...
% ctx_glb,ctx_loc]),R_ctx2(T2_idx),W_ctx2(T2_idx) ...
% /sum(W_ctx2(T2_idx)),uint32(tree_d_l));
%
% time_tr = toc(t_tr);
%
% fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
% [weak_learners_ctx2(i_w).kernels,weak_learners_ctx2(i_w).kernel_params,weak_learners_ctx2(i_w).reg_tree,...
% weak_learners_ctx2(i_w).ctx_list]...
% = remove_useless_filters_ctx(reg_tree_l,kernels,kernel_params);
%
% ctx2_list = weak_learners_ctx2(i_w).ctx_list;
%
% ctx2_list(ctx2_list < ncf_g + 1) = [];
%
% ctx2_list = ctx2_list - ncf_g;
%
% tmp_kmc = [];
%
% tmp_ltree = [];
%
% for i_km = 1 : length(ctx2_list)
%
% tmp_kmc(i_km,:) = kmc_ctx_c2(ctx2_list(i_km),:);
%
% tmp_ltree(i_km) = tleaf_ctx_c2(ctx2_list(i_km));
%
% end
%
% weak_learners_ctx2(i_w).kmc = tmp_kmc;
%
% weak_learners_ctx2(i_w).ltree = tmp_ltree;
% ctx2_list = ctx2_list - ncf_g;
% weak_learners_ctx2(i_w).ctx2_list = ctx2_list;
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx1','weak_learners');
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
% ctx_glb_all = [ctx_glb_all, ctx_loc_all];
% clear ctx_loc_all;
% features_ctx2 = ctx_glb_all(:,weak_learners_ctx2(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
%
%
% t_ev = tic;
% fprintf(' Evaluating the learned kernels on the whole training set...\n');
% features = zeros(length(labels),length(weak_learners_ctx2(i_w).kernels));
% for i_ch = 1:params.ch_no
% ch = params.ch_list{i_ch};
% sub_ch_no = data.train.(ch).sub_ch_no;
%
% X = data.train.(ch).X(:,data.train.(ch).idxs);
% for i_s = 1:sub_ch_no
% idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),...
% weak_learners_ctx2(i_w).kernel_params));
% if (~isempty(idxs))
% features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
% samples_idx(:,1:3),params.sample_size,...
% weak_learners_ctx2(i_w).kernels(idxs),...
% weak_learners_ctx2(i_w).kernel_params(idxs));
% end
% end
% end
% ev_time = toc(t_ev);
% fprintf(' Evaluation completed in %f seconds\n',ev_time);
%
% fprintf(' Performing ctx2 prediction on the whole training set...\n');
%
% t_pr = tic;
% cached_responses_ctx2 = LDARegStumpPredict(...
% weak_learners_ctx2(i_w).reg_tree,single([features, features_ctx2]));
% time_pr = toc(t_pr);
% fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
% fprintf(' Finding alpha 2 through line search...\n');
% t_alp = tic;
% alpha_ctx2 = mexLineSearch(current_response_ctx2,cached_responses_ctx2,labels,mex_loss_type);
% time_alp = toc(t_alp);
% fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx2,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
W = W .* wgt_samp;
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
W_ctx1 = W_ctx1 .* wgt_samp;
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
% alpha_ctx2 = alpha_ctx2 * params.shrinkage_factor;
%
% current_response_ctx2 = current_response_ctx2 + alpha_ctx2*cached_responses_ctx2;
%
% W_ctx2 = compute_wi(current_response_ctx2);
%
% W_ctx2 = W_ctx2 .* wgt_samp;
%
% R_ctx2 = compute_ri(current_response_ctx2);
%
% weak_learners_ctx2(i_w).alpha = alpha_ctx2;
save([params.codename '_weak_learners_sav.mat'],'weak_learners','weak_learners_ctx1');
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
MR = sum(((current_response>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_w(i_w,1) = 100*MR;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum(((current_response_ctx1>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx1w(i_w,1) = 100*MR;
% MR = sum((current_response_ctx2>0)~=(labels>0))/length(labels);
%
% fprintf(' Ctx2 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx2));
%
% train_scores_ctx2(i_w,1) = 100*MR;
%
% train_scores_ctx2(i_w,2) = compute_loss(current_response_ctx2);
%
% train_scores_ctx2(i_w,3) = alpha_ctx2;
%
% MR = sum(((current_response_ctx2>0)~=(labels>0)) .* wgt_samp)/...
% (length(labels) * mean(wgt_samp));
%
% train_scores_ctx2w(i_w,1) = 100*MR;
save([params.codename '_train_scores_sav_w.mat'],'train_scores_w','train_scores_ctx1w');
for i_img = 1 : length(data.train.gts.X)
img_idx = find(samples_idx(:,1) == i_img);
MR_img(i_w,i_img) = sum((current_response(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
MR_img_ctx1(i_w,i_img) = sum((current_response_ctx1(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
end
save([params.codename '_MR_sav.mat'],'MR_img','MR_img_ctx1');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx1');
end
if(i_w > 0)
% collect th colour value of the sample data
% samp_rgb = zeros(size(samples_idx,1),3);
%
% for i_img = 1 : size(data.train.(ch).X,1)
%
% X = data.train.(ch).X(i_img,data.train.(ch).idxs);
%
% clear I;
%
% for i_b = 1 : 3
%
% I(:,:,i_b) = X{i_b};
%
% end
%
%
% samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
%
% posi_samp = sub2ind(size(I(:,:,1)),samp_idx_img(:,2),samp_idx_img(:,3));
%
% I = reshape(I,[],3);
%
% samp_rgb(samples_idx == i_img,:) = I(posi_samp,:);
%
% end
wltree = weak_learners(i_w).reg_tree;
% [~,samp_lf] = predict_idx_wl(data,params,samples_idx,weak_learners(i_w));
%
% lf_hist = histc(samp_lf,1:length(wltree));
%
% lf_hist = lf_hist(1:length(wltree));
%
% lf_hist = lf_hist / sum(lf_hist);
%
% [lfn,lf_id] = sort(lf_hist,'descend');
%
% lf_id(lfn < 0.3) = [];
%
% lfn(lfn < 0.3) = [];
%
% for i_lf = 1 : length(lf_id)
%
% [~,ctx_km_c{i_lf}] = kmeans(samp_rgb(samp_lf == lf_id(i_lf),:),n_km,'EmptyAction','singleton');
%
% end
%
% for i_n = 1 : length(wltree)
%
% bkg_ftrs2{i_n} = [];
%
%
%
% %bkg_idxs{i_n} = [];
%
% end
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
mask_img = data.train.masks.X{i_img};
[mask_x,mask_y] = find(mask_img > 0);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),[mask_x,mask_y]);
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
%context_img = zeros(size(leaf_image));
% cxt_idx = 1;
n_leaf = 0;
ctx_c1 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
% if(length(n_idx) / n_samp_img > 0.2)
%
% I_2D = reshape(I,[],3);
%
% n_idx = downsample(n_idx,200);
%
% bkg_ftrs2{i_n} = [ bkg_ftrs2{i_n}; I_2D(n_idx,:)];
%
%
% end
end
end
% contx_list{i_w,i_img} = ctx_c2;
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
% ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
% ctx_ftrs1(ctx_ftrs1 < 0.1) = 5000;
mask_img = data.train.masks.X{i_img};
dist_ctx_map = bwdist(~mask_img);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
known_mb = score_image > 0.5;
known_mb = filter_small_comp(known_mb,50);
known_mb = (dist_ctx_map > 10) .* known_mb;
dist_ctx_map = bwdist(known_mb);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
% n_km = 30;
%
% ctx_c2 = [];
%
% clear ftrs_kmc_c2;
%
% kmc_ctx_c2 = [];
%
% tleaf_ctx_c2 = [];
%
% for i_n = 1 : length(wltree)
%
% if(~isempty(bkg_ftrs2{i_n}))
%
% tStart = tic;
%
% [~,ftrs_kmc_tmp] = kmeans(bkg_ftrs2{i_n},n_km,'EmptyAction','singleton');
%
% t1 = toc(tStart);
%
% fprintf('Clustering the context ftrs 2 took %d seconds', t1);
%
%
% ctx_c2(end + 1 : end + n_km) = (100 * i_n) + (1:n_km);
%
% ftrs_kmc{i_w,i_n} = ftrs_kmc_tmp;
%
% kmc_ctx_c2(end + 1: end + n_km,:) = ftrs_kmc_tmp;
%
% tleaf_ctx_c2(end + 1: end + n_km,:) = i_n;
%
% else
%
% ftrs_kmc{i_w,i_n} = {};
%
% end
%
% end
%
% n_ftrs2 = length(ctx_c2);
%
%
% for i_img = 1 : size(data.train.(ch).X,1)
%
% ctx_ftrs2_w{i_w,i_img} = [];
%
% X = data.train.(ch).X(i_img,data.train.(ch).idxs);
%
% tStart = tic;
%
% % to avoid the computational burden, now apply the method only
% % on some sample points
%
% samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
%
% [score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
%
% t1 = toc(tStart);
%
% fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
%
% ftrs2_img = zeros(size(leaf_image));
%
% samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
%
% samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
%
% ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
%
% for i_n = 1 : length(wltree)
%
% if(~isempty(ftrs_kmc{i_w,i_n}))
%
% ftrs2_img_tmp = ftrs_c2_img(X,ftrs_kmc{i_w,i_n});
%
% ftrs2_img = (i_n * 100 + ftrs2_img_tmp);
%
% % ftrs2_img = (i_n * 100 + ftrs2_img_tmp) .* (leaf_image == i_n);
%
%
% end
%
% end
% for i_ctx = 1 : length(ctx_c2)
%
% tStart = tic;
%
% lf_ctx = (ftrs2_img == ctx_c2(i_ctx));
%
% if(sum(lf_ctx(:)))
%
% dist_ctx_map = bwdist(lf_ctx);
%
% ctx_ftrs2(:,i_ctx) = dist_ctx_map(samp_idx_img);
%
% else
%
% ctx_ftrs2(:,i_ctx) = 5000;
%
% end
%
% t1 = toc(tStart);
%
% fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
%
% end
% ctx_ftrs2(ctx_ftrs2 < 0.1) = 5000;
% ctx_ftrs2_w{i_w,i_img} = ctx_ftrs2;
% clear ctx_ftrs2;
% end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_context_v3.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_context_v3.m
| 25,557 |
utf_8
|
5aa5932a1ada7fb8cf18470eb03d4606
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners] = train_boost_context_v3(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
weak_learners(params.wl_no).alpha = 0;
weak_learners_ctx1(params.wl_no).alpha = 0;
weak_learners_ctx2(params.wl_no).alpha = 0;
debug_flag = 1;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
current_response_ctx2 = current_response;
W_ctx1 = W;
R_ctx1 = R;
W_ctx2 = W;
R_ctx2 = R;
train_scores = zeros(params.wl_no,3);
train_scores_ctx1 = zeros(params.wl_no,3);
train_scores_ctx2 = zeros(params.wl_no,3);
n_km = 30;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
%save('tmp_ftrs.mat');
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
ctx_loc_all = zeros(size(samples_idx,1),n_ftrs2);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
if(~isempty(ctx_ftrs2_w{i_w - 1,i_img}))
ctx_loc_all(samples_idx(:,1) == i_img,:) = ctx_ftrs2_w{i_w - 1,i_img};
end
ctx_ftrs1_w{i_w - 1,i_img} = [];
ctx_ftrs2_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
ctx_loc = ctx_loc_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
% t_tr = tic;
% reg_tree_l = LDARegStumpTrain(single([features,ctx_loc]),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
% for i_img = 1 : size(data.train.(ch).X,1)
%
% T2_img = samples_idx(T2_idx,1) == i_img;
%
% ctx_loc_img = ctx_loc(T2_img,:);
%
% ctx_glb_img = ctx_glb(T2_img,:);
%
% fprintf(' Training regression tree %d on learned features combined with context 1 2...\n',i_img);
%
% t_tr = tic;
% reg_tree_l{i_img} = LDARegStumpTrain(single([features(T2_img,:),...
% ctx_glb_img,ctx_loc_img]),R(T2_idx(T2_img)),W(T2_idx(T2_img)) ...
% /sum(W(T2_idx((T2_img)))),...
% uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
%
% end
fprintf(' Training regression tree on learned features combined with context 1 2...\n');
t_tr = tic;
reg_tree_l = LDARegStumpTrain(single([features,...
ctx_glb,ctx_loc]),R_ctx2(T2_idx),W_ctx2(T2_idx) ...
/sum(W_ctx2(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
[weak_learners_ctx2(i_w).kernels,weak_learners_ctx2(i_w).kernel_params,weak_learners_ctx2(i_w).reg_tree,...
weak_learners_ctx2(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_l,kernels,kernel_params);
ctx2_list = weak_learners_ctx2(i_w).ctx_list;
ctx2_list(ctx2_list < ncf_g + 1) = [];
ctx2_list = ctx2_list - ncf_g;
tmp_kmc = [];
tmp_ltree = [];
for i_km = 1 : length(ctx2_list)
tmp_kmc(i_km,:) = kmc_ctx_c2(ctx2_list(i_km),:);
tmp_ltree(i_km) = tleaf_ctx_c2(ctx2_list(i_km));
end
weak_learners_ctx2(i_w).kmc = tmp_kmc;
weak_learners_ctx2(i_w).ltree = tmp_ltree;
% ctx2_list = ctx2_list - ncf_g;
weak_learners_ctx2(i_w).ctx2_list = ctx2_list;
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
ctx_glb_all = [ctx_glb_all, ctx_loc_all];
clear ctx_loc_all;
features_ctx2 = ctx_glb_all(:,weak_learners_ctx2(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx2(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),...
weak_learners_ctx2(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx2(i_w).kernels(idxs),...
weak_learners_ctx2(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx2 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx2 = LDARegStumpPredict(...
weak_learners_ctx2(i_w).reg_tree,single([features, features_ctx2]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 features_ctx2 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
fprintf(' Finding alpha 2 through line search...\n');
t_alp = tic;
alpha_ctx2 = mexLineSearch(current_response_ctx2,cached_responses_ctx2,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx2,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
alpha_ctx2 = alpha_ctx2 * params.shrinkage_factor;
current_response_ctx2 = current_response_ctx2 + alpha_ctx2*cached_responses_ctx2;
W_ctx2 = compute_wi(current_response_ctx2);
R_ctx2 = compute_ri(current_response_ctx2);
weak_learners_ctx2(i_w).alpha = alpha_ctx2;
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum((current_response_ctx2>0)~=(labels>0))/length(labels);
fprintf(' Ctx2 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx2));
train_scores_ctx2(i_w,1) = 100*MR;
train_scores_ctx2(i_w,2) = compute_loss(current_response_ctx2);
train_scores_ctx2(i_w,3) = alpha_ctx2;
end
save('train_scores_sav_v3.mat','train_scores','train_scores_ctx1','train_scores_ctx2');
if(i_w > 0)
% collect th colour value of the sample data
samp_rgb = zeros(size(samples_idx,1),3);
for i_img = 1 : size(data.train.(ch).X,1)
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
posi_samp = sub2ind(size(I(:,:,1)),samp_idx_img(:,2),samp_idx_img(:,3));
I = reshape(I,[],3);
samp_rgb(samples_idx == i_img,:) = I(posi_samp,:);
end
wltree = weak_learners(i_w).reg_tree;
[~,samp_lf] = predict_idx_wl(data,params,samples_idx,weak_learners(i_w));
lf_hist = histc(samp_lf,1:length(wltree));
lf_hist = lf_hist(1:length(wltree));
lf_hist = lf_hist / sum(lf_hist);
[lfn,lf_id] = sort(lf_hist,'descend');
lf_id(lfn < 0.3) = [];
lfn(lfn < 0.3) = [];
% for i_lf = 1 : length(lf_id)
%
% [~,ctx_km_c{i_lf}] = kmeans(samp_rgb(samp_lf == lf_id(i_lf),:),n_km,'EmptyAction','singleton');
%
% end
%
for i_n = 1 : length(wltree)
bkg_ftrs2{i_n} = [];
%bkg_idxs{i_n} = [];
end
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
if(debug_flag)
if(mod(i_img,7) == 1)
leaf_img_prev{i_img} = leaf_image;
end
end
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
%context_img = zeros(size(leaf_image));
% cxt_idx = 1;
n_leaf = 0;
ctx_c1 = [];
ctx_c2 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
if(length(n_idx) / n_samp_img > 0.2)
I_2D = reshape(I,[],3);
n_idx = downsample(n_idx,200);
bkg_ftrs2{i_n} = [ bkg_ftrs2{i_n}; I_2D(n_idx,:)];
end
end
end
% contx_list{i_w,i_img} = ctx_c2;
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
% ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
ctx_ftrs1(ctx_ftrs1 < 0.1) = 5000;
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
weak_learners_ctx1(i_w + 1).ctx_c1 = ctx_c1;
weak_learners_ctx2(i_w + 1).ctx_c1 = ctx_c1;
n_km = 30;
ctx_c2 = [];
clear ftrs_kmc_c2;
kmc_ctx_c2 = [];
tleaf_ctx_c2 = [];
for i_n = 1 : length(wltree)
if(~isempty(bkg_ftrs2{i_n}))
tStart = tic;
[~,ftrs_kmc_tmp] = kmeans(bkg_ftrs2{i_n},n_km,'EmptyAction','singleton');
t1 = toc(tStart);
fprintf('Clustering the context ftrs 2 took %d seconds', t1);
ctx_c2(end + 1 : end + n_km) = (100 * i_n) + (1:n_km);
ftrs_kmc{i_w,i_n} = ftrs_kmc_tmp;
kmc_ctx_c2(end + 1: end + n_km,:) = ftrs_kmc_tmp;
tleaf_ctx_c2(end + 1: end + n_km,:) = i_n;
else
ftrs_kmc{i_w,i_n} = {};
end
end
weak_learners_ctx2(i_w + 1).ctx_c2 = ctx_c2;
n_ftrs2 = length(ctx_c2);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_ftrs2_w{i_w,i_img} = [];
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
ftrs2_img = zeros(size(leaf_image));
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
for i_n = 1 : length(wltree)
if(~isempty(ftrs_kmc{i_w,i_n}))
ftrs2_img_tmp = ftrs_c2_img(X,ftrs_kmc{i_w,i_n});
ftrs2_img = (i_n * 100 + ftrs2_img_tmp) .* (leaf_image == i_n);
end
end
for i_ctx = 1 : length(ctx_c2)
tStart = tic;
lf_ctx = (ftrs2_img == ctx_c2(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs2(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs2(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
ctx_ftrs2(ctx_ftrs2 < 0.1) = 5000;
ctx_ftrs2_w{i_w,i_img} = ctx_ftrs2;
% clear ctx_ftrs2;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_ctx_latent_img_debug.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_ctx_latent_img_debug.m
| 6,410 |
utf_8
|
8229269b926bdeb54873ea52c86d242a
|
% use the mask distance as well as the main branch distance
% collect the latent label
% eavluate the effect of auto context
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx,weak_learners_ac] = train_boost_ctx_latent_img_debug(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ac = current_response;
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
% load the training images
X = data.train.imgs.X(:,data.train.imgs.idxs);
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W,R);
cached_responses = evaluate_weak_learners(X,params,samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
%%%%%% train the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
if(i_w > 1)
% in this step, apply the auto context feature learning
X_ac = X;
for i_img = 1 : size(X,1)
X_ac{i_img,size(X,2) + 1} = ac_ftrs{i_img};
end
[weak_learners_ac(i_w).kernels,weak_learners_ac(i_w).kernel_params,...
weak_learners_ac(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W_ac,R_ac);
cached_responses_ac = evaluate_weak_learners(X_ac,params,samples_idx,weak_learners_ac(i_w));
weak_learners_ac(i_w).alpha = search_alpha(current_response_ac,cached_responses_ac,labels,params);
current_response_ac = current_response_ac + weak_learners_ac(i_w).alpha * cached_responses_ac;
W_ac = compute_wi(current_response_ac);
R_ac = compute_ri(current_response_ac);
train_scores_ac(i_w,:) = weak_learner_scores(current_response_ac,labels,wgt_samp,compute_loss);
else
for i_img = 1 : size(X,1)
ac_ftrs{i_img} = zeros(size(X{i_img,1}));
end
end
%%%%%% Complete training the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
%%%%%%%%%%%% start training the ctx augmented weak learners%%%%%%%%%
if(i_w > 1)
% load the global context features
[weak_learners_ctx(i_w).kernels,weak_learners_ctx(i_w).kernel_params,...
weak_learners_ctx(i_w).reg_tree, weak_learners_ctx(i_w).ctx_list]...
= train_kernel_boost_ctx(X,params,ctx_glb_all,...
samples_idx,T1_idx,T2_idx,W_ctx,R_ctx);
% now the context feature is a subset of the full context features
weak_learners_ctx(i_w).ctx_lf_list = ctx_lf_list;
% this version simply ignores the ctx_list assigned by the previous
% method
% weak_learners_ctx(i_w).ctx_list = ctx_list;
weak_learners_ctx(i_w).ctx_latent = ctx_list_latent;
cached_responses_ctx = evaluate_weak_learners_ctx(X,params,ctx_glb_all,samples_idx,weak_learners_ctx(i_w));
weak_learners_ctx(i_w).alpha = search_alpha(current_response_ctx,cached_responses_ctx,labels,params);
current_response_ctx = current_response_ctx + weak_learners_ctx(i_w).alpha * cached_responses_ctx;
W_ctx = compute_wi(current_response_ctx);
R_ctx = compute_ri(current_response_ctx);
train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx','weak_learners','weak_learners_ac');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx','train_scores_ac');
end
%%%% complete training the global context feature weak learners
% collect the global features as well as auto context features, be aware
% of the global features, they are only prepared for the next round, so
% this part should be behind the context and auto context learning
[ctx_glb_all,ac_ftrs,ctx_lf_list,ctx_list_latent,sub_region_img] = collect_global_ctx_latent(X,data.train.gts,data.train.masks,...
params,weak_learners(i_w),samples_idx,ac_ftrs);
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_admm_ctx_fix.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_admm_ctx_fix.m
| 5,704 |
utf_8
|
6693d498880a21f4f3d8fd90e3046e81
|
% use the mask distance as well as the main branch distance
% collect the latent label
% eavluate the effect of auto context
% includes the latent label
% discard the kernel features and adopts the new admm features
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_admm] = train_admm_ctx_fix(params,data,samples_idx)
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ac = current_response;
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
X = data.train.imgs.X(:,data.train.imgs.idxs);
features_admm = collect_admm_ftrs(X,samples_idx);
features_admm1 = collect_admm_ftrs1(X,samples_idx);
features_admm = [features_admm,features_admm1];
ctx_y = collect_label_ctx(data.train.gts.X,samples_idx);
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
i_ch = 1;
ch = 'imgs';
sub_ch_no = data.train.imgs.sub_ch_no;
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression...
(params,params.(ch),X(:,i_s),1 : sub_ch_no,samples_idx(T1_idx,1:3),R(T1_idx),W(T1_idx),i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
end
for i_s = 1 : sub_ch_no
if(isfield(params,'n_kb'))
kernels{i_ch}{i_s} = kernels{i_ch}{i_s}(1:params.n_kb);
kernel_params{i_ch}{i_s} = kernel_params{i_ch}{i_s}(1:params.n_kb);
end
end
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
[weak_learners_admm(i_w).kernels,weak_learners_admm(i_w).kernel_params,...
weak_learners_admm(i_w).reg_tree, weak_learners_admm(i_w).ctx_list]...
= train_kernel_gb_ctx(X,kernels,kernel_params,params,features_admm,...
samples_idx,W_ctx,R_ctx);
[cached_responses_ctx,lf_resp_ctx] = evaluate_weak_learners_ctx_leaf_node(X,params,features_admm,samples_idx,weak_learners_admm(i_w));
wltree = weak_learners_admm(i_w).reg_tree;
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
resp_n = (lf_resp_ctx == i_n);
n_resp_lf(i_n) = sum(resp_n);
leaf_struct_stack = ctx_y(resp_n,:,:);
wltree(i_n).n_resp = n_resp_lf(i_n);
if(n_resp_lf(i_n) > 0)
m_patch_leaf = mean(leaf_struct_stack,1);
wltree(i_n).struct_y = reshape(m_patch_leaf,21,21);
end
end
end
weak_learners_admm(i_w).reg_tree = wltree;
% leaf_img = reshape(leaf_struct_stack(85474,:,:),21,21);
%
% m_patch_leaf = mean(leaf_struct_stack,1);
%
% m_patch_leaf_img = reshape(m_patch_leaf,21,21);
%
weak_learners_admm(i_w).alpha = search_alpha(current_response_ctx,cached_responses_ctx,labels,params);
current_response_ctx = current_response_ctx + weak_learners_admm(i_w).alpha * cached_responses_ctx;
W_ctx = compute_wi(current_response_ctx);
R_ctx = compute_ri(current_response_ctx);
train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx,labels,wgt_samp,compute_loss);
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree, weak_learners(i_w).ctx_list]...
= train_kernel_gb_ctx(X,kernels,kernel_params,params,[],...
samples_idx,W,R);
cached_responses = evaluate_weak_learners_ctx(X,params,[],samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_admm','weak_learners');
save([params.codename '_train_scores_sav.mat'],'train_scores_ctx','train_scores');
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_latent_img_v2.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_latent_img_v2.m
| 5,988 |
utf_8
|
6d2642ea978b7da9056495d29ecf656f
|
% use the mask distance as well as the main branch distance
% eavluate the effect of auto context
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx,weak_learners_ac] = train_boost_latent_img_v2(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
% introduce the concept of latent images
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ac = current_response;
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
% load the training images
X = data.train.imgs.X(:,data.train.imgs.idxs);
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W,R);
cached_responses = evaluate_weak_learners(X,params,samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
%%%%%% train the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
if(i_w > 1)
% in this step, apply the auto context feature learning
X_ac = X;
for i_img = 1 : size(X,1)
X_ac{i_img,size(X,2) + 1} = ac_ftrs{i_img};
end
[weak_learners_ac(i_w).kernels,weak_learners_ac(i_w).kernel_params,...
weak_learners_ac(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W_ac,R_ac);
cached_responses_ac = evaluate_weak_learners(X_ac,params,samples_idx,weak_learners_ac(i_w));
weak_learners_ac(i_w).alpha = search_alpha(current_response_ac,cached_responses_ac,labels,params);
current_response_ac = current_response_ac + weak_learners_ac(i_w).alpha * cached_responses_ac;
W_ac = compute_wi(current_response_ac);
R_ac = compute_ri(current_response_ac);
train_scores_ac(i_w,:) = weak_learner_scores(current_response_ac,labels,wgt_samp,compute_loss);
else
for i_img = 1 : size(X,1)
ac_ftrs{i_img} = zeros(size(X{i_img,1}));
end
end
%%%%%% Complete training the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
%%%%%%%%%%%% start training the ctx augmented weak learners%%%%%%%%%
if(i_w > 1)
% load the global context features
[weak_learners_ctx(i_w).kernels,weak_learners_ctx(i_w).kernel_params,...
weak_learners_ctx(i_w).reg_tree, weak_learners_ctx(i_w).ctx_list]...
= train_kernel_boost_ctx(X,params,ctx_glb_all,...
samples_idx,T1_idx,T2_idx,W_ctx,R_ctx);
cached_responses_ctx = evaluate_weak_learners_ctx(X,params,ctx_glb_all,samples_idx,weak_learners_ctx(i_w));
weak_learners_ctx(i_w).alpha = search_alpha(current_response_ctx,cached_responses_ctx,labels,params);
current_response_ctx = current_response_ctx + weak_learners_ctx(i_w).alpha * cached_responses_ctx;
W_ctx = compute_wi(current_response_ctx);
R_ctx = compute_ri(current_response_ctx);
train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx','weak_learners','weak_learners_ac');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx','train_scores_ac');
end
%%%% complete training the global context feature weak learners
% collect the global features as well as auto context features, be aware
% of the global features, they are only prepared for the next round, so
% this part should be behind the context and auto context learning
[ctx_glb_all,ac_ftrs] = collect_global_ctx(X,data.train.masks,...
params,weak_learners(i_w),samples_idx,ac_ftrs);
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_ctxplus_lftrs.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_ctxplus_lftrs.m
| 24,119 |
utf_8
|
aee065fc88ff5c243e5a950b83f26c06
|
% use the mask distance as well as the main branch distance
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx1] = train_boost_ctxplus_lftrs(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
W_ctx1 = W;
R_ctx1 = R;
n_km = 30;
% assign the weight for each individual data point
wgt_samp = zeros(size(samples_idx,1),1);
tol_z_wgt = params.tol_z_wgt;
fig_thres = params.fig_thres;
lf_thrs = params.lf_thrs;
for i_img = 1 : length(data.train.gts.X)
gt_img = data.train.gts.X{i_img};
dist_gt = bwdist(gt_img);
idx_img = (samples_idx(:,1) == i_img);
samp_idx_img_2D = samples_idx(idx_img,2:3);
samp_idx_img_1D = sub2ind(size(gt_img),samp_idx_img_2D(:,1),samp_idx_img_2D(:,2));
wgt_img = dist_gt(samp_idx_img_1D);
wgt_img(wgt_img > tol_z_wgt) = tol_z_wgt;
wgt_img = wgt_img/ tol_z_wgt;
wgt_img(dist_gt(samp_idx_img_1D) < 0.3) = 1;
wgt_samp(idx_img) = wgt_img;
end
W = W .* wgt_samp;
W_ctx1 = W_ctx1 .* wgt_samp;
% W_ctx2 = W_ctx2 .* wgt_samp;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
% if(i_w > 1)
%
% % new leaf features
%
% features_lf = cell(sub_ch_no,1);
% kernels_lf = cell(sub_ch_no,1);
% kernel_params_lf = cell(sub_ch_no,1);
%
%
% end
% for i_ch = 1:params.ch_no
i_ch = 1;
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels...
(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
%
% features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),...
% params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
%
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
% learn the leaf specific features designed which is adaptive to
% the specfic subset of samples
if(i_w > 1)
% leaf_samples = zeros(size(samples_idx,1),1);
%
% for i_img = 1 : size(data.train.(ch).X,1)
%
% leaf_samples(samples_idx(:,1) == i_img,1) = lf_samp_idx{i_img};
%
% end
%
% leaf_samples = leaf_samples(wr_idxs);
%
%
% hist_leaf_sp = histc(leaf_samples,1:max(leaf_samples));
%
% n_samp = size(wr_idxs,1);
%
% leaf_idx = find(hist_leaf_sp);
%
% current_response_prec = current_response;
%
% current_response_prec(labels < 0) = -current_response(labels < 0);
%
% current_response_prec = current_response_prec(wr_idxs);
%
% n_leaf = length(leaf_idx);
%
% leaf_prec = zeros(n_leaf,1);
%
% leaf_h = zeros(n_leaf,1);
%
% W1 = compute_wi(current_response);
%
% W_wr = W1(wr_idxs);
%
% for ilf = 1 : length(leaf_idx)
%
% lf = leaf_idx(ilf);
%
% leaf_prec(ilf) = mean(current_response_prec(leaf_samples == lf) > 0);
%
% leaf_h(ilf) = hist_leaf_sp(lf);
%
% leaf_err(ilf) = mean(W_wr(leaf_samples == lf));
%
% end
%
% [~,lfi] = sort(leaf_h);
%
% leaf_prec(lfi);
%
% leaf_err(lfi);
% only collect the leaf features for the large enough samples
leaf_samples = zeros(size(samples_idx,1),1);
for i_img = 1 : size(data.train.(ch).X,1)
leaf_samples(samples_idx(:,1) == i_img,1) = lf_samp_idx{i_img};
end
leaf_samples = leaf_samples(wr_idxs);
hist_leaf_sp = histc(leaf_samples,1:max(leaf_samples));
leaf_idx = find((hist_leaf_sp / params.T1_size) > lf_thrs);
n_subf(i_w) = length(leaf_idx);
save('tmp_n_subf_sav.mat','n_subf');
kernels_lf1 = cell(length(leaf_idx),1);
kernel_params_lf1 = cell(length(leaf_idx),1);
for ilf = 1 : length(leaf_idx)
features_lf{i_ch} = cell(sub_ch_no,1);
kernels_lf{i_ch} = cell(sub_ch_no,1);
kernel_params_lf{i_ch} = cell(sub_ch_no,1);
sp_lf_idx = leaf_samples == (leaf_idx(ilf));
params1 = params;
params1.rand_samples_no = 1000;
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning the leaf features on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels_lf{i_ch}{i_s},kernel_params_lf{i_ch}{i_s}] = ...
mexMultipleSmoothRegression(params1,params.(ch),X(:,i_s),...
X_idxs,s_T1(sp_lf_idx,:),wr_responses(sp_lf_idx),wr_weights(sp_lf_idx),i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels_lf{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the leaf filters learned on the subchannel\n');
features_lf{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T1(sp_lf_idx,1:3),...
params.sample_size,kernels_lf{i_ch}{i_s},kernel_params_lf{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
fprintf(' Merging leaf features and kernels...\n');
% kernels_lf{1} = kernels_lf;
[kernels_lf,kernel_params_lf,features_lf] = merge_features_kernels...
(kernels_lf,kernel_params_lf,features_lf);
fprintf(' Start reducing %d leaf features on subchannel \n',size(features_lf,2));
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
R_ctx1_wr = R_ctx1(wr_idxs);
W_ctx1_wr = W_ctx1(wr_idxs);
reg_tree_lf = LDARegStumpTrain(single(features_lf...
),R_ctx1_wr(sp_lf_idx),W_ctx1_wr(sp_lf_idx)...
/sum(W_ctx1_wr(sp_lf_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
fprintf(' Removing useless leaf kernels...\n');
[kernels_lf1{ilf},kernel_params_lf1{ilf}]...
= remove_useless_filters(reg_tree_lf,kernels_lf,kernel_params_lf);
fprintf(' %d leaf features is reduced to %d \n',...
size(features_lf,2),length(kernels_lf1{ilf}));
clear features_lf kernel_params_lf kernel_params_lf;
end
% from this step, the context features and leaf features are added for individual image.
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
ctx_ftrs1_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
fprintf(' Combine the %d leaf features\n',length(leaf_idx));
features_lf = cell(length(leaf_idx),1);
for ilf = 1 : length(leaf_idx)
t_ev = tic;
fprintf(' Evaluating the leaf filters %d of %d\n',ilf,length(leaf_idx));
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),kernel_params_lf1{ilf}));
if (~isempty(idxs))
features_lf{ilf}(:,idxs) = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),...
params.sample_size,kernels_lf1{ilf}(idxs),...
kernel_params_lf1{ilf}(idxs));
end
end
ev_time = toc(t_ev);
fprintf(' Done! (took %f seconds)\n',ev_time);
end
features_lf1 = [];
kernels_lf2 = [];
kernel_params_lf2 = [];
for ilf = 1 : length(leaf_idx)
features_lf1 = [features_lf1, features_lf{ilf}];
kernels_lf2 = [kernels_lf2; kernels_lf1{ilf}];
kernel_params_lf2 = [kernel_params_lf2; kernel_params_lf1{ilf}];
end
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
if(isfield(params,'ctx1_tree_depth'))
tree_d_g = params.ctx1_tree_depth;
else
tree_d_g = params.tree_depth;
end
reg_tree_g = LDARegStumpTrain(single([features,...
features_lf1,ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(tree_d_g));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx_lftrs(reg_tree_g,kernels,kernel_params,....
kernels_lf2,kernel_params_lf2);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx1','weak_learners');
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
W = W .* wgt_samp;
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
W_ctx1 = W_ctx1 .* wgt_samp;
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
save([params.codename '_weak_learners_sav.mat'],'weak_learners','weak_learners_ctx1');
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
MR = sum(((current_response>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_w(i_w,1) = 100*MR;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum(((current_response_ctx1>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx1w(i_w,1) = 100*MR;
save([params.codename '_train_scores_sav_w.mat'],'train_scores_w','train_scores_ctx1w');
for i_img = 1 : length(data.train.gts.X)
img_idx = find(samples_idx(:,1) == i_img);
MR_img(i_w,i_img) = sum((current_response(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
MR_img_ctx1(i_w,i_img) = sum((current_response_ctx1(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
end
save([params.codename '_MR_sav.mat'],'MR_img','MR_img_ctx1');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx1');
end
if(i_w > 0)
% collect th colour value of the sample data
wltree = weak_learners(i_w).reg_tree;
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
mask_img = data.train.masks.X{i_img};
[mask_x,mask_y] = find(mask_img > 0);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),[mask_x,mask_y]);
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
n_leaf = 0;
ctx_c1 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
end
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% record the leaf node each sample is assigned to
lf_samp_idx_img = leaf_image(samp_idx_img);
% set the pixels on the context as irrelevant to avoid the overfitting issues
mask_img = data.train.masks.X{i_img};
dist_ctx_map = bwdist(~mask_img);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
known_mb = score_image > fig_thres;
known_mb = (bwdist(~mask_img) > 10) .* known_mb;
if(sum(known_mb(:)))
dist_ctx_map = bwdist(known_mb);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,end + 1) = 5000;
end
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
lf_samp_idx{i_img} = lf_samp_idx_img;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_RF_ctx.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_RF_ctx.m
| 4,195 |
utf_8
|
def6c9c60931fb18d7d9eb07038a6cca
|
% use the mask distance as well as the main branch distance
% evaluate the effect of auto context
% takes the random forest framework
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx] = train_RF_ctx(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
% load the training images
X = data.train.imgs.X(:,data.train.imgs.idxs);
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W,R);
cached_responses = evaluate_weak_learners(X,params,samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
end
% collect the global features as well as auto context features, be aware
% of the global features, they are only prepared for the next round, so
% this part should be behind the context and auto context learning
ctx_glb_all = collect_global_ctx(X,data.train.masks,...
params,weak_learners(params.wl_no),samples_idx);
W_ctx = W_ctx .* wgt_samp;
for i_w = 1 : params.wl_no_ctx
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
%%%%%%%%%%%% start training the ctx augmented weak learners%%%%%%%%%
% load the global context features
[weak_learners_ctx(i_w).kernels,weak_learners_ctx(i_w).kernel_params,...
weak_learners_ctx(i_w).reg_tree, weak_learners_ctx(i_w).ctx_list]...
= train_kernel_rf_ctx(X,params,ctx_glb_all,...
samples_idx,T1_idx,T2_idx,W_ctx,R_ctx);
cached_responses_ctx = evaluate_weak_learners_ctx(X,params,ctx_glb_all,samples_idx,weak_learners_ctx(i_w));
current_response_ctx = current_response_ctx + cached_responses_ctx;
train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx / i_w,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx','weak_learners');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx');
%%%% complete training the global context feature weak learners
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_context.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_context.m
| 23,755 |
utf_8
|
e372e8bdd37a924891c53b0a9c01edb2
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners] = train_boost_context(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
weak_learners(params.wl_no).alpha = 0;
weak_learners_ctx1(params.wl_no).alpha = 0;
weak_learners_ctx2(params.wl_no).alpha = 0;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
current_response_ctx2 = current_response;
W_ctx1 = W;
R_ctx1 = R;
W_ctx2 = W;
R_ctx2 = R;
train_scores = zeros(params.wl_no,3);
train_scores_ctx1 = zeros(params.wl_no,3);
train_scores_ctx2 = zeros(params.wl_no,3);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 11)
% from this step, the context featuers are added for individual image.
n_km = 30;
%save('tmp_ftrs.mat');
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
ctx_loc_all = zeros(size(samples_idx,1),n_km);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
ctx_loc_all(samples_idx(:,1) == i_img,:) = ctx_ftrs2_w{i_w - 1,i_img};
ctx_ftrs1_w{i_w - 1,i_img} = [];
ctx_ftrs2_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
ctx_loc = ctx_loc_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
% t_tr = tic;
% reg_tree_l = LDARegStumpTrain(single([features,ctx_loc]),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
% for i_img = 1 : size(data.train.(ch).X,1)
%
% T2_img = samples_idx(T2_idx,1) == i_img;
%
% ctx_loc_img = ctx_loc(T2_img,:);
%
% ctx_glb_img = ctx_glb(T2_img,:);
%
% fprintf(' Training regression tree %d on learned features combined with context 1 2...\n',i_img);
%
% t_tr = tic;
% reg_tree_l{i_img} = LDARegStumpTrain(single([features(T2_img,:),...
% ctx_glb_img,ctx_loc_img]),R(T2_idx(T2_img)),W(T2_idx(T2_img)) ...
% /sum(W(T2_idx((T2_img)))),...
% uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
%
% end
fprintf(' Training regression tree on learned features combined with context 1 2...\n');
t_tr = tic;
reg_tree_l = LDARegStumpTrain(single([features,...
ctx_glb,ctx_loc]),R_ctx2(T2_idx),W_ctx2(T2_idx) ...
/sum(W_ctx2(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 11)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
[weak_learners_ctx2(i_w).kernels,weak_learners_ctx2(i_w).kernel_params,weak_learners_ctx2(i_w).reg_tree,...
weak_learners_ctx2(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_l,kernels,kernel_params);
ctx2_list = weak_learners_ctx2(i_w).ctx_list;
ctx2_list(ctx2_list < ncf_g + 1) = [];
ctx2_list = ctx2_list - ncf_g;
tmp_kmc = [];
tmp_ltree = [];
for i_km = 1 : length(ctx2_list)
tmp_kmc(i_km,:) = kmc_ctx_c2(ctx2_list(i_km),:);
tmp_ltree(i_km) = tleaf_ctx_c2(ctx2_list(i_km));
end
weak_learners_ctx2(i_w).kmc = tmp_kmc;
weak_learners_ctx2(i_w).ltree = tmp_ltree;
% ctx2_list = ctx2_list - ncf_g;
weak_learners_ctx2(i_w).ctx2_list = ctx2_list;
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 11)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
ctx_glb_all = [ctx_glb_all, ctx_loc_all];
clear ctx_loc_all;
features_ctx2 = ctx_glb_all(:,weak_learners_ctx2(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx2(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),...
weak_learners_ctx2(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx2(i_w).kernels(idxs),...
weak_learners_ctx2(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx2 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx2 = LDARegStumpPredict(...
weak_learners_ctx2(i_w).reg_tree,single([features, features_ctx2]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 features_ctx2 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 11)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
fprintf(' Finding alpha 2 through line search...\n');
t_alp = tic;
alpha_ctx2 = mexLineSearch(current_response_ctx2,cached_responses_ctx2,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx2,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
if(i_w > 11)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
alpha_ctx2 = alpha_ctx2 * params.shrinkage_factor;
current_response_ctx2 = current_response_ctx2 + alpha_ctx2*cached_responses_ctx2;
W_ctx2 = compute_wi(current_response_ctx2);
R_ctx2 = compute_ri(current_response_ctx2);
weak_learners_ctx2(i_w).alpha = alpha_ctx2;
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
if(i_w > 11)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum((current_response_ctx2>0)~=(labels>0))/length(labels);
fprintf(' Ctx2 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx2));
train_scores_ctx2(i_w,1) = 100*MR;
train_scores_ctx2(i_w,2) = compute_loss(current_response_ctx2);
train_scores_ctx2(i_w,3) = alpha_ctx2;
end
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
save('train_scores_sav.mat','train_scores','train_scores_ctx1','train_scores_ctx2');
if(i_w > 10)
% collect th colour value of the sample data
samp_rgb = zeros(size(samples_idx,1),3);
for i_img = 1 : size(data.train.(ch).X,1)
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
posi_samp = sub2ind(size(I(:,:,1)),samp_idx_img(:,2),samp_idx_img(:,3));
I = reshape(I,[],3);
samp_rgb(samples_idx == i_img,:) = I(posi_samp,:);
end
wltree = weak_learners(i_w).reg_tree;
[~,samp_lf] = predict_idx_wl(data,params,samples_idx,weak_learners(i_w));
lf_hist = histc(samp_lf,1:length(wltree));
lf_hist = lf_hist(1:length(wltree));
lf_hist = lf_hist / sum(lf_hist);
[lfn,lf_id] = sort(lf_hist,'descend');
lf_id(lfn < 0.3) = [];
lfn(lfn < 0.3) = [];
n_km = 30;
% for i_lf = 1 : length(lf_id)
%
% [~,ctx_km_c{i_lf}] = kmeans(samp_rgb(samp_lf == lf_id(i_lf),:),n_km,'EmptyAction','singleton');
%
% end
%
for i_n = 1 : length(wltree)
bkg_ftrs2{i_n} = [];
%bkg_idxs{i_n} = [];
end
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
[score_image,leaf_image] = predict_img_wl(X,params,weak_learners(i_w));
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
%context_img = zeros(size(leaf_image));
% cxt_idx = 1;
n_leaf = 0;
ctx_c1 = [];
ctx_c2 = [];
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
if(length(n_idx) / img_pg > 0.2)
I_2D = reshape(I,[],3);
n_idx = downsample(n_idx,1000);
bkg_ftrs2{i_n} = [ bkg_ftrs2{i_n}; I_2D(n_idx,:)];
end
end
end
% contx_list{i_w,i_img} = ctx_c2;
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
% ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
ctx_ftrs1(ctx_ftrs1 < 0.1) = 5000;
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
n_km = 30;
ctx_c2 = [];
clear ftrs_kmc_c2;
kmc_ctx_c2 = [];
tleaf_ctx_c2 = [];
for i_n = 1 : length(wltree)
if(~isempty(bkg_ftrs2{i_n}))
tStart = tic;
[~,ftrs_kmc_tmp] = kmeans(bkg_ftrs2{i_n},n_km,'EmptyAction','singleton');
t1 = toc(tStart);
fprintf('Clustering the context ftrs 2 took %d seconds', t1);
ctx_c2(end + 1 : end + n_km) = (100 * i_n) + (1:n_km);
ftrs_kmc{i_w,i_n} = ftrs_kmc_tmp;
kmc_ctx_c2(end + 1: end + n_km,:) = ftrs_kmc_tmp;
tleaf_ctx_c2(end + 1: end + n_km,:) = i_n;
else
ftrs_kmc{i_w,i_n} = {};
end
end
for i_img = 1 : size(data.train.(ch).X,1)
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
[~,leaf_image] = predict_img_wl(X,params,weak_learners(i_w));
ftrs2_img = zeros(size(leaf_image));
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
for i_n = 1 : length(wltree)
if(~isempty(ftrs_kmc{i_w,i_n}))
ftrs2_img_tmp = ftrs_c2_img(X,ftrs_kmc{i_w,i_n});
ftrs2_img = (i_n * 100 + ftrs2_img_tmp) .* (leaf_image == i_n);
end
end
for i_ctx = 1 : length(ctx_c2)
lf_ctx = (ftrs2_img == ctx_c2(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs2(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs2(:,i_ctx) = 5000;
end
end
ctx_ftrs2(ctx_ftrs2 < 0.1) = 5000;
ctx_ftrs2_w{i_w,i_img} = ctx_ftrs2;
% clear ctx_ftrs2;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_context_v8.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_context_v8.m
| 16,247 |
utf_8
|
db83495a2d7559523cf4feda14816fd3
|
% use the mask distance as well as the main branch distance
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx1] = train_boost_context_v8(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
W_ctx1 = W;
R_ctx1 = R;
n_km = 30;
% assign the weight for each individual data point
wgt_samp = zeros(size(samples_idx,1),1);
for i_img = 1 : length(data.train.gts.X)
gt_img = data.train.gts.X{i_img};
dist_gt = bwdist(gt_img);
idx_img = (samples_idx(:,1) == i_img);
samp_idx_img_2D = samples_idx(idx_img,2:3);
samp_idx_img_1D = sub2ind(size(gt_img),samp_idx_img_2D(:,1),samp_idx_img_2D(:,2));
wgt_img = dist_gt(samp_idx_img_1D);
wgt_img(wgt_img > 7) = 7;
wgt_img = wgt_img/ 7;
wgt_img(dist_gt(samp_idx_img_1D) < 0.3) = 1;
wgt_samp(idx_img) = wgt_img;
end
W = W .* wgt_samp;
W_ctx1 = W_ctx1 .* wgt_samp;
% W_ctx2 = W_ctx2 .* wgt_samp;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
ctx_ftrs1_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
if(isfield(params,'ctx1_tree_depth'))
tree_d_g = params.ctx1_tree_depth;
else
tree_d_g = params.tree_depth;
end
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(tree_d_g));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx1','weak_learners');
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
W = W .* wgt_samp;
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
W_ctx1 = W_ctx1 .* wgt_samp;
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
save([params.codename '_weak_learners_sav.mat'],'weak_learners','weak_learners_ctx1');
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
MR = sum(((current_response>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_w(i_w,1) = 100*MR;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum(((current_response_ctx1>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx1w(i_w,1) = 100*MR;
save([params.codename '_train_scores_sav_w.mat'],'train_scores_w','train_scores_ctx1w');
for i_img = 1 : length(data.train.gts.X)
img_idx = find(samples_idx(:,1) == i_img);
MR_img(i_w,i_img) = sum((current_response(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
MR_img_ctx1(i_w,i_img) = sum((current_response_ctx1(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
end
save([params.codename '_MR_sav.mat'],'MR_img','MR_img_ctx1');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx1');
end
if(i_w > 0)
% collect th colour value of the sample data
wltree = weak_learners(i_w).reg_tree;
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
mask_img = data.train.masks.X{i_img};
[mask_x,mask_y] = find(mask_img > 0);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),[mask_x,mask_y]);
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
n_leaf = 0;
ctx_c1 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
end
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
mask_img = data.train.masks.X{i_img};
dist_ctx_map = bwdist(~mask_img);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
known_mb = score_image > 0.5;
known_mb = filter_small_comp(known_mb,50);
known_mb = (dist_ctx_map > 10) .* known_mb;
dist_ctx_map = bwdist(known_mb);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_context_v6.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_context_v6.m
| 28,277 |
utf_8
|
af53953ab4065ff89b4a847d878f0501
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners] = train_boost_context_v6(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
% weak_learners(params.wl_no).alpha = 0;
%
% weak_learners_ctx1(params.wl_no).alpha = 0;
%
% weak_learners_ctx2(params.wl_no).alpha = 0;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
current_response_ctx2 = current_response;
W_ctx1 = W;
R_ctx1 = R;
W_ctx2 = W;
R_ctx2 = R;
%train_scores = zeros(params.wl_no,3);
%train_scores_ctx1 = zeros(params.wl_no,3);
%train_scores_ctx2 = zeros(params.wl_no,3);
n_km = 30;
% assign the weight for each individual data point
wgt_samp = zeros(size(samples_idx,1),1);
for i_img = 1 : length(data.train.gts.X)
gt_img = data.train.gts.X{i_img};
dist_gt = bwdist(gt_img);
idx_img = (samples_idx(:,1) == i_img);
samp_idx_img_2D = samples_idx(idx_img,2:3);
samp_idx_img_1D = sub2ind(size(gt_img),samp_idx_img_2D(:,1),samp_idx_img_2D(:,2));
wgt_img = dist_gt(samp_idx_img_1D);
wgt_img(wgt_img > 7) = 7;
wgt_img = wgt_img/ 7;
wgt_img(dist_gt(samp_idx_img_1D) < 0.3) = 1;
wgt_samp(idx_img) = wgt_img;
end
W = W .* wgt_samp;
W_ctx1 = W_ctx1 .* wgt_samp;
W_ctx2 = W_ctx2 .* wgt_samp;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
%save('tmp_ftrs.mat');
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
ctx_loc_all = zeros(size(samples_idx,1),n_ftrs2);
% save('tmp_ftrs.mat');
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
if(isempty(ctx_ftrs2_w{i_w - 1,i_img}))
save('empty_flag_sav.mat', ctx_ftrs2_w);
%ctx_loc_all(samples_idx(:,1) == i_img,:) = ones(sum(samples_idx(:,1) == i_img),n_km) * 5000;
else
ctx_loc_all(samples_idx(:,1) == i_img,:) = ctx_ftrs2_w{i_w - 1,i_img};
end
ctx_ftrs1_w{i_w - 1,i_img} = [];
ctx_ftrs2_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
ctx_loc = ctx_loc_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
if(isfield(params,'ctx1_tree_depth'))
tree_d_g = params.ctx1_tree_depth;
else
tree_d_g = params.tree_depth;
end
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(tree_d_g));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
% t_tr = tic;
% reg_tree_l = LDARegStumpTrain(single([features,ctx_loc]),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
% for i_img = 1 : size(data.train.(ch).X,1)
%
% T2_img = samples_idx(T2_idx,1) == i_img;
%
% ctx_loc_img = ctx_loc(T2_img,:);
%
% ctx_glb_img = ctx_glb(T2_img,:);
%
% fprintf(' Training regression tree %d on learned features combined with context 1 2...\n',i_img);
%
% t_tr = tic;
% reg_tree_l{i_img} = LDARegStumpTrain(single([features(T2_img,:),...
% ctx_glb_img,ctx_loc_img]),R(T2_idx(T2_img)),W(T2_idx(T2_img)) ...
% /sum(W(T2_idx((T2_img)))),...
% uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
%
% end
fprintf(' Training regression tree on learned features combined with context 1 2...\n');
t_tr = tic;
if(isfield(params,'ctx2_tree_depth'))
tree_d_l = params.ctx2_tree_depth;
else
tree_d_l = params.tree_depth;
end
reg_tree_l = LDARegStumpTrain(single([features,...
ctx_glb,ctx_loc]),R_ctx2(T2_idx),W_ctx2(T2_idx) ...
/sum(W_ctx2(T2_idx)),uint32(tree_d_l));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
[weak_learners_ctx2(i_w).kernels,weak_learners_ctx2(i_w).kernel_params,weak_learners_ctx2(i_w).reg_tree,...
weak_learners_ctx2(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_l,kernels,kernel_params);
ctx2_list = weak_learners_ctx2(i_w).ctx_list;
ctx2_list(ctx2_list < ncf_g + 1) = [];
ctx2_list = ctx2_list - ncf_g;
tmp_kmc = [];
tmp_ltree = [];
for i_km = 1 : length(ctx2_list)
tmp_kmc(i_km,:) = kmc_ctx_c2(ctx2_list(i_km),:);
tmp_ltree(i_km) = tleaf_ctx_c2(ctx2_list(i_km));
end
weak_learners_ctx2(i_w).kmc = tmp_kmc;
weak_learners_ctx2(i_w).ltree = tmp_ltree;
% ctx2_list = ctx2_list - ncf_g;
weak_learners_ctx2(i_w).ctx2_list = ctx2_list;
save('weak_learners_sav_July12.mat','weak_learners_ctx2','weak_learners_ctx1','weak_learners');
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
ctx_glb_all = [ctx_glb_all, ctx_loc_all];
clear ctx_loc_all;
features_ctx2 = ctx_glb_all(:,weak_learners_ctx2(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx2(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),...
weak_learners_ctx2(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx2(i_w).kernels(idxs),...
weak_learners_ctx2(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx2 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx2 = LDARegStumpPredict(...
weak_learners_ctx2(i_w).reg_tree,single([features, features_ctx2]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 features_ctx2 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
fprintf(' Finding alpha 2 through line search...\n');
t_alp = tic;
alpha_ctx2 = mexLineSearch(current_response_ctx2,cached_responses_ctx2,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx2,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
W = W .* wgt_samp;
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
W_ctx1 = W_ctx1 .* wgt_samp;
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
alpha_ctx2 = alpha_ctx2 * params.shrinkage_factor;
current_response_ctx2 = current_response_ctx2 + alpha_ctx2*cached_responses_ctx2;
W_ctx2 = compute_wi(current_response_ctx2);
W_ctx2 = W_ctx2 .* wgt_samp;
R_ctx2 = compute_ri(current_response_ctx2);
weak_learners_ctx2(i_w).alpha = alpha_ctx2;
save('weak_learners_sav.mat','weak_learners','weak_learners_ctx1','weak_learners_ctx1')
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
MR = sum(((current_response>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_w(i_w,1) = 100*MR;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum(((current_response_ctx1>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx1w(i_w,1) = 100*MR;
MR = sum((current_response_ctx2>0)~=(labels>0))/length(labels);
fprintf(' Ctx2 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx2));
train_scores_ctx2(i_w,1) = 100*MR;
train_scores_ctx2(i_w,2) = compute_loss(current_response_ctx2);
train_scores_ctx2(i_w,3) = alpha_ctx2;
MR = sum(((current_response_ctx2>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx2w(i_w,1) = 100*MR;
save('train_scores_sav_w.mat','train_scores_w','train_scores_ctx1w','train_scores_ctx2w');
for i_img = 1 : length(data.train.gts.X)
img_idx = find(samples_idx(:,1) == i_img);
MR_img(i_w,i_img) = sum((current_response(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
MR_img_ctx1(i_w,i_img) = sum((current_response_ctx1(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
end
save('MR_sav.mat','MR_img','MR_img_ctx1');
save('train_scores_sav.mat','train_scores','train_scores_ctx1','train_scores_ctx2');
end
if(i_w > 0)
% collect th colour value of the sample data
samp_rgb = zeros(size(samples_idx,1),3);
for i_img = 1 : size(data.train.(ch).X,1)
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
posi_samp = sub2ind(size(I(:,:,1)),samp_idx_img(:,2),samp_idx_img(:,3));
I = reshape(I,[],3);
samp_rgb(samples_idx == i_img,:) = I(posi_samp,:);
end
wltree = weak_learners(i_w).reg_tree;
[~,samp_lf] = predict_idx_wl(data,params,samples_idx,weak_learners(i_w));
lf_hist = histc(samp_lf,1:length(wltree));
lf_hist = lf_hist(1:length(wltree));
lf_hist = lf_hist / sum(lf_hist);
[lfn,lf_id] = sort(lf_hist,'descend');
lf_id(lfn < 0.3) = [];
lfn(lfn < 0.3) = [];
% for i_lf = 1 : length(lf_id)
%
% [~,ctx_km_c{i_lf}] = kmeans(samp_rgb(samp_lf == lf_id(i_lf),:),n_km,'EmptyAction','singleton');
%
% end
%
for i_n = 1 : length(wltree)
bkg_ftrs2{i_n} = [];
%bkg_idxs{i_n} = [];
end
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
%context_img = zeros(size(leaf_image));
% cxt_idx = 1;
n_leaf = 0;
ctx_c1 = [];
ctx_c2 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
if(length(n_idx) / n_samp_img > 0.2)
I_2D = reshape(I,[],3);
n_idx = downsample(n_idx,200);
bkg_ftrs2{i_n} = [ bkg_ftrs2{i_n}; I_2D(n_idx,:)];
end
end
end
% contx_list{i_w,i_img} = ctx_c2;
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
% ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
% ctx_ftrs1(ctx_ftrs1 < 0.1) = 5000;
mask_img = data.train.masks.X{i_img};
dist_ctx_map = bwdist(~mask_img);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
n_km = 30;
ctx_c2 = [];
clear ftrs_kmc_c2;
kmc_ctx_c2 = [];
tleaf_ctx_c2 = [];
for i_n = 1 : length(wltree)
if(~isempty(bkg_ftrs2{i_n}))
tStart = tic;
[~,ftrs_kmc_tmp] = kmeans(bkg_ftrs2{i_n},n_km,'EmptyAction','singleton');
t1 = toc(tStart);
fprintf('Clustering the context ftrs 2 took %d seconds', t1);
ctx_c2(end + 1 : end + n_km) = (100 * i_n) + (1:n_km);
ftrs_kmc{i_w,i_n} = ftrs_kmc_tmp;
kmc_ctx_c2(end + 1: end + n_km,:) = ftrs_kmc_tmp;
tleaf_ctx_c2(end + 1: end + n_km,:) = i_n;
else
ftrs_kmc{i_w,i_n} = {};
end
end
n_ftrs2 = length(ctx_c2);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_ftrs2_w{i_w,i_img} = [];
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
ftrs2_img = zeros(size(leaf_image));
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
for i_n = 1 : length(wltree)
if(~isempty(ftrs_kmc{i_w,i_n}))
ftrs2_img_tmp = ftrs_c2_img(X,ftrs_kmc{i_w,i_n});
ftrs2_img = (i_n * 100 + ftrs2_img_tmp);
% ftrs2_img = (i_n * 100 + ftrs2_img_tmp) .* (leaf_image == i_n);
end
end
for i_ctx = 1 : length(ctx_c2)
tStart = tic;
lf_ctx = (ftrs2_img == ctx_c2(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs2(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs2(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% ctx_ftrs2(ctx_ftrs2 < 0.1) = 5000;
ctx_ftrs2_w{i_w,i_img} = ctx_ftrs2;
% clear ctx_ftrs2;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_LTM_validation_3D.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_LTM_validation_3D.m
| 7,392 |
utf_8
|
ed681933bec2d489d679a407dac8bb0f
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,train_scores] = train_LTM_validation_3D(params,fn,ftrs,wgt,samples_idx)
% Train a KernelBoost classifier on the given samples
% the classifier combine the added discriptor
% allows an additional weight, i.e. assign the weight according to the
% number of pixels consisted in the seed
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
weak_learners(params.wl_no).alpha = 0;
labels = samples_idx(:,5);
samples_idx = samples_idx(:,1:4);
samples_idx(:,2:3) = samples_idx(:,2:3) + params.border_size;
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
W = W .* wgt;
R = compute_ri(current_response);
train_scores = zeros(params.wl_no,4);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = import_3D_data_v2(fn.train.imgs.X(1,:));
% for i_img = 1 : length(data.train.(ch).X)
%
% X{i_img,1} = sum(data.train.(ch).X{i_img},3);
%
% end
%X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = 1;
sub_ch_no = data.train.(ch).sub_ch_no;
sub_ch_no = 1;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
% add the histogram discriptor
ftrs1 = ftrs(T2_idx,:);
features = [features,ftrs1];
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree...
] = remove_useless_filters_ftrs(reg_tree,kernels,kernel_params);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
sub_ch_no = 1;
% X = data.train.(ch).X(:,data.train.(ch).idxs);
X = expand_img_v3(data.train.(ch).X,params);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
% idxs = 1;
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
% add the hd feature
features = [features,ftrs];
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
% incorperate the weight
W = W .* wgt;
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
WMR = sum(((current_response>0)~=(labels>0)) .* wgt )/sum(wgt);
fprintf(' Weighted Misclassif rate: %.2f | Loss: %f\n',100*WMR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
train_scores(i_w,4) = 100 * WMR;
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
figure(4);
plot(1:params.wl_no,train_scores(:,4),'r');
legend('WMR');
saveas(gcf,fullfile(params.results_dir,'Weighted_MR_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_ctx_ac_v2.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_ctx_ac_v2.m
| 6,845 |
utf_8
|
074895ccf168b760b801b029f0a692d2
|
% use the mask distance as well as the main branch distance
% eavluate the effect of auto context
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx,weak_learners_ac] = train_boost_ctx_ac_v2(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ac = current_response;
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
% load the training images
X = data.train.imgs.X(:,data.train.imgs.idxs);
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W,R);
cached_responses = evaluate_weak_learners(X,params,samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
%%%%%% train the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
if(i_w > 1)
% in this step, apply the auto context feature learning
X_ac = X;
for i_img = 1 : size(X,1)
X_ac{i_img,size(X,2) + 1} = ac_ftrs{i_img};
end
[weak_learners_ac(i_w).kernels,weak_learners_ac(i_w).kernel_params,...
weak_learners_ac(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W_ac,R_ac);
cached_responses_ac = evaluate_weak_learners(X_ac,params,samples_idx,weak_learners_ac(i_w));
weak_learners_ac(i_w).alpha = search_alpha(current_response_ac,cached_responses_ac,labels,params);
current_response_ac = current_response_ac + weak_learners_ac(i_w).alpha * cached_responses_ac;
W_ac = compute_wi(current_response_ac);
R_ac = compute_ri(current_response_ac);
train_scores_ac(i_w,:) = weak_learner_scores(current_response_ac,labels,wgt_samp,compute_loss);
else
for i_img = 1 : size(X,1)
ac_ftrs{i_img} = zeros(size(X{i_img,1}));
end
end
%%%%%% Complete training the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
%%%%%%%%%%%% start training the ctx augmented weak learners%%%%%%%%%
if(i_w > 1)
% load the global context features
[weak_learners_ctx(i_w).kernels,weak_learners_ctx(i_w).kernel_params,...
weak_learners_ctx(i_w).reg_tree, weak_learners_ctx(i_w).ctx_list]...
= train_kernel_boost_ctx(X,params,ctx_glb_all,...
samples_idx,T1_idx,T2_idx,W_ctx,R_ctx);
% now the context feature is a subset of the full context features
weak_learners_ctx(i_w).ctx_lf_list = ctx_lf_list;
% this version simply ignores the ctx_list assigned by the previous
% method
% weak_learners_ctx(i_w).ctx_list = ctx_list;
weak_learners_ctx(i_w).ctx_latent = ctx_list_latent;
cached_responses_ctx = evaluate_weak_learners_ctx(X,params,ctx_glb_all,samples_idx,weak_learners_ctx(i_w));
weak_learners_ctx(i_w).alpha = search_alpha(current_response_ctx,cached_responses_ctx,labels,params);
current_response_ctx = current_response_ctx + weak_learners_ctx(i_w).alpha * cached_responses_ctx;
W_ctx = compute_wi(current_response_ctx);
R_ctx = compute_ri(current_response_ctx);
train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx','weak_learners','weak_learners_ac');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx','train_scores_ac');
end
% collect the succesful new region
if(i_w > 1)
for i_img = 1 : size(X,1)
sub_rg{i_img} = sub_rg{i_img} + sub_region_img{i_img};
end
else
for i_img = 1 : size(X,1)
sub_rg{i_img} = zeros(size(X{i_img,1}));
end
end
% save([params.codename '_sub_region_train.mat'],'sub_rg');
%%%% complete training the global context feature weak learners
% collect the global features as well as auto context features, be aware
% of the global features, they are only prepared for the next round, so
% this part should be behind the context and auto context learning
[ctx_glb_all,ac_ftrs,ctx_lf_list,ctx_list_latent,sub_region_img] = collect_global_ctx_adv(X,data.train.gts,data.train.masks,...
params,weak_learners(i_w),samples_idx,ac_ftrs);
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_ctx_debug.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_ctx_debug.m
| 17,266 |
utf_8
|
e04fe67438959b8d920c36c60326a167
|
% use the mask distance as well as the main branch distance
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx1] = train_boost_ctx_debug(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
W_ctx1 = W;
R_ctx1 = R;
n_km = 30;
% assign the weight for each individual data point
wgt_samp = zeros(size(samples_idx,1),1);
tol_z_wgt = params.tol_z_wgt;
fig_thres = params.fig_thres;
if(~isfield(params,'weight_invariance'))
params.weight_invariance = 0;
end
w_invar = params.weight_invariance;
for i_img = 1 : length(data.train.gts.X)
gt_img = data.train.gts.X{i_img};
dist_gt = bwdist(gt_img);
idx_img = (samples_idx(:,1) == i_img);
samp_idx_img_2D = samples_idx(idx_img,2:3);
samp_idx_img_1D = sub2ind(size(gt_img),samp_idx_img_2D(:,1),samp_idx_img_2D(:,2));
wgt_img = dist_gt(samp_idx_img_1D);
wgt_img(wgt_img > tol_z_wgt) = tol_z_wgt;
wgt_img = wgt_img/ tol_z_wgt;
wgt_img(dist_gt(samp_idx_img_1D) < 0.3) = 1;
wgt_samp(idx_img) = wgt_img;
end
W = W .* wgt_samp;
W_ctx1 = W_ctx1 .* wgt_samp;
if(w_invar)
W_init = W;
end
% W_ctx2 = W_ctx2 .* wgt_samp;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
if(w_invar)
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression...
(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,W_init(wr_idxs),i_ch,i_s,ch);
else
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression...
(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
end
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
ctx_ftrs1_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
if(isfield(params,'ctx1_tree_depth'))
tree_d_g = params.ctx1_tree_depth;
else
tree_d_g = params.tree_depth;
end
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(tree_d_g));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx1','weak_learners');
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
% only for the sake of debugging the function
save('tmp_debug.mat');
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
W = W .* wgt_samp;
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
W_ctx1 = W_ctx1 .* wgt_samp;
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
save([params.codename '_weak_learners_sav.mat'],'weak_learners','weak_learners_ctx1');
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
MR = sum(((current_response>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_w(i_w,1) = 100*MR;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum(((current_response_ctx1>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx1w(i_w,1) = 100*MR;
save([params.codename '_train_scores_sav_w.mat'],'train_scores_w','train_scores_ctx1w');
for i_img = 1 : length(data.train.gts.X)
img_idx = find(samples_idx(:,1) == i_img);
MR_img(i_w,i_img) = sum((current_response(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
MR_img_ctx1(i_w,i_img) = sum((current_response_ctx1(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
end
save([params.codename '_MR_sav.mat'],'MR_img','MR_img_ctx1');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx1');
end
if(i_w > 0)
% collect th colour value of the sample data
wltree = weak_learners(i_w).reg_tree;
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
mask_img = data.train.masks.X{i_img};
[mask_x,mask_y] = find(mask_img > 0);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),[mask_x,mask_y]);
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
n_leaf = 0;
ctx_c1 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
end
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
mask_img = data.train.masks.X{i_img};
dist_ctx_map = bwdist(~mask_img);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
known_mb = score_image > fig_thres;
known_mb = (bwdist(~mask_img) > 10) .* known_mb;
if(sum(known_mb(:)))
dist_ctx_map = bwdist(known_mb);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,end + 1) = 5000;
end
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_ctx_latent_img.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_ctx_latent_img.m
| 6,404 |
utf_8
|
841e2c372107c2f583b349576c351b15
|
% use the mask distance as well as the main branch distance
% collect the latent label
% eavluate the effect of auto context
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx,weak_learners_ac] = train_boost_ctx_latent_img(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ac = current_response;
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
% load the training images
X = data.train.imgs.X(:,data.train.imgs.idxs);
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W,R);
cached_responses = evaluate_weak_learners(X,params,samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
%%%%%% train the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
if(i_w > 1)
% in this step, apply the auto context feature learning
X_ac = X;
for i_img = 1 : size(X,1)
X_ac{i_img,size(X,2) + 1} = ac_ftrs{i_img};
end
[weak_learners_ac(i_w).kernels,weak_learners_ac(i_w).kernel_params,...
weak_learners_ac(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W_ac,R_ac);
cached_responses_ac = evaluate_weak_learners(X_ac,params,samples_idx,weak_learners_ac(i_w));
weak_learners_ac(i_w).alpha = search_alpha(current_response_ac,cached_responses_ac,labels,params);
current_response_ac = current_response_ac + weak_learners_ac(i_w).alpha * cached_responses_ac;
W_ac = compute_wi(current_response_ac);
R_ac = compute_ri(current_response_ac);
train_scores_ac(i_w,:) = weak_learner_scores(current_response_ac,labels,wgt_samp,compute_loss);
else
for i_img = 1 : size(X,1)
ac_ftrs{i_img} = zeros(size(X{i_img,1}));
end
end
%%%%%% Complete training the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
%%%%%%%%%%%% start training the ctx augmented weak learners%%%%%%%%%
if(i_w > 1)
% load the global context features
[weak_learners_ctx(i_w).kernels,weak_learners_ctx(i_w).kernel_params,...
weak_learners_ctx(i_w).reg_tree, weak_learners_ctx(i_w).ctx_list]...
= train_kernel_boost_ctx(X,params,ctx_glb_all,...
samples_idx,T1_idx,T2_idx,W_ctx,R_ctx);
% now the context feature is a subset of the full context features
weak_learners_ctx(i_w).ctx_lf_list = ctx_lf_list;
% this version simply ignores the ctx_list assigned by the previous
% method
% weak_learners_ctx(i_w).ctx_list = ctx_list;
weak_learners_ctx(i_w).ctx_latent = ctx_list_latent;
cached_responses_ctx = evaluate_weak_learners_ctx(X,params,ctx_glb_all,samples_idx,weak_learners_ctx(i_w));
weak_learners_ctx(i_w).alpha = search_alpha(current_response_ctx,cached_responses_ctx,labels,params);
current_response_ctx = current_response_ctx + weak_learners_ctx(i_w).alpha * cached_responses_ctx;
W_ctx = compute_wi(current_response_ctx);
R_ctx = compute_ri(current_response_ctx);
train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx','weak_learners','weak_learners_ac');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx','train_scores_ac');
end
%%%% complete training the global context feature weak learners
% collect the global features as well as auto context features, be aware
% of the global features, they are only prepared for the next round, so
% this part should be behind the context and auto context learning
[ctx_glb_all,ac_ftrs,ctx_lf_list,ctx_list_latent,sub_region_img] = collect_global_ctx_latent(X,data.train.gts,data.train.masks,...
params,weak_learners(i_w),samples_idx,ac_ftrs);
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_lat_img_node_dist.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_lat_img_node_dist.m
| 9,152 |
utf_8
|
8b1524b85dff52bd2f964deacefc5bd1
|
% use the mask distance as well as the main branch distance
% collect the latent label
% eavluate the effect of auto context
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx,weak_learners_ac] = train_boost_lat_img_node_dist(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ac = current_response;
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
% load the training images
X = data.train.imgs.X(:,data.train.imgs.idxs);
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W,R);
cached_responses = evaluate_weak_learners(X,params,samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
%%%%%% train the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
% if(i_w > 1)
%
% % in this step, apply the auto context feature learning
%
% X_ac = X;
%
% for i_img = 1 : size(X,1)
%
% X_ac{i_img,size(X,2) + 1} = ac_ftrs{i_img};
%
% end
%
% [weak_learners_ac(i_w).kernels,weak_learners_ac(i_w).kernel_params,...
% weak_learners_ac(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W_ac,R_ac);
%
% cached_responses_ac = evaluate_weak_learners(X_ac,params,samples_idx,weak_learners_ac(i_w));
%
% weak_learners_ac(i_w).alpha = search_alpha(current_response_ac,cached_responses_ac,labels,params);
%
% current_response_ac = current_response_ac + weak_learners_ac(i_w).alpha * cached_responses_ac;
%
% W_ac = compute_wi(current_response_ac);
%
% R_ac = compute_ri(current_response_ac);
%
% train_scores_ac(i_w,:) = weak_learner_scores(current_response_ac,labels,wgt_samp,compute_loss);
%
% else
%
% for i_img = 1 : size(X,1)
%
% ac_ftrs{i_img} = zeros(size(X{i_img,1}));
%
% end
%
% end
%%%%%% Complete training the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
% %%%%%%%%%%%% start training the ctx augmented weak learners%%%%%%%%%
%
% if(i_w > 1)
%
% % load the global context features
%
%
% [weak_learners_ctx(i_w).kernels,weak_learners_ctx(i_w).kernel_params,...
% weak_learners_ctx(i_w).reg_tree, weak_learners_ctx(i_w).ctx_list]...
% = train_kernel_boost_ctx(X,params,ctx_glb_all,...
% samples_idx,T1_idx,T2_idx,W_ctx,R_ctx);
%
% % now the context feature is a subset of the full context features
%
% weak_learners_ctx(i_w).ctx_lf_list = ctx_lf_list;
%
% % this version simply ignores the ctx_list assigned by the previous
% % method
%
% % weak_learners_ctx(i_w).ctx_list = ctx_list;
%
%
% weak_learners_ctx(i_w).ctx_latent = ctx_list_latent;
%
% cached_responses_ctx = evaluate_weak_learners_ctx(X,params,ctx_glb_all,samples_idx,weak_learners_ctx(i_w));
%
% weak_learners_ctx(i_w).alpha = search_alpha(current_response_ctx,cached_responses_ctx,labels,params);
%
% current_response_ctx = current_response_ctx + weak_learners_ctx(i_w).alpha * cached_responses_ctx;
%
% W_ctx = compute_wi(current_response_ctx);
%
% R_ctx = compute_ri(current_response_ctx);
%
% train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx,labels,wgt_samp,compute_loss);
%
%
% save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx','weak_learners','weak_learners_ac');
%
% save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx','train_scores_ac');
%
%
% end
%%%% complete training the global context feature weak learners
% collect the global features as well as auto context features, be aware
% of the global features, they are only prepared for the next round, so
% this part should be behind the context and auto context learning
ln_idx_imgs{i_w} = collect_node_dist_latent_img(X,data.train.masks,...
params,weak_learners(i_w));
if(i_w > 5)
for i_img = 1 : 20
for i_w1 = 1 : i_w
lf_label_img{i_w1} = zeros([size(X{i_img,1}) length(ln_idx_imgs{i_w1}{i_img})]);
for i_l1 = 1 : length(ln_idx_imgs{i_w1}{i_img})
tmp_lf = zeros(size(X{i_img,1}));
tmp_lf(ln_idx_imgs{i_w1}{i_img}{i_l1}) = 1;
lf_label_img{i_w1}(:,:,i_l1) = tmp_lf;
end
end
lf_l = [];
optd = lf_label_img{i_w1}(:,:,6);
for i_w1 = 1 : i_w
for i_l1 = 1 : size(lf_label_img{i_w1},3)
lf_img1 = lf_label_img{i_w1}(:,:,i_l1);
n_l1{i_w1,i_l1} = sum(lf_img1(:));
for i_w2 = 1 : i_w
for i_l2 = 1 : size(lf_label_img{i_w2},3)
lf_img2 = lf_label_img{i_w2}(:,:,i_l2);
n_ol{i_w1,i_l1}(i_w2,i_l2) = sum(lf_img1(:) .* lf_img2(:));
uoa_l{i_w1,i_l1}(i_w2,i_l2) = sum(lf_img1(:) .* lf_img2(:)) ./...
sum((lf_img1(:) + lf_img2(:)) > 0);
end
end
end
end
for i_w1 = 1 : i_w
% for i_l1 = 1 :
for i_l1 = 1: size(lf_label_img{i_w1},3)
ol_lf_l{i_w1}(:,:,i_l1) = optd .* lf_label_img{i_w1}(:,:,i_l1);
n_ol{i_w1}(i_l1) = sum(sum(optd .* lf_label_img{i_w1}(:,:,i_l1)));
end
end
end
end
% [ctx_glb_all,ac_ftrs,ctx_lf_list,ctx_list_latent,sub_region_img] = ...
% collect_global_ctx_latent(X,data.train.gts,data.train.masks,...
% params,weak_learners(i_w),samples_idx,ac_ftrs);
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_context_v2.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_context_v2.m
| 25,632 |
utf_8
|
3b1cd934b09cd47ddf2c794aab407783
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners] = train_boost_context_v2(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
% weak_learners(params.wl_no).alpha = 0;
%
% weak_learners_ctx1(params.wl_no).alpha = 0;
%
% weak_learners_ctx2(params.wl_no).alpha = 0;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
current_response_ctx2 = current_response;
W_ctx1 = W;
R_ctx1 = R;
W_ctx2 = W;
R_ctx2 = R;
train_scores = zeros(params.wl_no,3);
train_scores_ctx1 = zeros(params.wl_no,3);
train_scores_ctx2 = zeros(params.wl_no,3);
n_km = 30;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
%save('tmp_ftrs.mat');
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
ctx_loc_all = zeros(size(samples_idx,1),n_ftrs2);
save('tmp_ftrs.mat');
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
if(isempty(ctx_ftrs2_w{i_w - 1,i_img}))
save('empty_flag_sav.mat', ctx_ftrs2_w);
%ctx_loc_all(samples_idx(:,1) == i_img,:) = ones(sum(samples_idx(:,1) == i_img),n_km) * 5000;
else
ctx_loc_all(samples_idx(:,1) == i_img,:) = ctx_ftrs2_w{i_w - 1,i_img};
end
ctx_ftrs1_w{i_w - 1,i_img} = [];
ctx_ftrs2_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
ctx_loc = ctx_loc_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
% t_tr = tic;
% reg_tree_l = LDARegStumpTrain(single([features,ctx_loc]),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
% for i_img = 1 : size(data.train.(ch).X,1)
%
% T2_img = samples_idx(T2_idx,1) == i_img;
%
% ctx_loc_img = ctx_loc(T2_img,:);
%
% ctx_glb_img = ctx_glb(T2_img,:);
%
% fprintf(' Training regression tree %d on learned features combined with context 1 2...\n',i_img);
%
% t_tr = tic;
% reg_tree_l{i_img} = LDARegStumpTrain(single([features(T2_img,:),...
% ctx_glb_img,ctx_loc_img]),R(T2_idx(T2_img)),W(T2_idx(T2_img)) ...
% /sum(W(T2_idx((T2_img)))),...
% uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
%
% end
fprintf(' Training regression tree on learned features combined with context 1 2...\n');
t_tr = tic;
reg_tree_l = LDARegStumpTrain(single([features,...
ctx_glb,ctx_loc]),R_ctx2(T2_idx),W_ctx2(T2_idx) ...
/sum(W_ctx2(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
[weak_learners_ctx2(i_w).kernels,weak_learners_ctx2(i_w).kernel_params,weak_learners_ctx2(i_w).reg_tree,...
weak_learners_ctx2(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_l,kernels,kernel_params);
ctx2_list = weak_learners_ctx2(i_w).ctx_list;
ctx2_list(ctx2_list < ncf_g + 1) = [];
ctx2_list = ctx2_list - ncf_g;
tmp_kmc = [];
tmp_ltree = [];
for i_km = 1 : length(ctx2_list)
tmp_kmc(i_km,:) = kmc_ctx_c2(ctx2_list(i_km),:);
tmp_ltree(i_km) = tleaf_ctx_c2(ctx2_list(i_km));
end
weak_learners_ctx2(i_w).kmc = tmp_kmc;
weak_learners_ctx2(i_w).ltree = tmp_ltree;
% ctx2_list = ctx2_list - ncf_g;
weak_learners_ctx2(i_w).ctx2_list = ctx2_list;
save('weak_learners_sav.mat','weak_learners_ctx2','weak_learners_ctx1','weak_learners');
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
ctx_glb_all = [ctx_glb_all, ctx_loc_all];
clear ctx_loc_all;
features_ctx2 = ctx_glb_all(:,weak_learners_ctx2(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx2(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),...
weak_learners_ctx2(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx2(i_w).kernels(idxs),...
weak_learners_ctx2(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx2 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx2 = LDARegStumpPredict(...
weak_learners_ctx2(i_w).reg_tree,single([features, features_ctx2]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 features_ctx2 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
fprintf(' Finding alpha 2 through line search...\n');
t_alp = tic;
alpha_ctx2 = mexLineSearch(current_response_ctx2,cached_responses_ctx2,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx2,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
alpha_ctx2 = alpha_ctx2 * params.shrinkage_factor;
current_response_ctx2 = current_response_ctx2 + alpha_ctx2*cached_responses_ctx2;
W_ctx2 = compute_wi(current_response_ctx2);
R_ctx2 = compute_ri(current_response_ctx2);
weak_learners_ctx2(i_w).alpha = alpha_ctx2;
save('weak_learners_sav.mat','weak_learners','weak_learners_ctx1','weak_learners_ctx1')
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum((current_response_ctx2>0)~=(labels>0))/length(labels);
fprintf(' Ctx2 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx2));
train_scores_ctx2(i_w,1) = 100*MR;
train_scores_ctx2(i_w,2) = compute_loss(current_response_ctx2);
train_scores_ctx2(i_w,3) = alpha_ctx2;
end
save('train_scores_sav.mat','train_scores','train_scores_ctx1','train_scores_ctx2');
if(i_w > 0)
% collect th colour value of the sample data
samp_rgb = zeros(size(samples_idx,1),3);
for i_img = 1 : size(data.train.(ch).X,1)
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
posi_samp = sub2ind(size(I(:,:,1)),samp_idx_img(:,2),samp_idx_img(:,3));
I = reshape(I,[],3);
samp_rgb(samples_idx == i_img,:) = I(posi_samp,:);
end
wltree = weak_learners(i_w).reg_tree;
[~,samp_lf] = predict_idx_wl(data,params,samples_idx,weak_learners(i_w));
lf_hist = histc(samp_lf,1:length(wltree));
lf_hist = lf_hist(1:length(wltree));
lf_hist = lf_hist / sum(lf_hist);
[lfn,lf_id] = sort(lf_hist,'descend');
lf_id(lfn < 0.3) = [];
lfn(lfn < 0.3) = [];
% for i_lf = 1 : length(lf_id)
%
% [~,ctx_km_c{i_lf}] = kmeans(samp_rgb(samp_lf == lf_id(i_lf),:),n_km,'EmptyAction','singleton');
%
% end
%
for i_n = 1 : length(wltree)
bkg_ftrs2{i_n} = [];
%bkg_idxs{i_n} = [];
end
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
%context_img = zeros(size(leaf_image));
% cxt_idx = 1;
n_leaf = 0;
ctx_c1 = [];
ctx_c2 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
if(length(n_idx) / n_samp_img > 0.2)
I_2D = reshape(I,[],3);
n_idx = downsample(n_idx,200);
bkg_ftrs2{i_n} = [ bkg_ftrs2{i_n}; I_2D(n_idx,:)];
end
end
end
% contx_list{i_w,i_img} = ctx_c2;
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
% ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
ctx_ftrs1(ctx_ftrs1 < 0.1) = 5000;
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
n_km = 30;
ctx_c2 = [];
clear ftrs_kmc_c2;
kmc_ctx_c2 = [];
tleaf_ctx_c2 = [];
for i_n = 1 : length(wltree)
if(~isempty(bkg_ftrs2{i_n}))
tStart = tic;
[~,ftrs_kmc_tmp] = kmeans(bkg_ftrs2{i_n},n_km,'EmptyAction','singleton');
t1 = toc(tStart);
fprintf('Clustering the context ftrs 2 took %d seconds', t1);
ctx_c2(end + 1 : end + n_km) = (100 * i_n) + (1:n_km);
ftrs_kmc{i_w,i_n} = ftrs_kmc_tmp;
kmc_ctx_c2(end + 1: end + n_km,:) = ftrs_kmc_tmp;
tleaf_ctx_c2(end + 1: end + n_km,:) = i_n;
else
ftrs_kmc{i_w,i_n} = {};
end
end
n_ftrs2 = length(ctx_c2);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_ftrs2_w{i_w,i_img} = [];
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
ftrs2_img = zeros(size(leaf_image));
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
for i_n = 1 : length(wltree)
if(~isempty(ftrs_kmc{i_w,i_n}))
ftrs2_img_tmp = ftrs_c2_img(X,ftrs_kmc{i_w,i_n});
ftrs2_img = (i_n * 100 + ftrs2_img_tmp) .* (leaf_image == i_n);
end
end
for i_ctx = 1 : length(ctx_c2)
tStart = tic;
lf_ctx = (ftrs2_img == ctx_c2(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs2(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs2(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
ctx_ftrs2(ctx_ftrs2 < 0.1) = 5000;
ctx_ftrs2_w{i_w,i_img} = ctx_ftrs2;
% clear ctx_ftrs2;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_3D_CLRG_combined.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_3D_CLRG_combined.m
| 7,462 |
utf_8
|
645b471aa41ba66468a056e0ed21fb45
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,train_scores] = train_boost_3D_CLRG_combined(params,data,ftrs,wgt,samples_idx,LTClassifier)
% Train a KernelBoost classifier on the given samples
% the classifier combine the added discriptor
% allows an additional weight, i.e. assign the weight according to the
% number of pixels consisted in the seed
% works on 3D iamge, in accordance with the paper, combine with a CLRG tree
% classifier
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
weak_learners(params.wl_no).alpha = 0;
labels = samples_idx(:,5);
samples_idx = samples_idx(:,1:4);
samples_idx(:,2:3) = samples_idx(:,2:3) + params.border_size;
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
W = W .* wgt;
R = compute_ri(current_response);
train_scores = zeros(params.wl_no,4);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = expand_img(data.train.(ch).X,params);
% for i_img = 1 : length(data.train.(ch).X)
%
% X{i_img,1} = sum(data.train.(ch).X{i_img},3);
%
% end
%X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = 1;
sub_ch_no = data.train.(ch).sub_ch_no;
sub_ch_no = 1;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
% add the histogram discriptor
ftrs1 = ftrs(T2_idx,:);
features = [features,ftrs1];
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree...
] = remove_useless_filters_ftrs(reg_tree,kernels,kernel_params);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
sub_ch_no = 1;
% X = data.train.(ch).X(:,data.train.(ch).idxs);
X = expand_img(data.train.(ch).X,params);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
% idxs = 1;
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
% add the hd feature
features = [features,ftrs];
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
% incorperate the weight
W = W .* wgt;
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
WMR = sum(((current_response>0)~=(labels>0)) .* wgt )/sum(wgt);
fprintf(' Weighted Misclassif rate: %.2f | Loss: %f\n',100*WMR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
train_scores(i_w,4) = 100 * WMR;
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
figure(4);
plot(1:params.wl_no,train_scores(:,4),'r');
legend('WMR');
saveas(gcf,fullfile(params.results_dir,'Weighted_MR_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_ctx.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_ctx.m
| 17,147 |
utf_8
|
33c735dea4921d444df3d77daea1f804
|
% use the mask distance as well as the main branch distance
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx1] = train_boost_ctx(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
W_ctx1 = W;
R_ctx1 = R;
n_km = 30;
% assign the weight for each individual data point
wgt_samp = zeros(size(samples_idx,1),1);
tol_z_wgt = params.tol_z_wgt;
fig_thres = params.fig_thres;
if(~isfield(params,'weight_invariance'))
params.weight_invariance = 0;
end
w_invar = params.weight_invariance;
for i_img = 1 : length(data.train.gts.X)
gt_img = data.train.gts.X{i_img};
dist_gt = bwdist(gt_img);
idx_img = (samples_idx(:,1) == i_img);
samp_idx_img_2D = samples_idx(idx_img,2:3);
samp_idx_img_1D = sub2ind(size(gt_img),samp_idx_img_2D(:,1),samp_idx_img_2D(:,2));
wgt_img = dist_gt(samp_idx_img_1D);
wgt_img(wgt_img > tol_z_wgt) = tol_z_wgt;
wgt_img = wgt_img/ tol_z_wgt;
wgt_img(dist_gt(samp_idx_img_1D) < 0.3) = 1;
wgt_samp(idx_img) = wgt_img;
end
W = W .* wgt_samp;
W_ctx1 = W_ctx1 .* wgt_samp;
if(w_invar)
W_init = W;
end
% W_ctx2 = W_ctx2 .* wgt_samp;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
if(w_invar)
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression...
(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,W_init(wr_idxs),i_ch,i_s,ch);
else
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression...
(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
end
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
ctx_ftrs1_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
if(isfield(params,'ctx1_tree_depth'))
tree_d_g = params.ctx1_tree_depth;
else
tree_d_g = params.tree_depth;
end
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(tree_d_g));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx1','weak_learners');
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
W = W .* wgt_samp;
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
W_ctx1 = W_ctx1 .* wgt_samp;
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
save([params.codename '_weak_learners_sav.mat'],'weak_learners','weak_learners_ctx1');
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
MR = sum(((current_response>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_w(i_w,1) = 100*MR;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum(((current_response_ctx1>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx1w(i_w,1) = 100*MR;
save([params.codename '_train_scores_sav_w.mat'],'train_scores_w','train_scores_ctx1w');
for i_img = 1 : length(data.train.gts.X)
img_idx = find(samples_idx(:,1) == i_img);
MR_img(i_w,i_img) = sum((current_response(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
MR_img_ctx1(i_w,i_img) = sum((current_response_ctx1(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
end
save([params.codename '_MR_sav.mat'],'MR_img','MR_img_ctx1');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx1');
end
if(i_w > 0)
% collect th colour value of the sample data
wltree = weak_learners(i_w).reg_tree;
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
mask_img = data.train.masks.X{i_img};
[mask_x,mask_y] = find(mask_img > 0);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),[mask_x,mask_y]);
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
n_leaf = 0;
ctx_c1 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
end
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
mask_img = data.train.masks.X{i_img};
dist_ctx_map = bwdist(~mask_img);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
known_mb = score_image > fig_thres;
known_mb = (bwdist(~mask_img) > 10) .* known_mb;
if(sum(known_mb(:)))
dist_ctx_map = bwdist(known_mb);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,end + 1) = 5000;
end
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_weight_3D.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_weight_3D.m
| 7,356 |
utf_8
|
838979308d182708f995a8a848328582
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,train_scores] = train_boost_weight_3D(params,data,ftrs,wgt,samples_idx)
% Train a KernelBoost classifier on the given samples
% the classifier combine the added discriptor
% allows an additional weight, i.e. assign the weight according to the
% number of pixels consisted in the seed
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
weak_learners(params.wl_no).alpha = 0;
labels = samples_idx(:,5);
samples_idx = samples_idx(:,1:4);
samples_idx(:,2:3) = samples_idx(:,2:3) + params.border_size;
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
W = W .* wgt;
R = compute_ri(current_response);
train_scores = zeros(params.wl_no,4);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = expand_img_v3(data.train.(ch).X,params);
% for i_img = 1 : length(data.train.(ch).X)
%
% X{i_img,1} = sum(data.train.(ch).X{i_img},3);
%
% end
%X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = 1;
sub_ch_no = data.train.(ch).sub_ch_no;
sub_ch_no = 1;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
% add the histogram discriptor
ftrs1 = ftrs(T2_idx,:);
features = [features,ftrs1];
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree...
] = remove_useless_filters_ftrs(reg_tree,kernels,kernel_params);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
sub_ch_no = 1;
% X = data.train.(ch).X(:,data.train.(ch).idxs);
X = expand_img_v3(data.train.(ch).X,params);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
% idxs = 1;
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
% add the hd feature
features = [features,ftrs];
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
% incorperate the weight
W = W .* wgt;
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
WMR = sum(((current_response>0)~=(labels>0)) .* wgt )/sum(wgt);
fprintf(' Weighted Misclassif rate: %.2f | Loss: %f\n',100*WMR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
train_scores(i_w,4) = 100 * WMR;
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
figure(4);
plot(1:params.wl_no,train_scores(:,4),'r');
legend('WMR');
saveas(gcf,fullfile(params.results_dir,'Weighted_MR_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_weight.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_weight.m
| 6,870 |
utf_8
|
36b46cfd41edf9337ff82b2b50fa1f21
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,train_scores] = train_boost_weight(params,data,ftrs,wgt,samples_idx)
% Train a KernelBoost classifier on the given samples
% the classifier combine the added discriptor
% allows an additional weight, i.e. assign the weight according to the
% number of pixels consisted in the seed
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
weak_learners(params.wl_no).alpha = 0;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
W = W .* wgt;
R = compute_ri(current_response);
train_scores = zeros(params.wl_no,4);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
% add the histogram discriptor
ftrs1 = ftrs(T2_idx,:);
features = [features,ftrs1];
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree...
] = remove_useless_filters_ftrs(reg_tree,kernels,kernel_params);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
% add the hd feature
features = [features,ftrs];
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
% incorperate the weight
W = W .* wgt;
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
WMR = sum(((current_response>0)~=(labels>0)) .* wgt )/sum(wgt);
fprintf(' Weighted Misclassif rate: %.2f | Loss: %f\n',100*WMR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
train_scores(i_w,4) = 100 * WMR;
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
figure(4);
plot(1:params.wl_no,train_scores(:,4),'r');
legend('WMR');
saveas(gcf,fullfile(params.results_dir,'Weighted_MR_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_admm_lat_3D.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_admm_lat_3D.m
| 3,970 |
utf_8
|
32e6c6e68884c9ef2e69079f488d343b
|
% use the mask distance as well as the main branch distance
% collect the latent label
% eavluate the effect of auto context
% includes the latent label
% discard the kernel features and adopts the new admm features
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners_admm] = train_admm_lat_3D(params,fn,samples_idx)
samples_no = size(samples_idx,1);
labels = samples_idx(:,5);
samples_idx = samples_idx(:,1:4);
current_response_admm = zeros(samples_no,1);
current_response_ac = current_response_admm;
current_response_ctx = current_response_admm;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response_admm);
R = compute_ri(current_response_admm);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
% wgt_samp = weight_sample_tol_3D(fn.train.gts,params,samples_idx);
wgt_samp = ones(size(samples_idx,1),1);
% X = data.train.imgs.X(:,data.train.imgs.idxs);
[features_admm,ftrs_kernel,ftrs_win] = collect_admm_ftrs_3D(fn.train.imgs,samples_idx);
% [features_admm1,ftrs_kernel1,ftrs_win1] = collect_admm_ftrs1_3D(fn.train.imgs,samples_idx);
% features_admm = [features_admm,features_admm1];
% ftrs_kernel = [ftrs_kernel;ftrs_kernel1];
% ftrs_win = [ftrs_win;ftrs_win1];
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response_admm);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
%
% [weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
% weak_learners(i_w).reg_tree] = train_admm_reg(X,params,samples_idx,T1_idx,T2_idx,W,R);
% collect the existing kernel boost features
% [kernels_kb,kernel_params_kb,features_kb] = train_kernel_features(X,params,samples_idx,T1_idx,T2_idx,W,R);
% collect the admm features
[weak_learners_admm(i_w).kernels,weak_learners_admm(i_w).kernel_params,...
weak_learners_admm(i_w).reg_tree,weak_learners_admm(i_w).admm_list] =...
train_admm_reg_3D(params,features_admm,T2_idx,W,R,ftrs_kernel,ftrs_win);
fprintf(' Performing prediction on the whole training set...\n');
admm_list = weak_learners_admm(i_w).admm_list;
t_pr = tic;
cached_responses_admm = LDARegStumpPredict(weak_learners_admm(i_w).reg_tree,...
single(features_admm(:,admm_list)));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
weak_learners_admm(i_w).alpha = search_alpha(current_response_admm,cached_responses_admm,labels,params);
current_response_admm = current_response_admm + weak_learners_admm(i_w).alpha * cached_responses_admm;
W = compute_wi(current_response_admm);
R = compute_ri(current_response_admm);
train_scores(i_w,:) = weak_learner_scores(current_response_admm,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_admm');
save([params.codename '_train_scores_sav.mat'],'train_scores');
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_admm_lat.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_admm_lat.m
| 3,783 |
utf_8
|
627afc057b202ef998ede2ba0d357279
|
% use the mask distance as well as the main branch distance
% collect the latent label
% eavluate the effect of auto context
% includes the latent label
% discard the kernel features and adopts the new admm features
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners_admm,weak_learners_ctx,weak_learners_ac] = train_admm_lat(params,data,samples_idx)
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response_admm = zeros(samples_no,1);
current_response_ac = current_response_admm;
current_response_ctx = current_response_admm;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response_admm);
R = compute_ri(current_response_admm);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
X = data.train.imgs.X(:,data.train.imgs.idxs);
features_admm = collect_admm_ftrs(X,samples_idx);
features_admm1 = collect_admm_ftrs1(X,samples_idx);
features_admm = [features_admm,features_admm1];
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response_admm);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
%
% [weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
% weak_learners(i_w).reg_tree] = train_admm_reg(X,params,samples_idx,T1_idx,T2_idx,W,R);
% collect the existing kernel boost features
% [kernels_kb,kernel_params_kb,features_kb] = train_kernel_features(X,params,samples_idx,T1_idx,T2_idx,W,R);
% collect the admm features
[weak_learners_admm(i_w).kernels,weak_learners_admm(i_w).kernel_params,...
weak_learners_admm(i_w).reg_tree,...
weak_learners_admm(i_w).ctx_list] = train_kernel_boost_ctx(X,params,...
features_admm,samples_idx,T1_idx,T2_idx,W,R);
% weak_learners_admm(i_w).ctx_lf_list = ctx_lf_list;
% this version simply ignores the ctx_list assigned by the previous
% method
% weak_learners_ctx(i_w).ctx_list = ctx_list;
cached_responses_admm = evaluate_weak_learners_ctx(X,params,features_admm,samples_idx,weak_learners_admm(i_w));
weak_learners_admm(i_w).alpha = search_alpha(current_response_admm,cached_responses_admm,labels,params);
current_response_admm = current_response_admm + weak_learners_admm(i_w).alpha * cached_responses_admm;
W = compute_wi(current_response_admm);
R = compute_ri(current_response_admm);
train_scores(i_w,:) = weak_learner_scores(current_response_admm,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_admm');
save([params.codename '_train_scores_sav.mat'],'train_scores');
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_context_v7.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_context_v7.m
| 29,256 |
utf_8
|
8ebd680d69ea266a4817f7d1d862a812
|
% use the mask distance as well as the main branch distance
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners] = train_boost_context_v7(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
% weak_learners(params.wl_no).alpha = 0;
%
% weak_learners_ctx1(params.wl_no).alpha = 0;
%
% weak_learners_ctx2(params.wl_no).alpha = 0;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
% current_response_ctx2 = current_response;
W_ctx1 = W;
R_ctx1 = R;
% W_ctx2 = W;
%
% R_ctx2 = R;
%train_scores = zeros(params.wl_no,3);
%train_scores_ctx1 = zeros(params.wl_no,3);
%train_scores_ctx2 = zeros(params.wl_no,3);
n_km = 30;
% assign the weight for each individual data point
wgt_samp = zeros(size(samples_idx,1),1);
for i_img = 1 : length(data.train.gts.X)
gt_img = data.train.gts.X{i_img};
dist_gt = bwdist(gt_img);
idx_img = (samples_idx(:,1) == i_img);
samp_idx_img_2D = samples_idx(idx_img,2:3);
samp_idx_img_1D = sub2ind(size(gt_img),samp_idx_img_2D(:,1),samp_idx_img_2D(:,2));
wgt_img = dist_gt(samp_idx_img_1D);
wgt_img(wgt_img > 7) = 7;
wgt_img = wgt_img/ 7;
wgt_img(dist_gt(samp_idx_img_1D) < 0.3) = 1;
wgt_samp(idx_img) = wgt_img;
end
W = W .* wgt_samp;
W_ctx1 = W_ctx1 .* wgt_samp;
% W_ctx2 = W_ctx2 .* wgt_samp;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
% save('tmp_ftrs.mat');
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
% ctx_loc_all = zeros(size(samples_idx,1),n_ftrs2);
% save('tmp_ftrs.mat');
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
% if(isempty(ctx_ftrs2_w{i_w - 1,i_img}))
%
% save('empty_flag_sav.mat', ctx_ftrs2_w);
%
% %ctx_loc_all(samples_idx(:,1) == i_img,:) = ones(sum(samples_idx(:,1) == i_img),n_km) * 5000;
%
% else
% ctx_loc_all(samples_idx(:,1) == i_img,:) = ctx_ftrs2_w{i_w - 1,i_img};
% end
ctx_ftrs1_w{i_w - 1,i_img} = [];
% ctx_ftrs2_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
% ctx_loc = ctx_loc_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
if(isfield(params,'ctx1_tree_depth'))
tree_d_g = params.ctx1_tree_depth;
else
tree_d_g = params.tree_depth;
end
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(tree_d_g));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
% t_tr = tic;
% reg_tree_l = LDARegStumpTrain(single([features,ctx_loc]),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
% for i_img = 1 : size(data.train.(ch).X,1)
%
% T2_img = samples_idx(T2_idx,1) == i_img;
%
% ctx_loc_img = ctx_loc(T2_img,:);
%
% ctx_glb_img = ctx_glb(T2_img,:);
%
% fprintf(' Training regression tree %d on learned features combined with context 1 2...\n',i_img);
%
% t_tr = tic;
% reg_tree_l{i_img} = LDARegStumpTrain(single([features(T2_img,:),...
% ctx_glb_img,ctx_loc_img]),R(T2_idx(T2_img)),W(T2_idx(T2_img)) ...
% /sum(W(T2_idx((T2_img)))),...
% uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
%
% end
% fprintf(' Training regression tree on learned features combined with context 1 2...\n');
%
% t_tr = tic;
%
% if(isfield(params,'ctx2_tree_depth'))
%
% tree_d_l = params.ctx2_tree_depth;
%
% else
%
% tree_d_l = params.tree_depth;
%
% end
%
% reg_tree_l = LDARegStumpTrain(single([features,...
% ctx_glb,ctx_loc]),R_ctx2(T2_idx),W_ctx2(T2_idx) ...
% /sum(W_ctx2(T2_idx)),uint32(tree_d_l));
%
% time_tr = toc(t_tr);
%
% fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
% [weak_learners_ctx2(i_w).kernels,weak_learners_ctx2(i_w).kernel_params,weak_learners_ctx2(i_w).reg_tree,...
% weak_learners_ctx2(i_w).ctx_list]...
% = remove_useless_filters_ctx(reg_tree_l,kernels,kernel_params);
%
% ctx2_list = weak_learners_ctx2(i_w).ctx_list;
%
% ctx2_list(ctx2_list < ncf_g + 1) = [];
%
% ctx2_list = ctx2_list - ncf_g;
%
% tmp_kmc = [];
%
% tmp_ltree = [];
%
% for i_km = 1 : length(ctx2_list)
%
% tmp_kmc(i_km,:) = kmc_ctx_c2(ctx2_list(i_km),:);
%
% tmp_ltree(i_km) = tleaf_ctx_c2(ctx2_list(i_km));
%
% end
%
% weak_learners_ctx2(i_w).kmc = tmp_kmc;
%
% weak_learners_ctx2(i_w).ltree = tmp_ltree;
% ctx2_list = ctx2_list - ncf_g;
% weak_learners_ctx2(i_w).ctx2_list = ctx2_list;
save('weak_learners_sav.mat','weak_learners_ctx1','weak_learners');
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
% ctx_glb_all = [ctx_glb_all, ctx_loc_all];
% clear ctx_loc_all;
% features_ctx2 = ctx_glb_all(:,weak_learners_ctx2(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
%
%
% t_ev = tic;
% fprintf(' Evaluating the learned kernels on the whole training set...\n');
% features = zeros(length(labels),length(weak_learners_ctx2(i_w).kernels));
% for i_ch = 1:params.ch_no
% ch = params.ch_list{i_ch};
% sub_ch_no = data.train.(ch).sub_ch_no;
%
% X = data.train.(ch).X(:,data.train.(ch).idxs);
% for i_s = 1:sub_ch_no
% idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),...
% weak_learners_ctx2(i_w).kernel_params));
% if (~isempty(idxs))
% features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
% samples_idx(:,1:3),params.sample_size,...
% weak_learners_ctx2(i_w).kernels(idxs),...
% weak_learners_ctx2(i_w).kernel_params(idxs));
% end
% end
% end
% ev_time = toc(t_ev);
% fprintf(' Evaluation completed in %f seconds\n',ev_time);
%
% fprintf(' Performing ctx2 prediction on the whole training set...\n');
%
% t_pr = tic;
% cached_responses_ctx2 = LDARegStumpPredict(...
% weak_learners_ctx2(i_w).reg_tree,single([features, features_ctx2]));
% time_pr = toc(t_pr);
% fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
% fprintf(' Finding alpha 2 through line search...\n');
% t_alp = tic;
% alpha_ctx2 = mexLineSearch(current_response_ctx2,cached_responses_ctx2,labels,mex_loss_type);
% time_alp = toc(t_alp);
% fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx2,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
W = W .* wgt_samp;
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
W_ctx1 = W_ctx1 .* wgt_samp;
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
% alpha_ctx2 = alpha_ctx2 * params.shrinkage_factor;
%
% current_response_ctx2 = current_response_ctx2 + alpha_ctx2*cached_responses_ctx2;
%
% W_ctx2 = compute_wi(current_response_ctx2);
%
% W_ctx2 = W_ctx2 .* wgt_samp;
%
% R_ctx2 = compute_ri(current_response_ctx2);
%
% weak_learners_ctx2(i_w).alpha = alpha_ctx2;
save('weak_learners_sav.mat','weak_learners','weak_learners_ctx1');
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
MR = sum(((current_response>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_w(i_w,1) = 100*MR;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum(((current_response_ctx1>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx1w(i_w,1) = 100*MR;
% MR = sum((current_response_ctx2>0)~=(labels>0))/length(labels);
%
% fprintf(' Ctx2 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx2));
%
% train_scores_ctx2(i_w,1) = 100*MR;
%
% train_scores_ctx2(i_w,2) = compute_loss(current_response_ctx2);
%
% train_scores_ctx2(i_w,3) = alpha_ctx2;
%
% MR = sum(((current_response_ctx2>0)~=(labels>0)) .* wgt_samp)/...
% (length(labels) * mean(wgt_samp));
%
% train_scores_ctx2w(i_w,1) = 100*MR;
save('train_scores_sav_w.mat','train_scores_w','train_scores_ctx1w');
for i_img = 1 : length(data.train.gts.X)
img_idx = find(samples_idx(:,1) == i_img);
MR_img(i_w,i_img) = sum((current_response(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
MR_img_ctx1(i_w,i_img) = sum((current_response_ctx1(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
end
save('MR_sav.mat','MR_img','MR_img_ctx1');
save('train_scores_sav.mat','train_scores','train_scores_ctx1');
end
if(i_w > 0)
% collect th colour value of the sample data
% samp_rgb = zeros(size(samples_idx,1),3);
%
% for i_img = 1 : size(data.train.(ch).X,1)
%
% X = data.train.(ch).X(i_img,data.train.(ch).idxs);
%
% clear I;
%
% for i_b = 1 : 3
%
% I(:,:,i_b) = X{i_b};
%
% end
%
%
% samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
%
% posi_samp = sub2ind(size(I(:,:,1)),samp_idx_img(:,2),samp_idx_img(:,3));
%
% I = reshape(I,[],3);
%
% samp_rgb(samples_idx == i_img,:) = I(posi_samp,:);
%
% end
wltree = weak_learners(i_w).reg_tree;
% [~,samp_lf] = predict_idx_wl(data,params,samples_idx,weak_learners(i_w));
%
% lf_hist = histc(samp_lf,1:length(wltree));
%
% lf_hist = lf_hist(1:length(wltree));
%
% lf_hist = lf_hist / sum(lf_hist);
%
% [lfn,lf_id] = sort(lf_hist,'descend');
%
% lf_id(lfn < 0.3) = [];
%
% lfn(lfn < 0.3) = [];
%
% for i_lf = 1 : length(lf_id)
%
% [~,ctx_km_c{i_lf}] = kmeans(samp_rgb(samp_lf == lf_id(i_lf),:),n_km,'EmptyAction','singleton');
%
% end
%
% for i_n = 1 : length(wltree)
%
% bkg_ftrs2{i_n} = [];
%
%
%
% %bkg_idxs{i_n} = [];
%
% end
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
mask_img = data.train.masks.X{i_img};
[mask_x,mask_y] = find(mask_img > 0);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),[mask_x,mask_y]);
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
%context_img = zeros(size(leaf_image));
% cxt_idx = 1;
n_leaf = 0;
ctx_c1 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
% if(length(n_idx) / n_samp_img > 0.2)
%
% I_2D = reshape(I,[],3);
%
% n_idx = downsample(n_idx,200);
%
% bkg_ftrs2{i_n} = [ bkg_ftrs2{i_n}; I_2D(n_idx,:)];
%
%
% end
end
end
% contx_list{i_w,i_img} = ctx_c2;
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
% ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
% ctx_ftrs1(ctx_ftrs1 < 0.1) = 5000;
mask_img = data.train.masks.X{i_img};
dist_ctx_map = bwdist(~mask_img);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
known_mb = score_image > 0.5;
known_mb = filter_small_comp(known_mb,50);
known_mb = (dist_ctx_map > 10) .* known_mb;
dist_ctx_map = bwdist(known_mb);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
% n_km = 30;
%
% ctx_c2 = [];
%
% clear ftrs_kmc_c2;
%
% kmc_ctx_c2 = [];
%
% tleaf_ctx_c2 = [];
%
% for i_n = 1 : length(wltree)
%
% if(~isempty(bkg_ftrs2{i_n}))
%
% tStart = tic;
%
% [~,ftrs_kmc_tmp] = kmeans(bkg_ftrs2{i_n},n_km,'EmptyAction','singleton');
%
% t1 = toc(tStart);
%
% fprintf('Clustering the context ftrs 2 took %d seconds', t1);
%
%
% ctx_c2(end + 1 : end + n_km) = (100 * i_n) + (1:n_km);
%
% ftrs_kmc{i_w,i_n} = ftrs_kmc_tmp;
%
% kmc_ctx_c2(end + 1: end + n_km,:) = ftrs_kmc_tmp;
%
% tleaf_ctx_c2(end + 1: end + n_km,:) = i_n;
%
% else
%
% ftrs_kmc{i_w,i_n} = {};
%
% end
%
% end
%
% n_ftrs2 = length(ctx_c2);
%
%
% for i_img = 1 : size(data.train.(ch).X,1)
%
% ctx_ftrs2_w{i_w,i_img} = [];
%
% X = data.train.(ch).X(i_img,data.train.(ch).idxs);
%
% tStart = tic;
%
% % to avoid the computational burden, now apply the method only
% % on some sample points
%
% samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
%
% [score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
%
% t1 = toc(tStart);
%
% fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
%
% ftrs2_img = zeros(size(leaf_image));
%
% samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
%
% samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
%
% ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
%
% for i_n = 1 : length(wltree)
%
% if(~isempty(ftrs_kmc{i_w,i_n}))
%
% ftrs2_img_tmp = ftrs_c2_img(X,ftrs_kmc{i_w,i_n});
%
% ftrs2_img = (i_n * 100 + ftrs2_img_tmp);
%
% % ftrs2_img = (i_n * 100 + ftrs2_img_tmp) .* (leaf_image == i_n);
%
%
% end
%
% end
% for i_ctx = 1 : length(ctx_c2)
%
% tStart = tic;
%
% lf_ctx = (ftrs2_img == ctx_c2(i_ctx));
%
% if(sum(lf_ctx(:)))
%
% dist_ctx_map = bwdist(lf_ctx);
%
% ctx_ftrs2(:,i_ctx) = dist_ctx_map(samp_idx_img);
%
% else
%
% ctx_ftrs2(:,i_ctx) = 5000;
%
% end
%
% t1 = toc(tStart);
%
% fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
%
% end
% ctx_ftrs2(ctx_ftrs2 < 0.1) = 5000;
% ctx_ftrs2_w{i_w,i_img} = ctx_ftrs2;
% clear ctx_ftrs2;
% end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_RF_ctx_ac.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_RF_ctx_ac.m
| 5,974 |
utf_8
|
eb15d4fd53fd945070a6be25d7eb9b5a
|
% use the mask distance as well as the main branch distance
% evaluate the effect of auto context
% takes the random forest framework
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx,weak_learners_ac] = train_RF_ctx_ac(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ac = current_response;
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
% load the training images
X = data.train.imgs.X(:,data.train.imgs.idxs);
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W,R);
cached_responses = evaluate_weak_learners(X,params,samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
%%%%%% train the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
if(i_w > 1)
% in this step, apply the auto context feature learning
X_ac = X;
for i_img = 1 : size(X,1)
X_ac{i_img,size(X,2) + 1} = ac_ftrs{i_img};
end
[weak_learners_ac(i_w).kernels,weak_learners_ac(i_w).kernel_params,...
weak_learners_ac(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W_ac,R_ac);
cached_responses_ac = evaluate_weak_learners(X_ac,params,samples_idx,weak_learners_ac(i_w));
weak_learners_ac(i_w).alpha = search_alpha(current_response_ac,cached_responses_ac,labels,params);
current_response_ac = current_response_ac + weak_learners_ac(i_w).alpha * cached_responses_ac;
W_ac = compute_wi(current_response_ac);
R_ac = compute_ri(current_response_ac);
train_scores_ac(i_w,:) = weak_learner_scores(current_response_ac,labels,wgt_samp,compute_loss);
else
for i_img = 1 : size(X,1)
ac_ftrs{i_img} = zeros(size(X{i_img,1}));
end
end
%%%%%% Complete training the base line weak learners augumented by auto context %%%%%%%%%%%%%%%%%
%%%%%%%%%%%% start training the ctx augmented weak learners%%%%%%%%%
if(i_w > 1)
% load the global context features
[weak_learners_ctx(i_w).kernels,weak_learners_ctx(i_w).kernel_params,...
weak_learners_ctx(i_w).reg_tree, weak_learners_ctx(i_w).ctx_list]...
= train_kernel_boost_ctx(X,params,ctx_glb_all,...
samples_idx,T1_idx,T2_idx,W_ctx,R_ctx);
cached_responses_ctx = evaluate_weak_learners_ctx(X,params,ctx_glb_all,samples_idx,weak_learners_ctx(i_w));
weak_learners_ctx(i_w).alpha = search_alpha(current_response_ctx,cached_responses_ctx,labels,params);
current_response_ctx = current_response_ctx + weak_learners_ctx(i_w).alpha * cached_responses_ctx;
W_ctx = compute_wi(current_response_ctx);
R_ctx = compute_ri(current_response_ctx);
train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx','weak_learners','weak_learners_ac');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx','train_scores_ac');
end
%%%% complete training the global context feature weak learners
% collect the global features as well as auto context features, be aware
% of the global features, they are only prepared for the next round, so
% this part should be behind the context and auto context learning
[ctx_glb_all,ac_ftrs] = collect_global_ctx(X,data.train.masks,...
params,weak_learners(i_w),samples_idx,ac_ftrs);
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_admm_lat_fn.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_admm_lat_fn.m
| 3,832 |
utf_8
|
b55e33e32ebb694abb32b0e2b5b567d1
|
% use the mask distance as well as the main branch distance
% train the model on the 3D training dataset
% collect the latent label
% eavluate the effect of auto context
% includes the latent label
% discard the kernel features and adopts the new admm features
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners_admm,weak_learners_ctx,weak_learners_ac] = train_admm_lat_fn(params,data,samples_idx)
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response_admm = zeros(samples_no,1);
current_response_ac = current_response_admm;
current_response_ctx = current_response_admm;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response_admm);
R = compute_ri(current_response_admm);
W_ac = W;
R_ac = R;
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol_fn(fn.train.gts,params,samples_idx);
X = data.train.imgs.X(:,data.train.imgs.idxs);
features_admm = collect_admm_ftrs(X,samples_idx);
features_admm1 = collect_admm_ftrs1(X,samples_idx);
features_admm = [features_admm,features_admm1];
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response_admm);
W = W .* wgt_samp;
W_ctx = W_ctx .* wgt_samp;
W_ac = W_ac .* wgt_samp;
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
%
% [weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
% weak_learners(i_w).reg_tree] = train_admm_reg(X,params,samples_idx,T1_idx,T2_idx,W,R);
% collect the existing kernel boost features
% [kernels_kb,kernel_params_kb,features_kb] = train_kernel_features(X,params,samples_idx,T1_idx,T2_idx,W,R);
% collect the admm features
[weak_learners_admm(i_w).kernels,weak_learners_admm(i_w).kernel_params,...
weak_learners_admm(i_w).reg_tree,...
weak_learners_admm(i_w).ctx_list] = train_kernel_boost_ctx(X,params,...
features_admm,samples_idx,T1_idx,T2_idx,W,R);
% weak_learners_admm(i_w).ctx_lf_list = ctx_lf_list;
% this version simply ignores the ctx_list assigned by the previous
% method
% weak_learners_ctx(i_w).ctx_list = ctx_list;
cached_responses_admm = evaluate_weak_learners_ctx(X,params,features_admm,samples_idx,weak_learners_admm(i_w));
weak_learners_admm(i_w).alpha = search_alpha(current_response_admm,cached_responses_admm,labels,params);
current_response_admm = current_response_admm + weak_learners_admm(i_w).alpha * cached_responses_admm;
W = compute_wi(current_response_admm);
R = compute_ri(current_response_admm);
train_scores(i_w,:) = weak_learner_scores(current_response_admm,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_admm');
save([params.codename '_train_scores_sav.mat'],'train_scores');
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_context_v9.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_context_v9.m
| 16,448 |
utf_8
|
320fda1a607dfc3e1e2024beb5ebcb0f
|
% use the mask distance as well as the main branch distance
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx1] = train_boost_context_v9(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
W_ctx1 = W;
R_ctx1 = R;
n_km = 30;
% assign the weight for each individual data point
wgt_samp = zeros(size(samples_idx,1),1);
tol_z_wgt = params.tol_z_wgt;
fig_thres = params.fig_thres;
for i_img = 1 : length(data.train.gts.X)
gt_img = data.train.gts.X{i_img};
dist_gt = bwdist(gt_img);
idx_img = (samples_idx(:,1) == i_img);
samp_idx_img_2D = samples_idx(idx_img,2:3);
samp_idx_img_1D = sub2ind(size(gt_img),samp_idx_img_2D(:,1),samp_idx_img_2D(:,2));
wgt_img = dist_gt(samp_idx_img_1D);
wgt_img(wgt_img > tol_z_wgt) = tol_z_wgt;
wgt_img = wgt_img/ tol_z_wgt;
wgt_img(dist_gt(samp_idx_img_1D) < 0.3) = 1;
wgt_samp(idx_img) = wgt_img;
end
W = W .* wgt_samp;
W_ctx1 = W_ctx1 .* wgt_samp;
% W_ctx2 = W_ctx2 .* wgt_samp;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
ctx_ftrs1_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
if(isfield(params,'ctx1_tree_depth'))
tree_d_g = params.ctx1_tree_depth;
else
tree_d_g = params.tree_depth;
end
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(tree_d_g));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx1','weak_learners');
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
W = W .* wgt_samp;
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
W_ctx1 = W_ctx1 .* wgt_samp;
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
save([params.codename '_weak_learners_sav.mat'],'weak_learners','weak_learners_ctx1');
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
MR = sum(((current_response>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_w(i_w,1) = 100*MR;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum(((current_response_ctx1>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx1w(i_w,1) = 100*MR;
save([params.codename '_train_scores_sav_w.mat'],'train_scores_w','train_scores_ctx1w');
for i_img = 1 : length(data.train.gts.X)
img_idx = find(samples_idx(:,1) == i_img);
MR_img(i_w,i_img) = sum((current_response(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
MR_img_ctx1(i_w,i_img) = sum((current_response_ctx1(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
end
save([params.codename '_MR_sav.mat'],'MR_img','MR_img_ctx1');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx1');
end
if(i_w > 0)
% collect th colour value of the sample data
wltree = weak_learners(i_w).reg_tree;
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
mask_img = data.train.masks.X{i_img};
[mask_x,mask_y] = find(mask_img > 0);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),[mask_x,mask_y]);
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
n_leaf = 0;
ctx_c1 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
end
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
mask_img = data.train.masks.X{i_img};
dist_ctx_map = bwdist(~mask_img);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
known_mb = score_image > fig_thres;
known_mb = (bwdist(~mask_img) > 10) .* known_mb;
if(sum(known_mb(:)))
dist_ctx_map = bwdist(known_mb);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,end + 1) = 5000;
end
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_LTM_validation_3D_v2.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_LTM_validation_3D_v2.m
| 8,398 |
utf_8
|
8b676a7e266f354890aae827c06525c1
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function weak_learners = train_LTM_validation_3D_v2(params,features,wgt,samples_idx)
% Train a KernelBoost classifier on the given samples
% the classifier combine the added discriptor
% allows an additional weight, i.e. assign the weight according to the
% number of pixels consisted in the seed
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
labels = samples_idx(:,5);
labels = (labels + 3) / 2;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
features1 = features(T2_idx,:);
features1 = single(features1);
fprintf(' Training classification tree on learned features...\n');
t_tr = tic;
weak_learners(i_w).tree = forestTrain(features1,labels(T2_idx),'maxDepth',params.wl_depth,'H',2,'dWts',wgt);
weak_learners(i_w).alpha = 1 / params.wl_no;
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
%
%
%
% current_response = zeros(samples_no,1);
%
% [compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
%
% W = compute_wi(current_response);
%
% W = W .* wgt;
%
%
% R = compute_ri(current_response);
%
% train_scores = zeros(params.wl_no,4);
%
% for i_w = 1:params.wl_no
% t_wl = tic;
% fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
%
% % Indexes of the two training subparts
% T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
% T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
% [wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
% s_T1 = samples_idx(wr_idxs,1:3);
% s_T2 = samples_idx(T2_idx,1:3);
%
% features = cell(params.ch_no,1);
% kernels = cell(params.ch_no,1);
% kernel_params = cell(params.ch_no,1);
%
% for i_ch = 1:params.ch_no
% ch = params.ch_list{i_ch};
% fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
%
%
% X = import_3D_data_v2(fn.train.imgs.X(1,:));
%
%
%
%
%
% % for i_img = 1 : length(data.train.(ch).X)
% %
% % X{i_img,1} = sum(data.train.(ch).X{i_img},3);
% %
% % end
%
%
% %X = data.train.(ch).X(:,data.train.(ch).idxs);
% X_idxs = 1;
%
% sub_ch_no = data.train.(ch).sub_ch_no;
%
% sub_ch_no = 1;
%
% features{i_ch} = cell(sub_ch_no,1);
% kernels{i_ch} = cell(sub_ch_no,1);
% kernel_params{i_ch} = cell(sub_ch_no,1);
%
% % Learn the filters
% fprintf(' Learning filters on the sub-channels\n');
% for i_s = 1:sub_ch_no
% t_sch = tic;
% fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
% [kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
% sch_time = toc(t_sch);
% fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
%
% t_ev = tic;
% fprintf(' Evaluating the filters learned on the subchannel\n');
% features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
% ev_time = toc(t_ev);
% fprintf(' Evaluation completed in %f seconds\n',ev_time);
% end
% end
%
% fprintf(' Merging features and kernels...\n');
% [kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
% fprintf(' Done!\n');
%
% % add the histogram discriptor
%
% ftrs1 = ftrs(T2_idx,:);
%
% features = [features,ftrs1];
%
%
% fprintf(' Training regression tree on learned features...\n');
% t_tr = tic;
% reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
%
% fprintf(' Removing useless kernels...\n');
% [weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree...
% ] = remove_useless_filters_ftrs(reg_tree,kernels,kernel_params);
%
%
% t_ev = tic;
% fprintf(' Evaluating the learned kernels on the whole training set...\n');
% features = zeros(length(labels),length(weak_learners(i_w).kernels));
% for i_ch = 1:params.ch_no
% ch = params.ch_list{i_ch};
% sub_ch_no = data.train.(ch).sub_ch_no;
%
% sub_ch_no = 1;
%
% % X = data.train.(ch).X(:,data.train.(ch).idxs);
%
% X = expand_img_v3(data.train.(ch).X,params);
%
% for i_s = 1:sub_ch_no
% idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
% % idxs = 1;
%
% if (~isempty(idxs))
% features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
% end
% end
% end
% ev_time = toc(t_ev);
% fprintf(' Evaluation completed in %f seconds\n',ev_time);
%
%
% % add the hd feature
%
%
% features = [features,ftrs];
%
% fprintf(' Performing prediction on the whole training set...\n');
% t_pr = tic;
% cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
% time_pr = toc(t_pr);
% fprintf(' Prediction finished, took %f seconds\n',time_pr);
% clear features;
%
% fprintf(' Finding alpha through line search...\n');
% t_alp = tic;
% alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
% time_alp = toc(t_alp);
% fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
% alpha = alpha * params.shrinkage_factor;
%
% current_response = current_response + alpha*cached_responses;
%
% W = compute_wi(current_response);
%
% % incorperate the weight
% W = W .* wgt;
%
% R = compute_ri(current_response);
%
% weak_learners(i_w).alpha = alpha;
%
% MR = sum((current_response>0)~=(labels>0))/length(labels);
% fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
%
% WMR = sum(((current_response>0)~=(labels>0)) .* wgt )/sum(wgt);
% fprintf(' Weighted Misclassif rate: %.2f | Loss: %f\n',100*WMR,compute_loss(current_response));
%
% train_scores(i_w,1) = 100*MR;
% train_scores(i_w,2) = compute_loss(current_response);
% train_scores(i_w,3) = alpha;
% train_scores(i_w,4) = 100 * WMR;
%
%
% wl_time = toc(t_wl);
% fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
% end
%
% clf;
% figure(1);
% plot(1:params.wl_no,train_scores(:,1),'b')
% legend('MR');
% saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
% figure(2);
% plot(1:params.wl_no,train_scores(:,2),'g');
% legend('loss');
% saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
% figure(3);
% plot(1:params.wl_no,train_scores(:,3),'r');
% legend('alpha');
% saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
%
% figure(4);
% plot(1:params.wl_no,train_scores(:,4),'r');
% legend('WMR');
% saveas(gcf,fullfile(params.results_dir,'Weighted_MR_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_context_v5.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_context_v5.m
| 28,296 |
utf_8
|
7ce667f2a31b5dc8ea96e68e951bb4b3
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners] = train_boost_context_v5(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
% weak_learners(params.wl_no).alpha = 0;
%
% weak_learners_ctx1(params.wl_no).alpha = 0;
%
% weak_learners_ctx2(params.wl_no).alpha = 0;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
current_response_ctx1 = current_response;
current_response_ctx2 = current_response;
W_ctx1 = W;
R_ctx1 = R;
W_ctx2 = W;
R_ctx2 = R;
%train_scores = zeros(params.wl_no,3);
%train_scores_ctx1 = zeros(params.wl_no,3);
%train_scores_ctx2 = zeros(params.wl_no,3);
n_km = 30;
% assign the weight for each individual data point
wgt_samp = zeros(size(samples_idx,1),1);
for i_img = 1 : length(data.train.gts.X)
gt_img = data.train.gts.X{i_img};
dist_gt = bwdist(gt_img);
idx_img = (samples_idx(:,1) == i_img);
samp_idx_img_2D = samples_idx(idx_img,2:3);
samp_idx_img_1D = sub2ind(size(gt_img),samp_idx_img_2D(:,1),samp_idx_img_2D(:,2));
wgt_img = dist_gt(samp_idx_img_1D);
wgt_img(wgt_img > 7) = 7;
wgt_img = wgt_img/ 7;
wgt_img(dist_gt(samp_idx_img_1D) < 0.3) = 1;
wgt_samp(idx_img) = wgt_img;
end
W = W .* wgt_samp;
W_ctx1 = W_ctx1 .* wgt_samp;
W_ctx2 = W_ctx2 .* wgt_samp;
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
if(i_w > 1)
% from this step, the context featuers are added for individual image.
%save('tmp_ftrs.mat');
nf = size(features,1);
ncf_g = size(ctx_ftrs1,2);
ctx_glb_all = zeros(size(samples_idx,1),ncf_g);
ctx_loc_all = zeros(size(samples_idx,1),n_ftrs2);
% save('tmp_ftrs.mat');
for i_img = 1 : size(data.train.(ch).X,1)
ctx_glb_all(samples_idx(:,1) == i_img,:) = ctx_ftrs1_w{i_w - 1,i_img};
if(isempty(ctx_ftrs2_w{i_w - 1,i_img}))
save('empty_flag_sav.mat', ctx_ftrs2_w);
%ctx_loc_all(samples_idx(:,1) == i_img,:) = ones(sum(samples_idx(:,1) == i_img),n_km) * 5000;
else
ctx_loc_all(samples_idx(:,1) == i_img,:) = ctx_ftrs2_w{i_w - 1,i_img};
end
ctx_ftrs1_w{i_w - 1,i_img} = [];
ctx_ftrs2_w{i_w - 1,i_img} = [];
end
ctx_glb = ctx_glb_all(T2_idx,:);
ctx_loc = ctx_loc_all(T2_idx,:);
fprintf(' Training regression tree on learned features combined with context 1...\n');
t_tr = tic;
if(isfield(params,'ctx1_tree_depth'))
tree_d_g = params.ctx1_tree_depth;
else
tree_d_g = params.tree_depth;
end
reg_tree_g = LDARegStumpTrain(single([features,...
ctx_glb]),R_ctx1(T2_idx),W_ctx1(T2_idx)...
/sum(W_ctx1(T2_idx)),uint32(tree_d_g));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
% t_tr = tic;
% reg_tree_l = LDARegStumpTrain(single([features,ctx_loc]),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
% for i_img = 1 : size(data.train.(ch).X,1)
%
% T2_img = samples_idx(T2_idx,1) == i_img;
%
% ctx_loc_img = ctx_loc(T2_img,:);
%
% ctx_glb_img = ctx_glb(T2_img,:);
%
% fprintf(' Training regression tree %d on learned features combined with context 1 2...\n',i_img);
%
% t_tr = tic;
% reg_tree_l{i_img} = LDARegStumpTrain(single([features(T2_img,:),...
% ctx_glb_img,ctx_loc_img]),R(T2_idx(T2_img)),W(T2_idx(T2_img)) ...
% /sum(W(T2_idx((T2_img)))),...
% uint32(params.tree_depth));
% time_tr = toc(t_tr);
% fprintf(' Done! (took %f seconds)\n',time_tr);
%
% end
fprintf(' Training regression tree on learned features combined with context 1 2...\n');
t_tr = tic;
if(isfield(params,'ctx2_tree_depth'))
tree_d_l = params.ctx2_tree_depth;
else
tree_d_l = params.tree_depth;
end
reg_tree_l = LDARegStumpTrain(single([features,...
ctx_glb,ctx_loc]),R_ctx2(T2_idx),W_ctx2(T2_idx) ...
/sum(W_ctx2(T2_idx)),uint32(tree_d_l));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
end
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree]...
= remove_useless_filters(reg_tree,kernels,kernel_params);
if(i_w > 1)
[weak_learners_ctx1(i_w).kernels,weak_learners_ctx1(i_w).kernel_params,weak_learners_ctx1(i_w).reg_tree,...
weak_learners_ctx1(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_g,kernels,kernel_params);
[weak_learners_ctx2(i_w).kernels,weak_learners_ctx2(i_w).kernel_params,weak_learners_ctx2(i_w).reg_tree,...
weak_learners_ctx2(i_w).ctx_list]...
= remove_useless_filters_ctx(reg_tree_l,kernels,kernel_params);
ctx2_list = weak_learners_ctx2(i_w).ctx_list;
ctx2_list(ctx2_list < ncf_g + 1) = [];
ctx2_list = ctx2_list - ncf_g;
tmp_kmc = [];
tmp_ltree = [];
for i_km = 1 : length(ctx2_list)
tmp_kmc(i_km,:) = kmc_ctx_c2(ctx2_list(i_km),:);
tmp_ltree(i_km) = tleaf_ctx_c2(ctx2_list(i_km));
end
weak_learners_ctx2(i_w).kmc = tmp_kmc;
weak_learners_ctx2(i_w).ltree = tmp_ltree;
% ctx2_list = ctx2_list - ncf_g;
weak_learners_ctx2(i_w).ctx2_list = ctx2_list;
save('weak_learners_sav.mat','weak_learners_ctx2','weak_learners_ctx1','weak_learners');
end
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
if(i_w > 1)
features_ctx1 = ctx_glb_all(:,weak_learners_ctx1(i_w).ctx_list);
ctx_glb_all = [ctx_glb_all, ctx_loc_all];
clear ctx_loc_all;
features_ctx2 = ctx_glb_all(:,weak_learners_ctx2(i_w).ctx_list);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx1(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners_ctx1(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx1(i_w).kernels(idxs),weak_learners_ctx1(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx1 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx1 = LDARegStumpPredict(...
weak_learners_ctx1(i_w).reg_tree,single([features, features_ctx1]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners_ctx2(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),...
weak_learners_ctx2(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),...
samples_idx(:,1:3),params.sample_size,...
weak_learners_ctx2(i_w).kernels(idxs),...
weak_learners_ctx2(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing ctx2 prediction on the whole training set...\n');
t_pr = tic;
cached_responses_ctx2 = LDARegStumpPredict(...
weak_learners_ctx2(i_w).reg_tree,single([features, features_ctx2]));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
clear features_ctx1 features_ctx2 ctx_glb_all;
end
%clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
if(i_w > 1)
fprintf(' Finding alpha 1 through line search...\n');
t_alp = tic;
alpha_ctx1 = mexLineSearch(current_response_ctx1,cached_responses_ctx1,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx1,time_alp);
fprintf(' Finding alpha 2 through line search...\n');
t_alp = tic;
alpha_ctx2 = mexLineSearch(current_response_ctx2,cached_responses_ctx2,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha_ctx2,time_alp);
end
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
W = W .* wgt_samp;
weak_learners(i_w).alpha = alpha;
if(i_w > 1)
alpha_ctx1 = alpha_ctx1 * params.shrinkage_factor;
current_response_ctx1 = current_response_ctx1 + alpha_ctx1*cached_responses_ctx1;
W_ctx1 = compute_wi(current_response_ctx1);
R_ctx1 = compute_ri(current_response_ctx1);
W_ctx1 = W_ctx1 .* wgt_samp;
weak_learners_ctx1(i_w).alpha = alpha_ctx1;
alpha_ctx2 = alpha_ctx2 * params.shrinkage_factor;
current_response_ctx2 = current_response_ctx2 + alpha_ctx2*cached_responses_ctx2;
W_ctx2 = compute_wi(current_response_ctx2);
W_ctx2 = W_ctx2 .* wgt_samp;
R_ctx2 = compute_ri(current_response_ctx2);
weak_learners_ctx2(i_w).alpha = alpha_ctx2;
save('weak_learners_sav.mat','weak_learners','weak_learners_ctx1','weak_learners_ctx1')
end
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
MR = sum(((current_response>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_w(i_w,1) = 100*MR;
if(i_w > 1)
MR = sum((current_response_ctx1>0)~=(labels>0))/length(labels);
fprintf(' Ctx1 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx1));
train_scores_ctx1(i_w,1) = 100*MR;
train_scores_ctx1(i_w,2) = compute_loss(current_response_ctx1);
train_scores_ctx1(i_w,3) = alpha_ctx1;
MR = sum(((current_response_ctx1>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx1w(i_w,1) = 100*MR;
MR = sum((current_response_ctx2>0)~=(labels>0))/length(labels);
fprintf(' Ctx2 Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response_ctx2));
train_scores_ctx2(i_w,1) = 100*MR;
train_scores_ctx2(i_w,2) = compute_loss(current_response_ctx2);
train_scores_ctx2(i_w,3) = alpha_ctx2;
MR = sum(((current_response_ctx2>0)~=(labels>0)) .* wgt_samp)/...
(length(labels) * mean(wgt_samp));
train_scores_ctx2w(i_w,1) = 100*MR;
save('train_scores_sav_w.mat','train_scores_w','train_scores_ctx1w','train_scores_ctx2w');
for i_img = 1 : length(data.train.gts.X)
img_idx = find(samples_idx(:,1) == i_img);
MR_img(i_w,i_img) = sum((current_response(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
MR_img_ctx1(i_w,i_img) = sum((current_response_ctx1(img_idx)>0)~=(labels(img_idx)>0))/length(labels(img_idx));
end
save('MR_sav.mat','MR_img','MR_img_ctx1');
save('train_scores_sav.mat','train_scores','train_scores_ctx1','train_scores_ctx2');
end
if(i_w > 0)
% collect th colour value of the sample data
samp_rgb = zeros(size(samples_idx,1),3);
for i_img = 1 : size(data.train.(ch).X,1)
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
posi_samp = sub2ind(size(I(:,:,1)),samp_idx_img(:,2),samp_idx_img(:,3));
I = reshape(I,[],3);
samp_rgb(samples_idx == i_img,:) = I(posi_samp,:);
end
wltree = weak_learners(i_w).reg_tree;
[~,samp_lf] = predict_idx_wl(data,params,samples_idx,weak_learners(i_w));
lf_hist = histc(samp_lf,1:length(wltree));
lf_hist = lf_hist(1:length(wltree));
lf_hist = lf_hist / sum(lf_hist);
[lfn,lf_id] = sort(lf_hist,'descend');
lf_id(lfn < 0.3) = [];
lfn(lfn < 0.3) = [];
% for i_lf = 1 : length(lf_id)
%
% [~,ctx_km_c{i_lf}] = kmeans(samp_rgb(samp_lf == lf_id(i_lf),:),n_km,'EmptyAction','singleton');
%
% end
%
for i_n = 1 : length(wltree)
bkg_ftrs2{i_n} = [];
%bkg_idxs{i_n} = [];
end
for i_img = 1 : size(data.train.(ch).X,1)
ch = params.ch_list{i_ch};
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
gt_img = data.train.gts.X{i_img};
clear I;
for i_b = 1 : 3
I(:,:,i_b) = X{i_b};
end
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
% get to explore individual region recognised by individual leaf
% node
img_pg = size(leaf_image,1) * size(leaf_image,2);
%context_img = zeros(size(leaf_image));
% cxt_idx = 1;
n_leaf = 0;
ctx_c1 = [];
ctx_c2 = [];
n_samp_img = sum(leaf_image(:) > 0);
for i_n = 1 : length(wltree)
if(wltree(i_n).isLeaf)
ctx_c1(end + 1) = i_n;
n_leaf = n_leaf + 1;
nv = wltree(i_n).value;
n_idx = find(leaf_image == i_n);
if(length(n_idx) / n_samp_img > 0.2)
I_2D = reshape(I,[],3);
n_idx = downsample(n_idx,200);
bkg_ftrs2{i_n} = [ bkg_ftrs2{i_n}; I_2D(n_idx,:)];
end
end
end
% contx_list{i_w,i_img} = ctx_c2;
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
ctx_ftrs1 = zeros(size(samp_idx_img,1),length(ctx_c1));
% ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
for i_ctx = 1 : length(ctx_c1)
tStart = tic;
lf_ctx = (leaf_image == ctx_c1(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs1(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs1(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% set the pixels on the context as irrelevant to avoid the overfitting issues
ctx_ftrs1(ctx_ftrs1 < 0.1) = 5000;
mask_img = data.train.masks.X{i_img};
dist_ctx_map = bwdist(~mask_img);
ctx_ftrs1(:,end + 1) = dist_ctx_map(samp_idx_img);
ctx_ftrs1_w{i_w,i_img} = ctx_ftrs1;
end
n_km = 30;
ctx_c2 = [];
clear ftrs_kmc_c2;
kmc_ctx_c2 = [];
tleaf_ctx_c2 = [];
for i_n = 1 : length(wltree)
if(~isempty(bkg_ftrs2{i_n}))
tStart = tic;
[~,ftrs_kmc_tmp] = kmeans(bkg_ftrs2{i_n},n_km,'EmptyAction','singleton');
t1 = toc(tStart);
fprintf('Clustering the context ftrs 2 took %d seconds', t1);
ctx_c2(end + 1 : end + n_km) = (100 * i_n) + (1:n_km);
ftrs_kmc{i_w,i_n} = ftrs_kmc_tmp;
kmc_ctx_c2(end + 1: end + n_km,:) = ftrs_kmc_tmp;
tleaf_ctx_c2(end + 1: end + n_km,:) = i_n;
else
ftrs_kmc{i_w,i_n} = {};
end
end
n_ftrs2 = length(ctx_c2);
for i_img = 1 : size(data.train.(ch).X,1)
ctx_ftrs2_w{i_w,i_img} = [];
X = data.train.(ch).X(i_img,data.train.(ch).idxs);
tStart = tic;
% to avoid the computational burden, now apply the method only
% on some sample points
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,:);
[score_image,leaf_image] = predict_img_wl_sample(X,params,weak_learners(i_w),samp_idx_img(:,2:3));
t1 = toc(tStart);
fprintf( ' Evaluating the image %d took %d seconds \n', i_img, t1);
ftrs2_img = zeros(size(leaf_image));
samp_idx_img = samples_idx(samples_idx(:,1) == i_img,2:3);
samp_idx_img = sub2ind(size(leaf_image),samp_idx_img(:,1),samp_idx_img(:,2));
ctx_ftrs2 = zeros(size(samp_idx_img,1),length(ctx_c2));
for i_n = 1 : length(wltree)
if(~isempty(ftrs_kmc{i_w,i_n}))
ftrs2_img_tmp = ftrs_c2_img(X,ftrs_kmc{i_w,i_n});
ftrs2_img = (i_n * 100 + ftrs2_img_tmp);
% ftrs2_img = (i_n * 100 + ftrs2_img_tmp) .* (leaf_image == i_n);
end
end
for i_ctx = 1 : length(ctx_c2)
tStart = tic;
lf_ctx = (ftrs2_img == ctx_c2(i_ctx));
if(sum(lf_ctx(:)))
dist_ctx_map = bwdist(lf_ctx);
ctx_ftrs2(:,i_ctx) = dist_ctx_map(samp_idx_img);
else
ctx_ftrs2(:,i_ctx) = 5000;
end
t1 = toc(tStart);
fprintf( ' Calculating the distance map of %d of the image %d took %d seconds \n', i_ctx, i_img, t1);
end
% ctx_ftrs2(ctx_ftrs2 < 0.1) = 5000;
ctx_ftrs2_w{i_w,i_img} = ctx_ftrs2;
% clear ctx_ftrs2;
end
end
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
|
github
|
BII-wushuang/FLLIT-master
|
train_GB_ctx.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_GB_ctx.m
| 5,315 |
utf_8
|
614ffbd7be504c723ec2cb4499eaf099
|
% use the mask distance as well as the main branch distance
% evaluate the effect of auto context
% takes the gradient boost framework
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners,weak_learners_ctx] = train_GB_ctx(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
% specfically reserved for testing the effect of unchanged weight when
% extracting the features.
samples_no = size(samples_idx,1);
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
current_response_ctx = current_response;
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
params.mex_loss_type = mex_loss_type;
W = compute_wi(current_response);
R = compute_ri(current_response);
W_ctx = W;
R_ctx = R;
% assign the weight for each individual data point
wgt_samp = weight_sample_tol(data.train.gts,params,samples_idx);
% load the training images
X = data.train.imgs.X(:,data.train.imgs.idxs);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
W = W .* wgt_samp;
%%%%%%%%%%%%%%%%% train the base line weak learners%%%%%%%%%%%%%%%%%
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,...
weak_learners(i_w).reg_tree] = train_kernel_boost(X,params,samples_idx,T1_idx,T2_idx,W,R);
cached_responses = evaluate_weak_learners(X,params,samples_idx,weak_learners(i_w));
weak_learners(i_w).alpha = search_alpha(current_response,cached_responses,labels,params);
current_response = current_response + weak_learners(i_w).alpha * cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores(i_w,:) = weak_learner_scores(current_response,labels,wgt_samp,compute_loss);
%%%%%%%%%%%%%%%%%%%% complete training the base line weak learners %%
end
% collect the global features as well as auto context features, be aware
% of the global features, they are only prepared for the next round, so
% this part should be behind the context and auto context learning
ctx_glb_all = collect_global_ctx(X,data.train.masks,...
params,weak_learners(params.wl_no),samples_idx);
w_invar = 0;
i_ch = 1;
ch = 'imgs';
sub_ch_no = size(X,2);
X_idxs = 1 : sub_ch_no;
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
s_T1 = samples_idx(T1_idx,1:3);
% Learn an identify filters for the whole context gb tree
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
if(w_invar)
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression...
(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,W_init(wr_idxs),i_ch,i_s,ch);
else
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression...
(params,params.(ch),X(:,i_s),X_idxs,s_T1,R(T1_idx),W(T1_idx),i_ch,i_s,ch);
end
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
end
for i_w = 1 : params.wl_no_ctx
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
%%%%%%%%%%%% start training the ctx augmented weak learners%%%%%%%%%
% load the global context features
W_ctx = W_ctx .* wgt_samp;
[weak_learners_ctx(i_w).kernels,weak_learners_ctx(i_w).kernel_params,...
weak_learners_ctx(i_w).reg_tree, weak_learners_ctx(i_w).ctx_list]...
= train_kernel_gb_ctx(X,kernels,kernel_params,params,ctx_glb_all,...
samples_idx,W_ctx,R_ctx);
cached_responses_ctx = evaluate_weak_learners_ctx(X,params,ctx_glb_all,samples_idx,weak_learners_ctx(i_w));
weak_learners_ctx(i_w).alpha = search_alpha(current_response_ctx,cached_responses_ctx,labels,params);
current_response_ctx = current_response_ctx + weak_learners_ctx(i_w).alpha * cached_responses_ctx;
W_ctx = compute_wi(current_response_ctx);
R_ctx = compute_ri(current_response_ctx);
train_scores_ctx(i_w,:) = weak_learner_scores(current_response_ctx,labels,wgt_samp,compute_loss);
save([params.codename '_weak_learners_sav.mat'],'weak_learners_ctx','weak_learners');
save([params.codename '_train_scores_sav.mat'],'train_scores','train_scores_ctx');
%%%% complete training the global context feature weak learners
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
end
|
github
|
BII-wushuang/FLLIT-master
|
train_boost_general.m
|
.m
|
FLLIT-master/src/KernelBoost-v0.1/train_boost_general.m
| 6,090 |
utf_8
|
9d6c05c3d19de9ecd4d47fac5840fc11
|
%
% samples_idx(:,1) => sample image no
% samples_idx(:,2) => sample row
% samples_idx(:,3) => sample column
% samples_idx(:,4) => sample label (-1/+1)
function [weak_learners] = train_boost_general(params,data,samples_idx)
% Train a KernelBoost classifier on the given samples
%
% authors: Carlos Becker, Roberto Rigamonti, CVLab EPFL
% e-mail: name <dot> surname <at> epfl <dot> ch
% web: http://cvlab.epfl.ch/
% date: February 2014
samples_no = size(samples_idx,1);
weak_learners(params.wl_no).alpha = 0;
labels = samples_idx(:,4);
samples_idx = samples_idx(:,1:3);
current_response = zeros(samples_no,1);
[compute_wi,compute_ri,compute_loss,compute_indiv_loss,compute_2nd_deriv,mex_loss_type] = select_fncts(params,labels);
W = compute_wi(current_response);
R = compute_ri(current_response);
train_scores = zeros(params.wl_no,3);
for i_w = 1:params.wl_no
t_wl = tic;
fprintf(' Learning WL %d/%d\n',i_w,params.wl_no);
% Indexes of the two training subparts
T1_idx = sort(randperm(length(labels),params.T1_size),'ascend');
T2_idx = sort(randperm(length(labels),params.T2_size),'ascend');
[wr_idxs,wr_responses,wr_weights] = compute_wr(params,T1_idx,W,R,compute_indiv_loss,compute_2nd_deriv,labels,current_response);
s_T1 = samples_idx(wr_idxs,1:3);
s_T2 = samples_idx(T2_idx,1:3);
features = cell(params.ch_no,1);
kernels = cell(params.ch_no,1);
kernel_params = cell(params.ch_no,1);
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
fprintf(' Learning channel %s (%d/%d)\n',ch,i_ch,params.ch_no);
X = data.train.(ch).X(:,data.train.(ch).idxs);
X_idxs = data.train.(ch).idxs;
sub_ch_no = data.train.(ch).sub_ch_no;
features{i_ch} = cell(sub_ch_no,1);
kernels{i_ch} = cell(sub_ch_no,1);
kernel_params{i_ch} = cell(sub_ch_no,1);
% Learn the filters
fprintf(' Learning filters on the sub-channels\n');
for i_s = 1:sub_ch_no
t_sch = tic;
fprintf(' Learning on subchannel %d/%d of channel %s\n',i_s,sub_ch_no,ch);
[kernels{i_ch}{i_s},kernel_params{i_ch}{i_s}] = mexMultipleSmoothRegression(params,params.(ch),X(:,i_s),X_idxs,s_T1,wr_responses,wr_weights,i_ch,i_s,ch);
sch_time = toc(t_sch);
fprintf(' Completed, learned %d filters in %f seconds\n',length(kernels{i_ch}{i_s}),sch_time);
t_ev = tic;
fprintf(' Evaluating the filters learned on the subchannel\n');
features{i_ch}{i_s} = mexEvaluateKernels(X(:,i_s),s_T2(:,1:3),params.sample_size,kernels{i_ch}{i_s},kernel_params{i_ch}{i_s});
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
end
end
fprintf(' Merging features and kernels...\n');
[kernels,kernel_params,features] = merge_features_kernels(kernels,kernel_params,features);
fprintf(' Done!\n');
fprintf(' Training regression tree on learned features...\n');
t_tr = tic;
reg_tree = LDARegStumpTrain(single(features),R(T2_idx),W(T2_idx)/sum(W(T2_idx)),uint32(params.tree_depth));
time_tr = toc(t_tr);
fprintf(' Done! (took %f seconds)\n',time_tr);
fprintf(' Removing useless kernels...\n');
[weak_learners(i_w).kernels,weak_learners(i_w).kernel_params,weak_learners(i_w).reg_tree] = remove_useless_filters(reg_tree,kernels,kernel_params);
t_ev = tic;
fprintf(' Evaluating the learned kernels on the whole training set...\n');
features = zeros(length(labels),length(weak_learners(i_w).kernels));
for i_ch = 1:params.ch_no
ch = params.ch_list{i_ch};
sub_ch_no = data.train.(ch).sub_ch_no;
X = data.train.(ch).X(:,data.train.(ch).idxs);
for i_s = 1:sub_ch_no
idxs = find(cellfun(@(x)(x.ch_no==i_ch && x.sub_ch_no==i_s),weak_learners(i_w).kernel_params));
if (~isempty(idxs))
features(:,idxs) = mexEvaluateKernels(X(:,i_s),samples_idx(:,1:3),params.sample_size,weak_learners(i_w).kernels(idxs),weak_learners(i_w).kernel_params(idxs));
end
end
end
ev_time = toc(t_ev);
fprintf(' Evaluation completed in %f seconds\n',ev_time);
fprintf(' Performing prediction on the whole training set...\n');
t_pr = tic;
cached_responses = LDARegStumpPredict(weak_learners(i_w).reg_tree,single(features));
time_pr = toc(t_pr);
fprintf(' Prediction finished, took %f seconds\n',time_pr);
clear features;
fprintf(' Finding alpha through line search...\n');
t_alp = tic;
alpha = mexLineSearch(current_response,cached_responses,labels,mex_loss_type);
time_alp = toc(t_alp);
fprintf(' Good alpha found (alpha=%f), took %f seconds\n',alpha,time_alp);
alpha = alpha * params.shrinkage_factor;
current_response = current_response + alpha*cached_responses;
W = compute_wi(current_response);
R = compute_ri(current_response);
weak_learners(i_w).alpha = alpha;
MR = sum((current_response>0)~=(labels>0))/length(labels);
fprintf(' Misclassif rate: %.2f | Loss: %f\n',100*MR,compute_loss(current_response));
train_scores(i_w,1) = 100*MR;
train_scores(i_w,2) = compute_loss(current_response);
train_scores(i_w,3) = alpha;
wl_time = toc(t_wl);
fprintf(' Learning WL %d took %f seconds\n------------------------------------------------\n\n',i_w,wl_time);
end
if(0)
clf;
figure(1);
plot(1:params.wl_no,train_scores(:,1),'b')
legend('MR');
saveas(gcf,fullfile(params.results_dir,'MR_train_scores.jpg'),'jpg');
figure(2);
plot(1:params.wl_no,train_scores(:,2),'g');
legend('loss');
saveas(gcf,fullfile(params.results_dir,'LOSS_train_scores.jpg'),'jpg');
figure(3);
plot(1:params.wl_no,train_scores(:,3),'r');
legend('alpha');
saveas(gcf,fullfile(params.results_dir,'ALPHA_train_scores.jpg'),'jpg');
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.