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
happyharrycn/unsupervised_edges-master
edgesEvalImgFast.m
.m
unsupervised_edges-master/structured_edges/edgesEvalImgFast.m
4,994
utf_8
3470ed4119e98435cb12f7c47902934e
function [thrs,cntR,sumR,cntP,sumP,V] = edgesEvalImgFast( E, G, varargin ) % Calculate edge precision/recall results for single edge image. % % Enhanced replacement for evaluation_bdry_image() from BSDS500 code: % http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/ % Uses same format and is fully compatible with evaluation_bdry_image. % Given default prms results are *identical* to evaluation_bdry_image. % % In addition to performing the evaluation, this function can optionally % create a visualization of the matches and errors for a given edge result. % The visualization of edge matches V has the following color coding: % green=true positive, blue=false positive, red=false negative % If multiple ground truth labels are given the false negatives have % varying strength (and true positives can match *any* ground truth). % % This function calls the mex file correspondPixels. Pre-compiled binaries % for some systems are provided in /private, source for correspondPixels is % available as part of the BSDS500 dataset (see link above). Note: % correspondPixels is computationally expensive and very slow in practice. % % USAGE % [thrs,cntR,sumR,cntP,sumP,V] = edgesEvalImg( E, G, [prms] ) % % INPUTS % E - [h x w] edge probability map (may be a filename) % G - file containing a cell of ground truth boundaries % prms - parameters (struct or name/value pairs) % .out - [''] optional output file for writing results % .thrs - [99] number or vector of thresholds for evaluation % .maxDist - [.0075] maximum tolerance for edge match % .thin - [1] if true thin boundary maps % .scale = [1] resize the gt and image for evalution % % OUTPUTS % thrs - [Kx1] vector of threshold values % cntR,sumR - [Kx1] ratios give recall per threshold % cntP,sumP - [Kx1] ratios give precision per threshold % V - [hxwx3xK] visualization of edge matches % % EXAMPLE % % See also edgesEvalDirFast % % Structured Edge Detection Toolbox Version 3.01 % Code written by Piotr Dollar, 2014. Modified by Yin Li % Licensed under the MSR-LA Full Rights License [see license.txt] % get additional parameters dfs={ 'out','', 'thrs',39, 'maxDist',.0075, 'thin',1 , 'scale', 1.0}; [out,thrs,maxDist,thin, scale] = getPrmDflt(varargin,dfs,1); if(any(mod(thrs,1)>0)), K=length(thrs); thrs=thrs(:); else K=thrs; thrs=linspace(1/(K+1),1-1/(K+1),K)'; end % load edges (E) and ground truth (G) if(all(ischar(E))), E=double(imread(E))/255; if (scale-1.0) > eps E=imresize(E, scale, 'nearest'); end end G=load(G); G=G.groundTruth; n=length(G); for g=1:n, G{g}=double(G{g}.Boundaries); if abs(scale-1.0) > eps G{g}=imresize(G{g}, scale, 'nearest'); end end % evaluate edge result at each threshold Z=zeros(K,1); cntR=Z; sumR=Z; cntP=Z; sumP=Z; if(nargout>=6), V=zeros([size(E) 3 K]); end for k = 1:K % threshhold and thin E E1 = double(E>=max(eps,thrs(k))); if(thin), E1=double(bwmorph(E1,'thin',inf)); end % compare to each ground truth in turn and accumualte Z=zeros(size(E)); matchE=Z; matchG=Z; allG=Z; for g = 1:n [matchE1,matchG1] = correspondPixels(E1,G{g},maxDist); matchE = matchE | matchE1>0; matchG = matchG + double(matchG1>0); allG = allG + G{g}; end % compute recall (summed over each gt image) cntR(k) = sum(matchG(:)); sumR(k) = sum(allG(:)); % compute precision (edges can match any gt image) cntP(k) = nnz(matchE); sumP(k) = nnz(E1); % optinally create visualization of matches if(nargout<6), continue; end; cs=[1 0 0; 0 .7 0; .7 .8 1]; cs=cs-1; FP=E1-matchE; TP=matchE; FN=(allG-matchG)/n; for g=1:3, V(:,:,g,k)=max(0,1+FN*cs(1,g)+TP*cs(2,g)+FP*cs(3,g)); end V(:,2:end,:,k) = min(V(:,2:end,:,k),V(:,1:end-1,:,k)); V(2:end,:,:,k) = min(V(2:end,:,:,k),V(1:end-1,:,:,k)); end % if output file specified write results to disk [thrs2, cntR2, sumR2, cntP2, sumP2] = quadInterpolate(thrs, cntR, sumR, cntP, sumP, 100); if(isempty(out)), return; end; fid=fopen(out,'w'); assert(fid~=1); fprintf(fid,'%10g %10g %10g %10g %10g\n',[thrs2 cntR2 sumR2 cntP2 sumP2]'); fclose(fid); end % interpolate the PR curve by quadratic function function [thrs2, cntR2, sumR2, cntP2, sumP2] = quadInterpolate(thrs, cntR, sumR, cntP, sumP,K) thrs2 = linspace(0.01,1,K)';thrs2 = [0.005;thrs2]; sumR2 = interp1(thrs, sumR, thrs2, 'spline'); sumR2 = max(round(sumR2),0); sumP2 = interp1(thrs, sumP, thrs2, 'spline'); [~, ind] = min(sumP2); sumP2(ind+1:end)=0;sumP2 = max(round(sumP2),0); R = cntR./(sumR+eps); R2 = interp1(thrs, R, thrs2,'spline');[~, ind] = min(R2);R2(ind+1:end)=0; R2 = min(R2,1);R2 = max(R2,0); cntR2 = R2.*sumR2;cntR2 = max(round(cntR2),0); P = cntP./(sumP+eps); try P2 = interp1(thrs, P, thrs2, 'spline'); %P2 = spline(thrs, P, thrs2); catch print('oops\n'); P2 = interp1(thrs, P, thrs2, 'linear'); end P2 = min(P2,1);P2 = max(P2,0); cntP2 = P2.*sumP2; cntP2 = max(round(cntP2),0); end
github
happyharrycn/unsupervised_edges-master
edgesEvalDir.m
.m
unsupervised_edges-master/structured_edges/edgesEvalDir.m
5,852
utf_8
b708b92045eaa75fa68d09e169447bb6
function varargout = edgesEvalDir( varargin ) % Calculate edge precision/recall results for directory of edge images. % % Enhanced replacement for boundaryBench() from BSDS500 code: % http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/ % Uses same format for results and is fully compatible with boundaryBench. % Given default prms results are *identical* to boundaryBench with the % additional 9th output of R50 (recall at 50% precision). % % The odsF/P/R/T are results at the ODS (optimal dataset scale). % The oisF/P/R are results at the OIS (optimal image scale). % Naming convention: P=precision, R=recall, F=2/(1/P+1/R), T=threshold. % % In addition to the outputs, edgesEvalDir() creates three files: % eval_bdry_img.txt - per image OIS results [imgId T R P F] % eval_bdry_thr.txt - per threshold ODS results [T R P F] % eval_bdry.txt - complete results (*re-ordered* copy of output) % These files are identical to the ones created by boundaryBench. % % USAGE % [odsF,odsP,odsR,odsT,oisF,oisP,oisR,AP,R50] = edgesEvalDir( prms ) % [ODS,~,~,~,OIS,~,~,AP,R50] = edgesEvalDir( prms ) % % INPUTS % prms - parameters (struct or name/value pairs) % .resDir - ['REQ'] dir containing edge detection results (.png) % .gtDir - ['REQ'] dir containing ground truth (.mat) % .pDistr - [{'type','parfor'}] parameters for fevalDistr % .cleanup - [0] if true delete temporary files % .thrs - [99] number or vector of thresholds for evaluation % .maxDist - [.0075] maximum tolerance for edge match % .thin - [1] if true thin boundary maps % % OUTPUTS % odsF/P/R/T - F-measure, precision, recall and threshold at ODS % oisF/P/R - F-measure, precision, and recall at OIS % AP - average precision % R50 - recall at 50% precision % % EXAMPLE % % See also edgesEvalImg, edgesEvalPlot % % Structured Edge Detection Toolbox Version 3.01 % Code written by Piotr Dollar, 2014. % Licensed under the MSR-LA Full Rights License [see license.txt] % get additional parameters dfs={ 'resDir','REQ', 'gtDir','REQ', 'pDistr',{{'type','parfor'}}, ... 'cleanup',0, 'thrs',99, 'maxDist',.0075, 'thin',1 }; p=getPrmDflt(varargin,dfs,1); resDir=p.resDir; gtDir=p.gtDir; evalDir=[resDir '-eval/']; if(~exist(evalDir,'dir')), mkdir(evalDir); end % check if results already exist, if so load and return fNm = fullfile(evalDir,'eval_bdry.txt'); if(exist(fNm,'file')), R=dlmread(fNm); R=mat2cell2(R,[1 8]); varargout=R([4 3 2 1 7 6 5 8]); if(nargout<=8), return; end; R=dlmread(fullfile(evalDir,'eval_bdry_thr.txt')); P=R(:,3); R=R(:,2); [~,o]=unique(P); R50=interp1(P(o),R(o),max(P(o(1)),.5)); varargout=[varargout R50]; return; end % perform evaluation on each image (this part can be very slow) assert(exist(resDir,'dir')==7); assert(exist(gtDir,'dir')==7); ids=dir(fullfile(gtDir,'*.mat')); ids={ids.name}; n=length(ids); do=false(1,n); jobs=cell(1,n); res=cell(1,n); for i=1:n, id=ids{i}(1:end-4); res{i}=fullfile(evalDir,[id '_ev1.txt']); do(i)=~exist(res{i},'file'); im1=fullfile(resDir,[id '.png']); gt1=fullfile(gtDir,[id '.mat']); jobs{i}={im1,gt1,'out',res{i},'thrs',p.thrs,'maxDist',p.maxDist,... 'thin',p.thin}; if(0), edgesEvalImg(jobs{i}{:}); end end fevalDistr('edgesEvalImg',jobs(do),p.pDistr{:}); % collect evaluation results I=dlmread(res{1}); T=I(:,1); Z=zeros(numel(T),1); cntR=Z; sumR=Z; cntP=Z; sumP=Z; oisCntR=0; oisSumR=0; oisCntP=0; oisSumP=0; scores=zeros(n,5); for i=1:n % load image results and accumulate I = dlmread(res{i}); cntR1=I(:,2); cntR=cntR+cntR1; sumR1=I(:,3); sumR=sumR+sumR1; cntP1=I(:,4); cntP=cntP+cntP1; sumP1=I(:,5); sumP=sumP+sumP1; % compute OIS scores for image [R,P,F] = computeRPF(cntR1,sumR1,cntP1,sumP1); [~,k]=max(F); [oisR1,oisP1,oisF1,oisT1] = findBestRPF(T,R,P); scores(i,:) = [i oisT1 oisR1 oisP1 oisF1]; % oisCnt/Sum will be used to compute dataset OIS scores oisCntR=oisCntR+cntR1(k); oisSumR=oisSumR+sumR1(k); oisCntP=oisCntP+cntP1(k); oisSumP=oisSumP+sumP1(k); end % compute ODS R/P/F and OIS R/P/F [R,P,F] = computeRPF(cntR,sumR,cntP,sumP); [odsR,odsP,odsF,odsT] = findBestRPF(T,R,P); [oisR,oisP,oisF] = computeRPF(oisCntR,oisSumR,oisCntP,oisSumP); % compute AP/R50 (interpolating 100 values, has minor bug: should be /101) if(0), R=[0; R; 1]; P=[1; P; 0]; F=[0; F; 0]; T=[1; T; 0]; end [~,k]=unique(R); k=k(end:-1:1); R=R(k); P=P(k); T=T(k); F=F(k); AP=0; if(numel(R)>1), AP=interp1(R,P,0:.01:1); AP=sum(AP(~isnan(AP)))/100; end [~,o]=unique(P); R50=interp1(P(o),R(o),max(P(o(1)),.5)); % write results to disk varargout = {odsF,odsP,odsR,odsT,oisF,oisP,oisR,AP,R50}; writeRes(evalDir,'eval_bdry_img.txt',scores); writeRes(evalDir,'eval_bdry_thr.txt',[T R P F]); writeRes(evalDir,'eval_bdry.txt',[varargout{[4 3 2 1 7 6 5 8]}]); % optionally perform cleanup if( p.cleanup ), delete([evalDir '/*_ev1.txt']); delete([resDir '/*.png']); rmdir(resDir); end end function [R,P,F] = computeRPF(cntR,sumR,cntP,sumP) % compute precision, recall and F measure given cnts and sums R=cntR./max(eps,sumR); P=cntP./max(eps,sumP); F=2*P.*R./max(eps,P+R); end function [bstR,bstP,bstF,bstT] = findBestRPF(T,R,P) % linearly interpolate to find best thr for optimizing F if(numel(T)==1), bstT=T; bstR=R; bstP=P; bstF=2*P.*R./max(eps,P+R); return; end A=linspace(0,1,100); B=1-A; bstF=-1; for j = 2:numel(T) Rj=R(j).*A+R(j-1).*B; Pj=P(j).*A+P(j-1).*B; Tj=T(j).*A+T(j-1).*B; Fj=2.*Pj.*Rj./max(eps,Pj+Rj); [f,k]=max(Fj); if(f>bstF), bstT=Tj(k); bstR=Rj(k); bstP=Pj(k); bstF=f; end end end function writeRes( alg, fNm, vals ) % write results to disk k=size(vals,2); fNm=fullfile(alg,fNm); fid=fopen(fNm,'w'); if(fid==-1), error('Could not open file %s for writing.',fNm); end frmt=repmat('%10g ',[1 k]); frmt=[frmt(1:end-1) '\n']; fprintf(fid,frmt,vals'); fclose(fid); end
github
happyharrycn/unsupervised_edges-master
edgesEvalDirFast.m
.m
unsupervised_edges-master/structured_edges/edgesEvalDirFast.m
5,998
utf_8
2705468968d13cfb5879826f8fc1a673
function varargout = edgesEvalDirFast( varargin ) % Calculate edge precision/recall results for directory of edge images. % % Enhanced replacement for boundaryBench() from BSDS500 code: % http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/ % Uses same format for results and is fully compatible with boundaryBench. % Given default prms results are *identical* to boundaryBench with the % additional 9th output of R50 (recall at 50% precision). % % The odsF/P/R/T are results at the ODS (optimal dataset scale). % The oisF/P/R are results at the OIS (optimal image scale). % Naming convention: P=precision, R=recall, F=2/(1/P+1/R), T=threshold. % % In addition to the outputs, edgesEvalDir() creates three files: % eval_bdry_img.txt - per image OIS results [imgId T R P F] % eval_bdry_thr.txt - per threshold ODS results [T R P F] % eval_bdry.txt - complete results (*re-ordered* copy of output) % These files are identical to the ones created by boundaryBench. % % USAGE % [odsF,odsP,odsR,odsT,oisF,oisP,oisR,AP,R50] = edgesEvalDir( prms ) % [ODS,~,~,~,OIS,~,~,AP,R50] = edgesEvalDir( prms ) % % INPUTS % prms - parameters (struct or name/value pairs) % .resDir - ['REQ'] dir containing edge detection results (.png) % .gtDir - ['REQ'] dir containing ground truth (.mat) % .pDistr - [{'type','parfor'}] parameters for fevalDistr % .cleanup - [0] if true delete temporary files % .thrs - [99] number or vector of thresholds for evaluation % .maxDist - [.0075] maximum tolerance for edge match % .thin - [1] if true thin boundary maps % % OUTPUTS % odsF/P/R/T - F-measure, precision, recall and threshold at ODS % oisF/P/R - F-measure, precision, and recall at OIS % AP - average precision % R50 - recall at 50% precision % % EXAMPLE % % See also edgesEvalImg, edgesEvalPlot % % Structured Edge Detection Toolbox Version 3.01 % Code written by Piotr Dollar, 2014. Modified by Yin Li % Licensed under the MSR-LA Full Rights License [see license.txt] % get additional parameters dfs={ 'resDir','REQ', 'gtDir','REQ', 'pDistr',{{'type','parfor'}}, ... 'cleanup',0, 'thrs',39, 'maxDist',.0075, 'thin',1, 'scale', 1 }; p=getPrmDflt(varargin,dfs,1); resDir=p.resDir; gtDir=p.gtDir; evalDir=[resDir '-eval/']; if(~exist(evalDir,'dir')), mkdir(evalDir); end % check if results already exist, if so load and return fNm = fullfile(evalDir,'eval_bdry.txt'); if(exist(fNm,'file')), R=dlmread(fNm); R=mat2cell2(R,[1 8]); varargout=R([4 3 2 1 7 6 5 8]); if(nargout<=8), return; end; R=dlmread(fullfile(evalDir,'eval_bdry_thr.txt')); P=R(:,3); R=R(:,2); [~,o]=unique(P); R50=interp1(P(o),R(o),max(P(o(1)),.5)); varargout=[varargout R50]; return; end % perform evaluation on each image (this part can be very slow) assert(exist(resDir,'dir')==7); assert(exist(gtDir,'dir')==7); ids=dir(fullfile(gtDir,'*.mat')); ids={ids.name}; n=length(ids); do=false(1,n); jobs=cell(1,n); res=cell(1,n); for i=1:n, id=ids{i}(1:end-4); res{i}=fullfile(evalDir,[id '_ev1.txt']); do(i)=~exist(res{i},'file'); im1=fullfile(resDir,[id '.png']); gt1=fullfile(gtDir,[id '.mat']); if exist(im1, 'file') && exist(gt1, 'file') jobs{i}={im1,gt1,'out',res{i},'thrs',p.thrs,'maxDist',p.maxDist,... 'thin',p.thin, 'scale', p.scale}; else do(i) = false; fprintf('Warning: %s missing!\n', im1); end end fevalDistr('edgesEvalImgFast',jobs(do),p.pDistr{:}); % collect evaluation results I=dlmread(res{1}); T=I(:,1); Z=zeros(numel(T),1); cntR=Z; sumR=Z; cntP=Z; sumP=Z; oisCntR=0; oisSumR=0; oisCntP=0; oisSumP=0; scores=zeros(n,5); for i=1:n % load image results and accumulate I = dlmread(res{i}); cntR1=I(:,2); cntR=cntR+cntR1; sumR1=I(:,3); sumR=sumR+sumR1; cntP1=I(:,4); cntP=cntP+cntP1; sumP1=I(:,5); sumP=sumP+sumP1; % compute OIS scores for image [R,P,F] = computeRPF(cntR1,sumR1,cntP1,sumP1); [~,k]=max(F); [oisR1,oisP1,oisF1,oisT1] = findBestRPF(T,R,P); scores(i,:) = [i oisT1 oisR1 oisP1 oisF1]; % oisCnt/Sum will be used to compute dataset OIS scores oisCntR=oisCntR+cntR1(k); oisSumR=oisSumR+sumR1(k); oisCntP=oisCntP+cntP1(k); oisSumP=oisSumP+sumP1(k); end % compute ODS R/P/F and OIS R/P/F [R,P,F] = computeRPF(cntR,sumR,cntP,sumP); [odsR,odsP,odsF,odsT] = findBestRPF(T,R,P); [oisR,oisP,oisF] = computeRPF(oisCntR,oisSumR,oisCntP,oisSumP); % compute AP/R50 (interpolating 100 values, has minor bug: should be /101) if(0), R=[0; R; 1]; P=[1; P; 0]; F=[0; F; 0]; T=[1; T; 0]; end [~,k]=unique(R); k=k(end:-1:1); R=R(k); P=P(k); T=T(k); F=F(k); AP=0; if(numel(R)>1), AP=interp1(R,P,0:.01:1); AP=sum(AP(~isnan(AP)))/100; end [~,o]=unique(P); R50=interp1(P(o),R(o),max(P(o(1)),.5)); % write results to disk varargout = {odsF,odsP,odsR,odsT,oisF,oisP,oisR,AP,R50}; writeRes(evalDir,'eval_bdry_img.txt',scores); writeRes(evalDir,'eval_bdry_thr.txt',[T R P F]); writeRes(evalDir,'eval_bdry.txt',[varargout{[4 3 2 1 7 6 5 8]}]); % optionally perform cleanup if( p.cleanup ), delete([evalDir '/*_ev1.txt']); delete([resDir '/*.png']); rmdir(resDir); end end function [R,P,F] = computeRPF(cntR,sumR,cntP,sumP) % compute precision, recall and F measure given cnts and sums R=cntR./max(eps,sumR); P=cntP./max(eps,sumP); F=2*P.*R./max(eps,P+R); end function [bstR,bstP,bstF,bstT] = findBestRPF(T,R,P) % linearly interpolate to find best thr for optimizing F if(numel(T)==1), bstT=T; bstR=R; bstP=P; bstF=2*P.*R./max(eps,P+R); return; end A=linspace(0,1,100); B=1-A; bstF=-1; for j = 2:numel(T) Rj=R(j).*A+R(j-1).*B; Pj=P(j).*A+P(j-1).*B; Tj=T(j).*A+T(j-1).*B; Fj=2.*Pj.*Rj./max(eps,Pj+Rj); [f,k]=max(Fj); if(f>bstF), bstT=Tj(k); bstR=Rj(k); bstP=Pj(k); bstF=f; end end end function writeRes( alg, fNm, vals ) % write results to disk k=size(vals,2); fNm=fullfile(alg,fNm); fid=fopen(fNm,'w'); if(fid==-1), error('Could not open file %s for writing.',fNm); end frmt=repmat('%10g ',[1 k]); frmt=[frmt(1:end-1) '\n']; fprintf(fid,frmt,vals'); fclose(fid); end
github
happyharrycn/unsupervised_edges-master
edgesTrain.m
.m
unsupervised_edges-master/structured_edges/edgesTrain.m
16,041
utf_8
3df2375071950b7d0bbce36c6111524e
function model = edgesTrain( trnImgDir, trnGtDir, varargin ) % Train structured edge detector. % % For an introductory tutorial please see edgesDemo.m. % % USAGE % opts = edgesTrain() % model = edgesTrain( trnImgDir, trnGtDir, opts ) % % INPUTS % trnImgDir - folder with all training images % trnGtDir - folder with all edge maps % opts - parameters (struct or name/value pairs) % (1) model parameters: % .imWidth - [32] width of image patches % .gtWidth - [16] width of ground truth patches % (2) tree parameters: % .nPos - [5e5] number of positive patches per tree % .nNeg - [5e5] number of negative patches per tree % .nImgs - [inf] maximum number of images to use for training % .nTrees - [8] number of trees in forest to train % .fracFtrs - [1/4] fraction of features to use to train each tree % .minCount - [1] minimum number of data points to allow split % .minChild - [8] minimum number of data points allowed at child nodes % .maxDepth - [64] maximum depth of tree % .discretize - ['pca'] options include 'pca' and 'kmeans' % .nSamples - [256] number of samples for clustering structured labels % .nClasses - [2] number of classes (clusters) for binary splits % .split - ['gini'] options include 'gini', 'entropy' and 'twoing' % (3) feature parameters: % .nOrients - [4] number of orientations per gradient scale % .grdSmooth - [0] radius for image gradient smoothing (using convTri) % .chnSmooth - [2] radius for reg channel smoothing (using convTri) % .simSmooth - [8] radius for sim channel smoothing (using convTri) % .normRad - [4] gradient normalization radius (see gradientMag) % .shrink - [2] amount to shrink channels % .nCells - [5] number of self similarity cells % .rgbd - [0] 0:RGB, 1:depth, 2:RBG+depth (for NYU data only) % (4) detection parameters (can be altered after training): % .stride - [2] stride at which to compute edges % .multiscale - [0] if true run multiscale edge detector % .sharpen - [2] sharpening amount (can only decrease after training) % .nTreesEval - [4] number of trees to evaluate per location % .nThreads - [4] number of threads for evaluation of trees % .nms - [0] if true apply non-maximum suppression to edges % (5) other parameters: % .seed - [1] seed for random stream (for reproducibility) % .useParfor - [0] if true train trees in parallel (memory intensive) % .modelDir - ['models/'] target directory for storing models % .modelFnm - ['model'] model filename % .bsdsDir - ['BSR/BSDS500/data/'] location of BSDS dataset % .scale = [1] scale factor for gt and images % % OUTPUTS % model - trained structured edge detector w the following fields % .opts - input parameters and constants % .thrs - [nNodes x nTrees] threshold corresponding to each fid % .fids - [nNodes x nTrees] feature ids for each node % .child - [nNodes x nTrees] index of child for each node % .count - [nNodes x nTrees] number of data points at each node % .depth - [nNodes x nTrees] depth of each node % .eBins - data structure for storing all node edge maps % .eBnds - data structure for storing all node edge maps % % EXAMPLE % % See also edgesDemo, edgesChns, edgesDetect, forestTrain % % Structured Edge Detection Toolbox Version 3.01 % Code written by Piotr Dollar, 2014. Modified by Yin % Licensed under the MSR-LA Full Rights License [see license.txt] % get default parameters % I have hard coded some param here dfs={'imWidth',32, 'gtWidth',16, 'nPos', 5e5, 'nNeg', 5e5, 'nImgs',inf, ... 'nTrees',8, 'fracFtrs',1/4, 'minCount',1, 'minChild',8, ... 'maxDepth',64, 'discretize','pca', 'nSamples',256, 'nClasses',2, ... 'split','gini', 'nOrients',4, 'grdSmooth',0, 'chnSmooth',2, ... 'simSmooth',8, 'normRad',4, 'shrink',2, 'nCells',5, 'rgbd',0, ... 'stride',2, 'multiscale',1, 'sharpen',2, 'nTreesEval',4, ... 'nThreads', 4, 'nms',0, 'seed',1, 'useParfor', 1, 'modelDir','./tmp/', ... 'modelFnm','model', 'scale', 1, 'nGt', 4, 'threshBracket', [0.1 0.4]}; opts = getPrmDflt(varargin,dfs,1); if(nargin==0), model=opts; return; end % if forest exists load it and return % modelDir -> param.tmpFolder % modelFnm -> param.dataset + param.iter cd(fileparts(mfilename('fullpath'))); forestDir = [opts.modelDir '/forest/']; forestFn = [forestDir opts.modelFnm]; if(exist([forestFn '.mat'], 'file')) load([forestFn '.mat']); return; end % compute constants and store in opts nTrees=opts.nTrees; nCells=opts.nCells; shrink=opts.shrink; opts.nPos=round(opts.nPos); opts.nNeg=round(opts.nNeg); opts.nTreesEval=min(opts.nTreesEval,nTrees); opts.stride=max(opts.stride,shrink); imWidth=opts.imWidth; gtWidth=opts.gtWidth; imWidth=round(max(gtWidth,imWidth)/shrink/2)*shrink*2; opts.imWidth=imWidth; opts.gtWidth=gtWidth; nChnsGrad=(opts.nOrients+1)*2; nChnsColor=3; nChns = nChnsGrad+nChnsColor; opts.nChns = nChns; opts.nChnFtrs = imWidth*imWidth*nChns/shrink/shrink; opts.nSimFtrs = (nCells*nCells)*(nCells*nCells-1)/2*nChns; opts.nTotFtrs = opts.nChnFtrs + opts.nSimFtrs; disp(opts); % generate stream for reproducibility of model stream=RandStream('mrg32k3a','Seed',opts.seed); % train nTrees random trees (can be trained with parfor if enough memory) if(opts.useParfor), parfor i=1:nTrees, trainTree(trnImgDir, trnGtDir, opts,stream,i); end else for i=1:nTrees, trainTree(trnImgDir, trnGtDir, opts,stream,i); end end % merge trees and save model model = mergeTrees( opts ); if(~exist(forestDir,'dir')), mkdir(forestDir); end save([forestFn '.mat'], 'model', '-v7.3'); end %% merging all trees into forest function model = mergeTrees( opts ) % accumulate trees and merge into final model nTrees=opts.nTrees; gtWidth=opts.gtWidth; treeFn = [opts.modelDir '/tree/' opts.modelFnm '_tree']; for i=1:nTrees t=load([treeFn int2str2(i,3) '.mat'],'tree'); t=t.tree; if(i==1), trees=t(ones(1,nTrees)); else trees(i)=t; end end nNodes=0; for i=1:nTrees, nNodes=max(nNodes,size(trees(i).fids,1)); end % merge all fields of all trees model.opts=opts; Z=zeros(nNodes,nTrees,'uint32'); model.thrs=zeros(nNodes,nTrees,'single'); model.fids=Z; model.child=Z; model.count=Z; model.depth=Z; model.segs=zeros(gtWidth,gtWidth,nNodes,nTrees,'uint8'); for i=1:nTrees, tree=trees(i); nNodes1=size(tree.fids,1); model.fids(1:nNodes1,i) = tree.fids; model.thrs(1:nNodes1,i) = tree.thrs; model.child(1:nNodes1,i) = tree.child; model.count(1:nNodes1,i) = tree.count; model.depth(1:nNodes1,i) = tree.depth; model.segs(:,:,1:nNodes1,i) = tree.hs-1; end % remove very small segments (<=5 pixels) segs=model.segs; nSegs=squeeze(max(max(segs)))+1; parfor i=1:nTrees*nNodes, m=nSegs(i); if(m==1), continue; end; S=segs(:,:,i); del=0; for j=1:m, Sj=(S==j-1); if(nnz(Sj)>5), continue; end S(Sj)=median(single(S(convTri(single(Sj),1)>0))); del=1; end if(del), [~,~,S]=unique(S); S=reshape(S-1,gtWidth,gtWidth); segs(:,:,i)=S; nSegs(i)=max(S(:))+1; end end model.segs=segs; model.nSegs=nSegs; % store compact representations of sparse binary edge patches nBnds=opts.sharpen+1; eBins=cell(nTrees*nNodes,nBnds); eBnds=zeros(nNodes*nTrees,nBnds); parfor i=1:nTrees*nNodes if(model.child(i) || model.nSegs(i)==1), continue; end %#ok<PFBNS> E=gradientMag(single(model.segs(:,:,i)))>.01; E0=0; % eBins stores the sparse edge coordinates for all segments % eBnds stores the number of edge pixels for all segments for j=1:nBnds, eBins{i,j}=uint16(find(E & ~E0)'-1); E0=E; eBnds(i,j)=length(eBins{i,j}); E=convTri(single(E),1)>.01; end end eBins=eBins'; model.eBins=[eBins{:}]'; % eBnds now stores the index of each sparse edge structure eBnds=eBnds'; model.eBnds=uint32([0; cumsum(eBnds(:))]); end %% the main function for training function trainTree( trnImgDir, trnGtDir, opts, stream, treeInd ) % Train a single tree in forest model. % location of ground truth % note we will only train on the images with GT results imgIds=dir(fullfile(trnGtDir, '*.png')); fileExt = '.png'; if isempty(imgIds); imgIds = dir(fullfile(trnGtDir, '*.jpg')); fileExt = '.jpg'; end imgIds=imgIds([imgIds.bytes]>0); imgIds={imgIds.name}; nImgs=length(imgIds); for i=1:nImgs, imgIds{i}=imgIds{i}(1:end-4); end % extract commonly used options imWidth=opts.imWidth; imRadius=imWidth/2; gtWidth=opts.gtWidth; gtRadius=gtWidth/2; nChns=opts.nChns; nTotFtrs=opts.nTotFtrs; nPos=opts.nPos; nNeg=opts.nNeg; shrink=opts.shrink; % finalize setup treeDir = [opts.modelDir '/tree/']; treeFn = [treeDir opts.modelFnm '_tree']; if(exist([treeFn int2str2(treeInd,3) '.mat'],'file')) fprintf('Reusing tree %d of %d\n',treeInd,opts.nTrees); return; end fprintf('\n-------------------------------------------\n'); fprintf('Training tree %d of %d\n',treeInd,opts.nTrees); tStart=clock; % set global stream to stream with given substream (will undo at end) streamOrig = RandStream.getGlobalStream(); set(stream,'Substream',treeInd); RandStream.setGlobalStream( stream ); % collect positive and negative patches and compute features fids=sort(randperm(nTotFtrs,round(nTotFtrs*opts.fracFtrs))); k = nPos+nNeg; nImgs=min(nImgs,opts.nImgs); ftrs = zeros(k,length(fids),'single'); labels = zeros(gtWidth,gtWidth,k,'uint8'); k = 0; tid = ticStatus('Collecting data',30,1); % modified by YL for i = 1:nImgs % get image and compute channels me=imread(fullfile(trnGtDir, [imgIds{i} fileExt])); me = im2double(me); I=imread(fullfile(trnImgDir, [imgIds{i} fileExt])); nGt = opts.nGt; % resize the image and groundtruth if necessary if opts.scale < 1 %me = imresize(me, opts.scale); I = imresize(I, opts.scale); assert(size(I,1)==size(me,1) && size(I,2)==size(me,2)) end % get image features siz=size(I); p=zeros(1,4); p([2 4])=mod(4-mod(siz(1:2),4),4); if(any(p)), I=imPad(I,p,'symmetric'); end [chnsReg,chnsSim] = edgesChns(I,opts); % sample positive and negative locations xy=[]; k1=0; B=false(siz(1),siz(2)); B(shrink:shrink:end,shrink:shrink:end)=1; B([1:imRadius end-imRadius:end],:)=0; B(:,[1:imRadius end-imRadius:end])=0; % generate the threshlist thresh = exp(linspace(log(opts.threshBracket(1)), log(opts.threshBracket(2)), nGt)); gt = cell([1 nGt]); % all we care about is the pretty positive samples! Mneg=~(bwdist(me>0.1)<gtRadius); posLabels = []; for j=1:nGt % threshold the motion boundary to get the a boundary map Mpos=(me>thresh(j)); gt{j} = Mpos; % get the pos sample (if there is a boundary pixel within the patch) Mpos(bwdist(Mpos)<gtRadius)=1; [y,x]=find(Mpos.*B); k2=min(length(y),ceil(2*nPos/nImgs/nGt)); rp=randperm(length(y),k2); y=y(rp); x=x(rp); xy=[xy; x y ones(k2,1)*j]; k1=k1+k2; %#ok<AGROW> posLabels = [posLabels; ones(k2, 1)]; % lower thrshold for neg samples [y,x]=find(Mneg.*B); k2=min(length(y),ceil(nNeg/nImgs/nGt)); rp=randperm(length(y),k2); y=y(rp); x=x(rp); xy=[xy; x y ones(k2,1)*j]; k1=k1+k2; %#ok<AGROW> posLabels = [posLabels; zeros(k2, 1)]; end % k1 is the maximum number of samples, but we do not know the exact % number until we sample them k1 = ceil((nPos + nNeg)/nImgs); kSamples = length(posLabels); if(k1>size(ftrs,1)-k), k1=size(ftrs,1)-k; xy=xy(1:k1,:); end % crop patches and ground truth labels psReg=zeros(imWidth/shrink,imWidth/shrink,nChns,k1,'single'); lbls=zeros(gtWidth,gtWidth,k1,'uint8'); psSim=psReg; ri=imRadius/shrink; rg=gtRadius; % check each local patch curSampleIdx = 0; for j=1:kSamples, if curSampleIdx < k1 % get the sample coordinate xy1=xy(j,:); xy2=xy1/shrink; % crop boundary patch -> find super pixel using boundary map % -> remove boundary pixels e = gt{xy1(3)}(xy1(2)-rg+1:xy1(2)+rg,xy1(1)-rg+1:xy1(1)+rg); s = bwlabel(~e, 4); t = spDetectMex('boundaries',uint32(s),single(e),0,1); t = t+ 1; if(all(t(:)==t(1)) && posLabels(j)==1), continue; % this is not a good edge sample, so skip it elseif all(t(:)==t(1)) curSampleIdx = curSampleIdx + 1; lbls(:,:,curSampleIdx)=1; % negtive sample else curSampleIdx = curSampleIdx + 1; [~,~,t]=unique(t); lbls(:,:,curSampleIdx)=reshape(t,gtWidth,gtWidth); % positive sample end % crop the feature psReg(:,:,:,curSampleIdx)=chnsReg(xy2(2)-ri+1:xy2(2)+ri,xy2(1)-ri+1:xy2(1)+ri,:); psSim(:,:,:,curSampleIdx)=chnsSim(xy2(2)-ri+1:xy2(2)+ri,xy2(1)-ri+1:xy2(1)+ri,:); end end % the actual number of samples k1 = curSampleIdx; psReg = psReg(:,:,:,1:k1); psSim = psSim(:,:,:,1:k1); lbls = lbls(:,:,1:k1); % visualization code % if(1), figure(1); montage2(squeeze(psReg(:,:,1,:))); drawnow; end % if(1), figure(2); montage2(lbls(:,:,:)); drawnow; end % if(1), figure(3); imshow(me); drawnow; end % pause % compute features and store ftrs1=[reshape(psReg,[],k1)' stComputeSimFtrs(psSim,opts)]; ftrs(k+1:k+k1,:)=ftrs1(:,fids); labels(:,:,k+1:k+k1)=lbls; k=k+k1; if(k==size(ftrs,1)), tocStatus(tid,1); break; end tocStatus(tid,i/nImgs); end if(k<size(ftrs,1)), ftrs=ftrs(1:k,:); labels=labels(:,:,1:k); end % train structured edge classifier (random decision tree) pTree=struct('minCount',opts.minCount, 'minChild',opts.minChild, ... 'maxDepth',opts.maxDepth, 'H',opts.nClasses, 'split',opts.split); t=labels; labels=cell(k,1); for i=1:k, labels{i}=t(:,:,i); end pTree.discretize=@(hs,H) discretize(hs,H,opts.nSamples,opts.discretize); tree=forestTrain(ftrs,labels,pTree); tree.hs=cell2array(tree.hs); tree.fids(tree.child>0) = fids(tree.fids(tree.child>0)+1)-1; if(~exist(treeDir,'dir')), mkdir(treeDir); end save([treeFn int2str2(treeInd,3) '.mat'],'tree'); e=etime(clock,tStart); fprintf('Training of tree %d complete (time=%.1fs).\n',treeInd,e); RandStream.setGlobalStream( streamOrig ); end %% sim features function ftrs = stComputeSimFtrs( chns, opts ) % Compute self-similarity features (order must be compatible w mex file). w=opts.imWidth/opts.shrink; n=opts.nCells; if(n==0), ftrs=[]; return; end nSimFtrs=opts.nSimFtrs; nChns=opts.nChns; m=size(chns,4); inds=round(w/n/2); inds=round((1:n)*(w+2*inds-1)/(n+1)-inds+1); chns=reshape(chns(inds,inds,:,:),n*n,nChns,m); ftrs=zeros(nSimFtrs/nChns,nChns,m,'single'); k=0; for i=1:n*n-1, k1=n*n-i; i1=ones(1,k1)*i; ftrs(k+1:k+k1,:,:)=chns(i1,:,:)-chns((1:k1)+i,:,:); k=k+k1; end ftrs = reshape(ftrs,nSimFtrs,m)'; end %% discretize the edge patches function [hs,segs] = discretize( segs, nClasses, nSamples, type ) % Convert a set of segmentations into a set of labels in [1,nClasses]. persistent cache; w=size(segs{1},1); assert(size(segs{1},2)==w); if(~isempty(cache) && cache{1}==w), [~,is1,is2]=deal(cache{:}); else % compute all possible lookup inds for w x w patches is=1:w^4; is1=floor((is-1)/w/w); is2=is-is1*w*w; is1=is1+1; kp=is2>is1; is1=is1(kp); is2=is2(kp); cache={w,is1,is2}; end % compute n binary codes zs of length nSamples nSamples=min(nSamples,length(is1)); kp=randperm(length(is1),nSamples); n=length(segs); is1=is1(kp); is2=is2(kp); zs=false(n,nSamples); for i=1:n, zs(i,:)=segs{i}(is1)==segs{i}(is2); end zs=bsxfun(@minus,zs,sum(zs,1)/n); zs=zs(:,any(zs,1)); if(isempty(zs)), hs=ones(n,1,'uint32'); segs=segs{1}; return; end % find most representative segs (closest to mean) [~,ind]=min(sum(zs.*zs,2)); segs=segs{ind}; % apply PCA to reduce dimensionality of zs U=pca(zs'); d=min(5,size(U,2)); zs=zs*U(:,1:d); % discretize zs by clustering or discretizing pca dimensions d=min(d,floor(log2(nClasses))); hs=zeros(n,1); for i=1:d, hs=hs+(zs(:,i)<0)*2^(i-1); end [~,~,hs]=unique(hs); hs=uint32(hs); if(strcmpi(type,'kmeans')) nClasses1=max(hs); C=zs(1:nClasses1,:); for i=1:nClasses1, C(i,:)=mean(zs(hs==i,:),1); end hs=uint32(kmeans2(zs,nClasses,'C0',C,'nIter',1)); end % optionally display different types of hs for i=1:0, figure(i); montage2(cell2array(segs(hs==i))); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
rgb.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionplayerPro/rgb.m
7,732
utf_8
e3e60031f5dfe6aa0d1f477e521ca66d
% rgb.m: translates a colour from multiple formats into matlab colour format % type 'rgb demo' to get started % % [matlabcolor]=rgb(col) % matlab colors are in the format [R G B] % % if 'col' is a string, it is interpreted as % % [[modifier] descriptor] colour_name % % where % modifier is one of (slightly, normal, very, extremely) % descriptor is one of (light/pale, normal, dark) % colorname is a name of a colour % (type 'rgb list' or 'rgb demo' to see them all) % % if 'col' is an integer between 0 and &HFFFFFF inclusive, % it is interpreted as a double word RGB value in the form % [0][R][G][B] % % if 'col' is a negative integer between -1 and -&HFFFFFF % inclusive, it is interpreted as the complement of a double % word RGB value in the form [0][B][G][R] % % if 'col' is a string of the form 'qbX' or 'qbXX' where X % is a digit then the number part is interpreted as a qbasic % color % % if 'col' is one of {k,w,r,g,b,y,m,c} a sensible result is % returned % % if 'col' is already in matlab format, it is unchanged % VERSION: 06/06/2002 % AUTHOR: ben mitch % CONTACT: [email protected] % WWW: www.benmitch.co.uk\matlab (not yet) % LOCATION: figures\colors\ function out=rgb(in) if isa(in,'char') & length(in)>2 & length(in)<5 & strcmpi('qb',in(1:2)) out=qbcolor(sscanf(in(3:end),'%i')); elseif isa(in,'char') & length(in)==1 out=translatecolorchar(in); elseif isa(in,'char') if strcmp(in,'demo') rgb_demo; return; end if strcmp(in,'list') rgb_list; return; end out=translatecolorstring(in); elseif isa(in,'double') & size(in,1)==1 & size(in,2)==1 & abs(in)<16777216 out=translatecolorRGB(in); elseif isa(in,'double') & size(in,1)==1 & size(in,2)==3 out=in; else warning('Unrecognised color format, black assumed'); out=[0 0 0]; end function out=translatecolorchar(in) switch(in) case 'k', out=[0 0 0]; case 'w', out=[1 1 1]; case 'r', out=[1 0 0]; case 'g', out=[0 1 0]; case 'b', out=[0 0 1]; case 'y', out=[1 1 0]; case 'm', out=[1 0 1]; case 'c', out=[0 1 1]; otherwise warning(['Unrecognised colour "' in '", black assumed']) out=[0 0 0]; return; end function out=translatecolorstring(in) args.tokens=rgb_parse(in); args.N=length(args.tokens); if args.N>3 warning('Too many words in color description, any more than 3 will be ignored'); end while(args.N<3) args.tokens=[{'normal'};args.tokens]; args.N=args.N+1; end cols=get_cols; col=[]; for n=1:size(cols,1) names=cols{n,1}; for m=1:length(names) if strcmp(args.tokens{3},names{m}) col=cols{n,2}; break; end end if ~isempty(col) break; end end if isempty(col) warning(['Unrecognised colour "' args.tokens{3} '", black assumed']) out=[0 0 0]; return; end switch args.tokens{1} case 'slightly', fac=0.75; case 'normal', fac=0.5; case 'very', fac=0.25; case 'extremely', fac=0.125; otherwise warning(['Unrecognised modifier "' args.tokens{1} '", normal assumed']) fac=0.5; end switch args.tokens{2} case {'light','pale'}, out=1-(1-col)*fac; case 'normal', out=col; case 'dark', out=col*fac; otherwise warning(['Unrecognised descriptor "' args.tokens{2} '", normal assumed']) out=col; end function out=translatecolorRGB(in) BGR=0; if in<0 in=-in; BGR=1; end b=bytes4(in); if BGR out=b(4:-1:2); else out=b(2:4); end function out=qbcolor(in) % rgb value from basic colour code % 0-7 are normal, 8-15 are bright % 0 - black % 1 - red, 2 - green, 3 - blue % 4 - cyan, 5 - magenta, 6 - yellow % 7 - white bright=0.5; if in>7 in=in-8; bright=1; end switch in case 0, rgb=[0 0 0]; case 1, rgb=[1 0 0]; case 2, rgb=[0 1 0]; case 3, rgb=[0 0 1]; case 4, rgb=[0 1 1]; case 5, rgb=[1 0 1]; case 6, rgb=[1 1 0]; case 7, rgb=[1 1 1]; otherwise warning('Unrecognised QBasic color, black assumed'); out=[0 0 0]; return; end out=rgb*bright; function tokens=rgb_parse(str) % parse string to obtain all tokens % quoted strings count as single tokens inquotes=0; intoken=0; pos=1; l=length(str); st=0; ed=0; token=''; tab=char(9); tokens=cell(0); while(pos<=l) ch=str(pos); if inquotes if ch=='"' inquotes=0; tokens={tokens{:} token}; else token=[token ch]; end elseif intoken if ch==' ' | ch==tab intoken=0; tokens={tokens{:} token}; elseif ch=='"' error(['Quote misplace in <' str '>']); else token=[token ch]; end else if ch==' ' | ch==tab % do nothing elseif ch=='"' token=''; inquotes=1; else token=ch; intoken=1; end end pos=pos+1; end if intoken tokens={tokens{:} token}; end if inquotes error(['Unpaired quotes in <' str '>']); end tokens=tokens'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % DEMO %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rgb_demo figure(1) clf cols = get_cols; cols = {cols{:,1}}'; cols = { cols{:}, ... 'k', ... 'r', ... 'g', ... 'b', ... 'y', ... 'm', ... 'c', ... 'w', ... '', ... 'extremely dark green', ... 'very dark green', ... 'dark green', ... 'slightly dark green', ... 'green', ... 'slightly pale green', ... 'pale green', ... 'very pale green', ... 'extremely pale green', ... }; height=9; x=0; y=0; for n=1:length(cols) rect(x,y,cols{n}) y=y+1; if y==height x=x+2; y=0; end end if y==0 x=x-2; end axis([0 (x+2) 0 height]) title('names on different rows are alternates') function rect(x,y,col) if isempty(col) return; end r=rectangle('position',[x+0.1 y+0.1 1.8 0.8]); col_=col; if iscell(col) col=col{1}; end colrgb=rgb(col); if strcmp(col(1),'u') & length(col)==2 t=text(x+1,y+0.5,{'unnamed',['colour (' col(2) ')']}); set(r,'facecolor',colrgb); else t=text(x+1,y+0.5,col_); set(r,'facecolor',colrgb); if sum(colrgb)<1.5 set(t,'color',[1 1 1]); end end set(t,'horizontalalignment','center') set(t,'fontsize',10) function rgb_list cols=get_cols; disp(' ') for n=1:size(cols,1) code=cols{n,2}; str=cols{n,1}; str_=[]; for m=1:length(str) str_=[str_ str{m} ', ']; end str_=str_(1:end-2); if strcmp(str_(1),'u') & length(str_)==2 str_=['* (' str_(2) ')']; end disp([' [' sprintf('%.1f %.1f %.1f',code) '] - ' str_]) end disp([10 '* colours marked thus are not named - if you know their' 10 ' designation, or if you feel sure a colour is mis-named,' 10 ' email me (address via help) or comment at' 10 ' www.mathworks.com/matlabcentral - "rgb demo" to see them' 10]) function cols=get_cols cols={ 'black', [0 0 0]; ... 'navy', [0 0 0.5]; ... 'blue', [0 0 1]; ... 'u1', [0 0.5 0]; ... {'teal','turquoise'}, [0 0.5 0.5]; ... 'slateblue', [0 0.5 1]; ... {'green','lime'}, [0 1 0]; ... 'springgreen', [0 1 0.5]; ... {'cyan','aqua'}, [0 1 1]; ... 'maroon', [0.5 0 0]; ... 'purple', [0.5 0 0.5]; ... 'u2', [0.5 0 1]; ... 'olive', [0.5 0.5 0]; ... {'gray','grey'}, [0.5 0.5 0.5]; ... 'u3', [0.5 0.5 1]; ... {'mediumspringgreen','chartreuse'}, [0.5 1 0]; ... 'u4', [0.5 1 0.5]; ... 'sky', [0.5 1 1]; ... 'red', [1 0 0]; ... 'u5', [1 0 0.5]; ... {'magenta','fuchsia'}, [1 0 1]; ... 'orange', [1 0.5 0]; ... 'u6', [1 0.5 0.5]; ... 'u7', [1 0.5 1]; ... 'yellow', [1 1 0]; ... 'u8', [1 1 0.5]; ... 'white', [1 1 1]; ... }; for n=1:size(cols,1) if ~iscell(cols{n,1}) cols{n,1}={cols{n,1}}; end end % converts a DWORD into a four byte row vector function out=bytes4(in) out=[0 0 0 0]; if in<0 | in>(2^32-1) warning('DWORD out of range, zero assumed'); return; end N=4; while(in>0) out(N)=mod(in,256); in=(in-out(N))/256; N=N-1; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
newMPPObject.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionplayerPro/newMPPObject.m
601
utf_8
42d488d286b1fadfe14e55d2aea0209a
% -- % creates a template for MotionplayerPro Objects % fields required: % - type (currently possible values: 'dot', 'cross', 'tetra' % - data: matrix of size (3*nrOfObj x nrOfFrames) % - samplingRate % optional fields: (for default values see DEFAULTSCENE) % - color % - alpha % - size % % author: Jochen Tautges ([email protected]) function object = newMPPObject() % help newMPPObject; object.type = []; object.data = []; object.samplingRate = []; object.color = []; object.alpha = []; object.size = []; object.boundingBox = [];
github
umariqb/3D_Pose_Estimation_CVPR2016-master
MPP_GUI.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionplayerPro/MPP_GUI.m
3,405
utf_8
aedd8a008aa2e4af018cdaa12503396a
function fig = MPP_GUI(varargin) global SCENE; % figure and camera settings ---------------------------------------------- fig = figure('Visible','on',... 'Name','MotionPlayerPro',... 'NumberTitle','off',... 'Position',[SCENE.position,SCENE.size],... 'Resize', 'on', ... 'Color', [0 0 0 ], ...%[.92 .95 .95],... 'Interruptible','on',... 'WindowScrollWheelFcn',@windowScrollWheelFcn,... 'KeyPressFcn',@keyPressFunction,... 'KeyReleaseFcn',@keyReleaseFunction,... 'Renderer','OpenGl'); % 'WindowButtonDownFcn',@mouseButtonDownFunction,... % 'WindowButtonUpFcn',@mouseButtonUpFunction,... SCENE.handles.light = light('Position',SCENE.lightPosition,'Style','infinite'); set(SCENE.handles.light,'Visible',SCENE.status.light); SCENE.keyEvents.shiftKeyDown = false; SCENE.keyEvents.altKeyDown = false; cameratoolbar(fig, 'Show'); cameratoolbar(fig, 'SetCoordSys',SCENE.status.mainAxis); axis equal; axis off; hold all; function keyPressFunction(src,evnt) switch(evnt.Key) case 'leftarrow' curFrame = max(SCENE.status.curFrame - 10,1); setFramePro(curFrame); drawnow(); case 'downarrow' curFrame = max(SCENE.status.curFrame - 100,1); setFramePro(curFrame); drawnow(); case 'rightarrow' curFrame = min(SCENE.status.curFrame + 10,SCENE.nframes); setFramePro(curFrame); drawnow(); case 'uparrow' curFrame = min(SCENE.status.curFrame + 100,SCENE.nframes); setFramePro(curFrame); drawnow(); case 'shift' if(~SCENE.keyEvents.shiftKeyDown) SCENE.keyEvents.shiftKeyDown = true; cameratoolbar(SCENE.handles.fig, 'SetCoordSys',SCENE.status.mainAxis); cameratoolbar(SCENE.handles.fig, 'SetMode','orbit'); % set(cam_Status_Label,'String','orbit'); end case 'alt' if(~SCENE.keyEvents.altKeyDown) SCENE.keyEvents.altKeyDown = true; cameratoolbar(SCENE.handles.fig, 'SetCoordSys',SCENE.status.mainAxis); cameratoolbar(SCENE.handles.fig, 'SetMode','pan'); % set(cam_Status_Label,'String','pan'); end case 'space' if(SCENE.status.running) pauseFunction; else playFunction; end otherwise disp('unknown key'); end end function keyReleaseFunction(src,evnt) switch(evnt.Key) case 'shift' SCENE.keyEvents.shiftKeyDown = false; cameratoolbar(SCENE.handles.fig, 'SetCoordSys','none'); cameratoolbar(SCENE.handles.fig, 'SetMode','nomode'); case 'alt' SCENE.keyEvents.altKeyDown = false; cameratoolbar(SCENE.handles.fig, 'SetCoordSys','none'); cameratoolbar(SCENE.handles.fig, 'SetMode','nomode'); end end function windowScrollWheelFcn(src, evnt) f = .05; if(evnt.VerticalScrollCount < 0) zoom(1+f); else zoom(1-f); end end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
motionplayerProGUI.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionplayerPro/motionplayerProGUI.m
29,219
utf_8
ae6f6ca6e5c3b23a95a5b71b80b6d6be
function fig = motionplayerProGUI(varargin) global SCENE; % help -------------------------------------------------------------------- helpDlg = {'Key-Bindings:',... '------------------------------------------------------',... '<space>:',' play/pause',... '<leftarrow>:',' move motion back 10 frames',... '<downarrow>:',' move motion back 100 frames',... '<rightarrow>:',' move motion forward 10 frames',... '<uparrow>:',' move motion forward 100 frames',... '<shift>+<mouse>:',' orbit rotate scene',... '<alt>+<mouse>:',' pan scene',... '<mousewheel>:',' zoom scene'}; % figure and camera settings ---------------------------------------------- fig = figure('Visible','on',... 'Name','MotionPlayerPro',... 'NumberTitle','off',... 'Position',[SCENE.position,SCENE.size],... 'Resize', 'on', ... 'Color', [1 1 1], ...%[.92 .95 .95],... 'Interruptible','on',... 'WindowScrollWheelFcn',@windowScrollWheelFcn,... 'KeyPressFcn',@keyPressFunction,... 'KeyReleaseFcn',@keyReleaseFunction,... 'Renderer','OpenGl'); % 'WindowButtonDownFcn',@mouseButtonDownFunction,... % 'WindowButtonUpFcn',@mouseButtonUpFunction,... SCENE.handles.light = light('Position',SCENE.lightPosition,'Style','infinite'); set(SCENE.handles.light,'Visible',SCENE.status.light); SCENE.keyEvents.shiftKeyDown = false; SCENE.keyEvents.altKeyDown = false; cameratoolbar(fig, 'Show'); cameratoolbar(fig, 'SetCoordSys',SCENE.status.mainAxis); axis equal; % axis vis3d; axis off; renewAxisDimensions(SCENE.boundingBox); % initializing figure with first frame(s) --------------------------------- for j=1:SCENE.nmots if SCENE.nmots>1 % the interpolate skeleton colors c = (j-1)/(SCENE.nmots-1); interpolated_color = ... c * SCENE.colors.multipleSkels_FaceVertexData_end... + (1-c) * SCENE.colors.multipleSkels_FaceVertexData_start; end nrOfNodes = size(SCENE.mots{j}.vertices{1},1)/3; for i=1:size(SCENE.mots{j}.vertices,1)-1 v = reshape(SCENE.mots{j}.vertices{i+1}(:,1),3,nrOfNodes)'; f = SCENE.mots{j}.faces; if SCENE.nmots==1 SCENE.mots{j}.joint_handles(i) = ... patch('Vertices',v,'Faces',f,... 'FaceVertexCData',SCENE.colors.singleSkel_FaceVertexData,... 'FaceColor',SCENE.colors.singleSkel_FaceColor,... 'FaceAlpha',SCENE.colors.singelSkel_FaceAlpha, ... 'EdgeColor',SCENE.colors.singleSkel_EdgeColor); else SCENE.mots{j}.joint_handles(i) = ... patch('Vertices',v,'Faces',f,... 'FaceColor',hsv2rgb(interpolated_color),... 'FaceAlpha',SCENE.colors.multipleSkels_FaceAlpha, ... 'EdgeColor',SCENE.colors.multipleSkels_EdgeColor); end end SCENE.mots{j}.jointID_handles = -ones(SCENE.mots{j}.njoints,1); end hold all; % % for j=1:SCENE.npoints % % if SCENE.npoints>1 % % c = (j-1)/(SCENE.npoints-1); % % else % % c = 0; % % end % % color = ... % % c * SCENE.colors.points_end... % % + (1-c) * SCENE.colors.points_start; % % % % i = mod(j,numel(SCENE.pointsSpec)); % % if i==0, i=numel(SCENE.pointsSpec); end % % SCENE.handles.points(j) = plot3(SCENE.points{j}(1:3:end,1),... % % SCENE.points{j}(2:3:end,1),... % % SCENE.points{j}(3:3:end,1),... % % SCENE.pointsSpec{i},'color',hsv2rgb(color)); % % end if ~isempty(SCENE.objects) objects = fieldnames(SCENE.objects); nrOfDiffObjects = numel(objects); for p=1:nrOfDiffObjects for k=1:SCENE.objects.(objects{p}).counter color = SCENE.objects.(objects{p}).color{k}; switch objects{p} case 'tetra' coords = [1 -1 -1 1;1 -1 1 -1;-1 -1 1 1]; f = [1 2 3;1 2 4;1 3 4;2 3 4]; nrOfObj = size(SCENE.objects.tetra.procdata{k},1); if ~isempty(SCENE.objects.tetra.alpha{k}) alphaValues = SCENE.objects.tetra.alpha{k}(:,1); else alphaValues = ones(nrOfObj,1); end SCENE.handles.tetra{k}=zeros(nrOfObj,1); for n=1:nrOfObj v = reshape(SCENE.objects.tetra.procdata{k}{n}(:,1),3,size(coords,2)); SCENE.handles.tetra{k}(n) = patch('Vertices',v','Faces',f,... 'FaceColor',color,... 'FaceAlpha',alphaValues(n), ... 'EdgeColor','none'); end case {'dot','cross','circle'} switch objects{p} case 'dot', lineSpec = '.'; case 'cross', lineSpec = 'x'; case 'circle', lineSpec = 'o'; otherwise error('Unknown obj type'); end SCENE.handles.(objects{p}){k} = plot3(SCENE.objects.(objects{p}).procdata{k}(1:3:end,1),... SCENE.objects.(objects{p}).procdata{k}(2:3:end,1),... SCENE.objects.(objects{p}).procdata{k}(3:3:end,1),... lineSpec,'color',color); case {'line'} nrOfLines = size(SCENE.objects.line.procdata{k},1); nrOfJoints = size(SCENE.objects.line.procdata{k}{1},1)/3; n=0; color = rgb(SCENE.objects.line.color{k}); for n1=1:nrOfLines for n2=1:nrOfJoints n=n+1; if ~isempty(SCENE.objects.line.alpha{k}) w = SCENE.objects.line.alpha{k}(n1,1); color = w * color + (1-w) * [1 1 1]; end SCENE.handles.line{k}(n) = plot3(SCENE.objects.line.procdata{k}{n1,1}(3*n2-2,:),... SCENE.objects.(objects{p}).procdata{k}{n1,1}(3*n2-1,:),... SCENE.objects.(objects{p}).procdata{k}{n1,1}(3*n2,:),... '-','color',color); end end end end end end if SCENE.status.groundPlane_drawn computeGroundPlane(SCENE.boundingBox); end hold off; % if SCENE.nmots>1 % spreadFunction(); % end %% control panel----------------------------------------------------------- SCENE.handles.control_Panel = uipanel(... 'Parent',fig,... 'Units','pixels',... 'Position',[2 2 799 110],... 'BackgroundColor',[.97 .97 .97]); SCENE.handles.goto_First_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.goto_First,...'String','|<',... 'Units','pixels',... 'Position',[2 80 27 20],... 'TooltipString','go to first frame',... 'BackgroundColor',SCENE.colors.buttons_group1, ... 'CallBack',@gotoFirstFunction); SCENE.handles.play_reverse_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.play_reverse,...'String','<|',... 'Units','pixels',... 'Position',[30 80 27 20],... 'TooltipString','play backwards',... 'BackgroundColor',SCENE.colors.buttons_group1, ... 'CallBack',@playReverseFunction); SCENE.handles.pause_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.pause,...'String','||',... 'Units','pixels',... 'Position',[58 80 27 20],... 'TooltipString','pause',... 'BackgroundColor',SCENE.colors.buttons_group1, ... 'CallBack',@pauseFunction); SCENE.handles.play_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.play,...'String','|>',... 'Units','pixels',... 'Position',[86 80 27 20],... 'TooltipString','play',... 'BackgroundColor',SCENE.colors.buttons_group1, ... 'CallBack',@playFunction); SCENE.handles.goto_Last_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.goto_Last,...'String','>|',... 'Units','pixels',... 'Position',[114 80 27 20],... 'TooltipString','go to last frame',... 'BackgroundColor',SCENE.colors.buttons_group1, ... 'CallBack',@gotoLastFunction); SCENE.handles.slower_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.slower,...'String','<<',... 'Units','pixels',... 'Position',[148 80 27 20],... 'TooltipString','slower',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@slowerFunction); SCENE.handles.loop_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.unlooped,...'String','|--|',... 'Units','pixels',... 'Position',[176 80 27 20],... 'TooltipString','loop',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@loopFunction); SCENE.handles.faster_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.faster,...'String','>>',... 'Units','pixels',... 'Position',[204 80 27 20],... 'TooltipString','faster',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@fasterFunction); SCENE.handles.drawCoordSyst_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.coords+0.5,... 'Units','pixels',... 'Position',[236 80 27 20],... 'TooltipString','draw coordinate system',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@drawCoordinateSystem); SCENE.handles.drawLocalCoordSyst_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.localcoords+0.5,... 'Units','pixels',... 'Position',[264 80 27 20],... 'TooltipString','draw local coordinate systems',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@drawLocalCoordinateSystems2); SCENE.handles.drawGroundPlane_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.groundPlane,... 'Units','pixels',... 'Position',[292 80 27 20],... 'TooltipString','hide ground plane',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@drawGroundPlane); SCENE.handles.drawJointIDs_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.jointIDs+0.5,... 'Units','pixels',... 'Position',[320 80 27 20],... 'TooltipString','show joint IDs',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@drawJointIDs); SCENE.handles.drawSensorCoordSyst_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.sensorcoords+0.5,... 'Units','pixels',... 'Position',[348 80 27 20],... 'TooltipString','draw sensor coordinate systems',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@drawSensorCoordinateSystems); % SCENE.handles.drawSensorCoordSyst2_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... % 'CData',SCENE.buttons.sensorcoords+0.5,... % 'Units','pixels',... % 'Position',[348 80 27 20],... % 'TooltipString','draw sensor coordinate systems',... % 'BackgroundColor',SCENE.colors.buttons_group2, ... % 'CallBack',@drawSensorCoordinateSystems2); if SCENE.nmots>1 SCENE.handles.spread_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.spread+0.5,... 'Units','pixels',... 'Position',[376 80 27 20],... 'TooltipString','spread motions',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@spreadFunction); end SCENE.handles.render_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.renderScene,... 'Units','pixels',... 'Position',[SCENE.size(1)-41-2*32 7 30 20],... 'TooltipString','render Scene to avi',... 'BackgroundColor',[0.9 0.3 0], ... 'CallBack',@renderMPProScene); SCENE.handles.help_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'String','Help',... 'Units','pixels',... 'FontWeight','bold',... 'HorizontalAlignment','center',... 'Position',[SCENE.size(1)-41-32 6 30 22],... 'CallBack',@helpButtonFunction); SCENE.handles.quit_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.quit,...'String','Quit',... 'Units','pixels',... 'Position',[SCENE.size(1)-41 7 30 20],... 'TooltipString','quit',... 'BackgroundColor',[0.9,.0,.0], ... 'CallBack',@closeFunction); % SCENE.handles.axis_x_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... % 'String','x',... % 'Units','pixels',... % 'Position',[284 80 20 20],... % 'FontWeight','bold',... % 'TooltipString','set main axis to x',... % 'BackgroundColor',[0.8,0.8,0.8], ... % 'CallBack',@setMainAxisFunction); % % SCENE.handles.axis_y_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... % 'String','y',... % 'Units','pixels',... % 'Position',[306 80 20 20],... % 'FontWeight','bold',... % 'TooltipString','set main axis to y',... % 'BackgroundColor',[0.9,0.9,0.97], ... % 'CallBack',@setMainAxisFunction); % % SCENE.handles.axis_z_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... % 'String','z',... % 'Units','pixels',... % 'Position',[328 80 20 20],... % 'FontWeight','bold',... % 'TooltipString','set main axis to z',... % 'BackgroundColor',[0.8,0.8,0.8], ... % 'CallBack',@setMainAxisFunction); SCENE.handles.status_Panel = uipanel(... 'Parent',SCENE.handles.control_Panel,'Units','pixels',... 'Position',[2 2 SCENE.size(1)-8 30],... 'BackgroundColor',[.97 .97 .97]); SCENE.handles.curFrameLabel = uicontrol(SCENE.handles.status_Panel,'Style','Text', ... 'String',sprintf(' 1 / %d (%.2f s)', SCENE.nframes,0),... 'Units','pixels',... 'TooltipString','current frame',... 'HorizontalAlignment','left',... 'BackgroundColor',[.97 .97 .97],... 'Position',[1 0 130 22]); SCENE.handles.curSpeedLabel = uicontrol(SCENE.handles.status_Panel,'Style','Text', ... 'String','x 1.000',... 'Units','pixels',... 'TooltipString','current speed',... 'HorizontalAlignment','left',... 'BackgroundColor',[.97 .97 .97],... 'Position',[150 0 40 22]); % add frame markers above slider ------------------------------------------ if(SCENE.nframes > 1) SCENE.handles.sliderHandle = uicontrol(SCENE.handles.control_Panel,'Style','Slider', ... 'String','Current Frame',... 'Units','pixels',... 'Max',SCENE.nframes,... 'Min',1,... 'Value',1,... 'SliderStep',[1/SCENE.nframes (1/SCENE.size(1))*40],... 'Position',[2 35 SCENE.size(1)-8 20],... 'BackgroundColor',[.8 .8 .8], ... 'CallBack',@moveFrameSliderFunction); if SCENE.nframes<=20 numMarks = SCENE.nframes; else numMarks = 15; end for i=20:-1:5 if mod(SCENE.nframes-1,i)==0 numMarks=i+1; break; end end posFromLeft = 11; posFromRight = SCENE.size(1)-62; posFromLeft = posFromLeft-(posFromRight-posFromLeft)/(SCENE.nframes-1); for frameNum = 1:(SCENE.nframes-1)/(numMarks-1):SCENE.nframes uicontrol(SCENE.handles.control_Panel,'Style','Text',... 'String',round(frameNum),'Units','pixels',... 'FontSize',7,'BackgroundColor',[.97 .97 .97],... 'Position',[posFromLeft+(round(frameNum)/SCENE.nframes)*(posFromRight-posFromLeft) 60 45 12]); end end if SCENE.status.spread for n=1:SCENE.nmots if SCENE.mots{n}.rotDataAvailable spreadVertices(n); else fprintf('Note: Transformation of point clouds (c3d) is not yet supported!\n'); end end computeBoundingBoxSCENE(); set(SCENE.handles.spread_Button, 'CData',SCENE.buttons.spread,'TooltipString','unspread motions'); SCENE.status.spread = true; if SCENE.status.groundPlane_drawn computeGroundPlane(SCENE.boundingBox); end renewAxisDimensions(SCENE.boundingBox); setFramePro(SCENE.status.curFrame); end %% callback functions ----------------------------------------------------- function playReverseFunction(varargin) if (SCENE.status.curFrame == 1) SCENE.status.curFrame = SCENE.nframes; end SCENE.status.reverse = true; SCENE.status.running = true; SCENE.status.timeStamp = (SCENE.status.curFrame)/SCENE.samplingRate; SCENE.timeOffset = SCENE.status.timeStamp; tic; while SCENE.status.running && (SCENE.status.curFrame>1 || SCENE.status.looped) nextFrame = getNextFrame_local(); if SCENE.status.running setFramePro(nextFrame); drawnow; SCENE.status.timeStamp = SCENE.timeOffset-toc*SCENE.status.speed; end end SCENE.status.running = false; end function pauseFunction(varargin) SCENE.status.running = false; end function playFunction(varargin) if (SCENE.status.curFrame == SCENE.nframes) SCENE.status.curFrame = 1; end SCENE.status.reverse = false; SCENE.status.running = true; SCENE.status.timeStamp = (SCENE.status.curFrame)/SCENE.samplingRate; SCENE.timeOffset = SCENE.status.timeStamp; tic; while SCENE.status.running && (SCENE.status.curFrame<SCENE.nframes || SCENE.status.looped) nextFrame = getNextFrame_local(); if SCENE.status.running setFramePro(nextFrame); drawnow; SCENE.status.timeStamp = SCENE.timeOffset+toc*SCENE.status.speed; end end SCENE.status.running = false; end function gotoFirstFunction(varargin) SCENE.status.running = false; SCENE.status.curFrame = 1; setFramePro(1); drawnow(); end function gotoLastFunction(varargin) SCENE.status.running = false; SCENE.status.curFrame = SCENE.nframes; setFramePro(SCENE.nframes); drawnow(); end function closeFunction(varargin) SCENE.status.running = false; close; SCENE.objects = []; SCENE.mots = []; SCENE.nmots = 0; SCENE.skels = []; SCENE.nskels = 0; % clear global SCENE; end function slowerFunction(varargin) if (SCENE.status.speed > 0.125) SCENE.status.speed = SCENE.status.speed/2; set(SCENE.handles.curSpeedLabel,'String',... sprintf('x %1.3f',SCENE.status.speed)); SCENE.status.timeStamp = (SCENE.status.curFrame)/SCENE.samplingRate; SCENE.timeOffset = SCENE.status.timeStamp; tic; end end function fasterFunction(varargin) if (SCENE.status.speed < 8) SCENE.status.speed = SCENE.status.speed*2; set(SCENE.handles.curSpeedLabel,'String',... sprintf('x %1.3f',SCENE.status.speed)); SCENE.status.timeStamp = (SCENE.status.curFrame)/SCENE.samplingRate; SCENE.timeOffset = SCENE.status.timeStamp; tic; end end function loopFunction(varargin) if (SCENE.status.looped) SCENE.status.looped = false; set(SCENE.handles.loop_Button, 'CData',SCENE.buttons.unlooped,'TooltipString','loop'); else SCENE.status.looped = true; set(SCENE.handles.loop_Button, 'CData',SCENE.buttons.looped,'TooltipString','no loop'); end end function drawJointIDs(varargin) if SCENE.status.jointIDs_drawn SCENE.status.jointIDs_drawn = false; for ii=1:SCENE.nmots arrayfun(@(x) delete(x), SCENE.mots{ii}.jointID_handles); end set(SCENE.handles.drawJointIDs_Button,'CData',SCENE.buttons.jointIDs+0.5,'TooltipString','show joint IDs'); else SCENE.status.jointIDs_drawn = true; if ~SCENE.status.running setFramePro(SCENE.status.curFrame); end set(SCENE.handles.drawJointIDs_Button,'CData',SCENE.buttons.jointIDs,'TooltipString','hide joint IDs'); end end function moveFrameSliderFunction(varargin) if (SCENE.status.running) SCENE.status.running = false; end curFrame = round(get(SCENE.handles.sliderHandle,'Value')); SCENE.status.timeStamp = curFrame/SCENE.samplingRate; SCENE.timeOffset = SCENE.status.timeStamp; setFramePro(curFrame); drawnow; end function spreadFunction(varargin) if SCENE.status.spread == false for m=1:SCENE.nmots if SCENE.mots{m}.rotDataAvailable spreadVertices(m); else fprintf('Note: Transformation of point clouds (c3d) is not yet supported!\n'); end end computeBoundingBoxSCENE(); set(SCENE.handles.spread_Button, 'CData',SCENE.buttons.spread,'TooltipString','unspread motions'); SCENE.status.spread = true; if SCENE.status.groundPlane_drawn computeGroundPlane(SCENE.boundingBox); end renewAxisDimensions(SCENE.boundingBox); else for m=1:SCENE.nmots if SCENE.mots{m}.rotDataAvailable unspreadVertices(m); end end computeBoundingBoxSCENE(); set(SCENE.handles.spread_Button, 'CData',SCENE.buttons.spread+0.5,'TooltipString','spread motions'); SCENE.status.spread = false; if SCENE.status.groundPlane_drawn computeGroundPlane(SCENE.boundingBox); end renewAxisDimensions(SCENE.boundingBox); end setFramePro(SCENE.status.curFrame); end % function setMainAxisFunction(varargin) % buttonHandle = get(varargin{1,1}); % mA = buttonHandle.String; % switch(mA) % case 'x' % SCENE.status.mainAxis = 'x'; % set(SCENE.handles.axis_x_Button,'BackgroundColor',[.9 .9 .97]); % set(SCENE.handles.axis_y_Button,'BackgroundColor',[.8 .8 .8]); % set(SCENE.handles.axis_z_Button,'BackgroundColor',[.8 .8 .8]); % case 'y' % SCENE.status.mainAxis = 'y'; % set(SCENE.handles.axis_x_Button,'BackgroundColor',[.8 .8 .8]); % set(SCENE.handles.axis_y_Button,'BackgroundColor',[.9 .9 .97]); % set(SCENE.handles.axis_z_Button,'BackgroundColor',[.8 .8 .8]); % case 'z' % SCENE.status.mainAxis = 'z'; % set(SCENE.handles.axis_x_Button,'BackgroundColor',[.8 .8 .8]); % set(SCENE.handles.axis_y_Button,'BackgroundColor',[.8 .8 .8]); % set(SCENE.handles.axis_z_Button,'BackgroundColor',[.9 .9 .97]); % end % cameratoolbar(fig, 'SetCoordSys',SCENE.status.mainAxis); % end function drawGroundPlane(varargin) if SCENE.status.groundPlane_drawn SCENE.status.groundPlane_drawn = false; % set(SCENE.handles.groundPlane,'Visible','off'); set(SCENE.handles.drawGroundPlane_Button,'CData',SCENE.buttons.groundPlane+0.5,'TooltipString','draw ground plane'); set(SCENE.handles.groundPlane,'FaceAlpha',0,'EdgeColor','none'); else SCENE.status.groundPlane_drawn = true; % set(SCENE.handles.groundPlane,'Visible','on'); set(SCENE.handles.drawGroundPlane_Button,'CData',SCENE.buttons.groundPlane,'TooltipString','hide ground plane'); set(SCENE.handles.groundPlane,'FaceAlpha',0.7,'EdgeColor','black'); end end function keyPressFunction(src,evnt) switch(evnt.Key) case 'leftarrow' curFrame = max(SCENE.status.curFrame - 10,1); setFramePro(curFrame); drawnow(); case 'downarrow' curFrame = max(SCENE.status.curFrame - 100,1); setFramePro(curFrame); drawnow(); case 'rightarrow' curFrame = min(SCENE.status.curFrame + 10,SCENE.nframes); setFramePro(curFrame); drawnow(); case 'uparrow' curFrame = min(SCENE.status.curFrame + 100,SCENE.nframes); setFramePro(curFrame); drawnow(); case 'shift' if(~SCENE.keyEvents.shiftKeyDown) SCENE.keyEvents.shiftKeyDown = true; cameratoolbar(fig, 'SetCoordSys',SCENE.status.mainAxis); cameratoolbar(fig, 'SetMode','orbit'); % set(cam_Status_Label,'String','orbit'); end case 'alt' if(~SCENE.keyEvents.altKeyDown) SCENE.keyEvents.altKeyDown = true; cameratoolbar(fig, 'SetCoordSys',SCENE.status.mainAxis); cameratoolbar(fig, 'SetMode','pan'); % set(cam_Status_Label,'String','pan'); end case 'space' if(SCENE.status.running) pauseFunction; else playFunction; end otherwise disp('unknown key'); end end function keyReleaseFunction(src,evnt) switch(evnt.Key) case 'shift' SCENE.keyEvents.shiftKeyDown = false; cameratoolbar(fig, 'SetCoordSys','none'); cameratoolbar(fig, 'SetMode','nomode'); case 'alt' SCENE.keyEvents.altKeyDown = false; cameratoolbar(fig, 'SetCoordSys','none'); cameratoolbar(fig, 'SetMode','nomode'); end end function windowScrollWheelFcn(src, evnt) f = .05; if(evnt.VerticalScrollCount < 0) zoom(1+f); else zoom(1-f); end end function helpButtonFunction(src,evnt) % msgbox(helpDlg,'Help','help'); helpFig = figure( 'Visible','on',... 'Name','Help',... 'NumberTitle','off',... 'Menu','none',... 'Position',[400,200,250,400],... 'Resize', 'on', ... 'Color',[.92 .95 .95]); uicontrol(helpFig,'Style','Text', ... 'String',helpDlg,... 'Units','pixels',... 'HorizontalAlignment','left',... 'BackgroundColor',[.97 .97 .97],... 'Position',[0 0 250 400]); end end %% local functions -------------------------------------------------------- function nextFrame = getNextFrame_local() global SCENE; framesToDrop = SCENE.status.timeStamp*SCENE.samplingRate-SCENE.status.curFrame; if SCENE.status.reverse nextFrame = SCENE.status.curFrame+round(framesToDrop)-1; else nextFrame = SCENE.status.curFrame+round(framesToDrop)+1; end if nextFrame<=0 if SCENE.status.looped nextFrame = SCENE.nframes; else nextFrame = 1; end elseif nextFrame>SCENE.nframes if SCENE.status.looped nextFrame = 1;%mod(nextFrame,SCENE.nframes); else nextFrame = SCENE.nframes; end end if (framesToDrop<0 && ~SCENE.status.reverse) || (framesToDrop>0 && SCENE.status.reverse) pause(abs(framesToDrop/SCENE.samplingRate)); end end function renewAxisDimensions(bb) diagonal = sqrt(sum((bb([1,3,5])-bb([2,4,6])).^2))/2; % center of the boundingbox's bottom xc = bb(1) + (bb(2) - bb(1))/2; yc = bb(3) + (bb(4) - bb(3))/2; % %zc = bb(5) + (bb(6) - bb(5))/2; axisDimensions = [xc-diagonal xc+diagonal yc-diagonal yc+diagonal]; axis (axisDimensions); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
computeVertices.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionplayerPro/computeVertices.m
10,374
utf_8
62c10be8f0070b96e360ea9b9d7f6212
function mot = computeVertices(skel,mot,scale_factor,bonestype) if isfield(mot,'rotationQuat') if ~iscell(mot.rotationQuat) if ~isempty(mot.rotationQuat) rotQuats = mat2cell(mot.rotationQuat,4*ones(1,numel(mot.animated))); mot.rotationQuat = cell(mot.njoints,1); mot.rotationQuat(mot.animated)=rotQuats; end end else mot.rotationQuat = []; mot.rotationEuler = []; end if (isempty(mot.rotationQuat) || all(cellfun(@(x) isempty(x),mot.rotationQuat)))... && (isempty(mot.rotationEuler) || all(cellfun(@(x) isempty(x),mot.rotationEuler))) if isempty(mot.jointTrajectories) error('No data available to compute mot.vertices!'); else mot.faces = [1 2 3;1 3 4;1 4 5;1 5 2;2 3 6;3 4 6;4 5 6;5 2 6]; mot.rotDataAvailable = false; mot.vertices = cell(mot.njoints,1); marker_edge_length = 2*scale_factor; for i=1:mot.njoints mot.jointTrajectories{i} = mot.jointTrajectories{i} * scale_factor; mot.vertices{i} = repmat(mot.jointTrajectories{i},6,1); mot.vertices{i}(2,:) = mot.vertices{i}(2,:)+marker_edge_length; mot.vertices{i}(6,:) = mot.vertices{i}(6,:)-marker_edge_length; mot.vertices{i}(7,:) = mot.vertices{i}(7,:)-marker_edge_length; mot.vertices{i}(12,:) = mot.vertices{i}(12,:)+marker_edge_length; mot.vertices{i}(13,:) = mot.vertices{i}(13,:)+marker_edge_length; mot.vertices{i}(17,:) = mot.vertices{i}(17,:)-marker_edge_length; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%hashim % [mot.jointTrajectories,mot.vertices,mot.faces] = iterativeForwKinematics_local(skel,mot,bonestype); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%hashim end else if isempty(mot.rotationQuat) mot = convert2quat(skel,mot); end mot.rotDataAvailable = true; mot.rotationQuat(mot.unanimated)={[ones(1,mot.nframes);zeros(3,mot.nframes)]}; [mot.jointTrajectories,mot.vertices,mot.faces] = iterativeForwKinematics_local(skel,mot,bonestype); % mot.vertices = recursive_forwardKinematicsQuat_local(skel,mot,1,... % [zeros(15,mot.nframes); mot.rootTranslation],... % C_quatmult(repmat(skel.rootRotationalOffsetQuat,1,mot.nframes),mot.rotationQuat{1})); % mot.jointTrajectories = cellfun(@(x) x(end-2:end,:), mot.vertices,'UniformOutput',0); end end function [jointTrajectories,vertices,faces] = H_iterativeForwKinematics_local(skel,mot,bonestype) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%hashim localSystems = cell(skel.njoints,1); jointTrajectories = cell(skel.njoints,1); jointTrajectories{1} = mot.rootTranslation; vertices = cell(skel.njoints,1); for i=1:size(skel.paths,1) for j=2:numel(skel.paths{i}) joint = skel.paths{i}(j); pred = skel.paths{i}(j-1); localSystems{joint,1} = localSystems{pred}; jointTrajectories{joint} = mot.jointTrajectories{pred}; [v,faces,nrOfV] = computeVertices_local(skel.nodes(joint).offset,bonestype); v = reshape(v,3,nrOfV); vertices{joint} = zeros(nrOfV*3,mot.nframes); for k=1:nrOfV vertices{joint}(k*3-2:k*3,:) = mot.jointTrajectories{pred}; end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%hashim end function [jointTrajectories,vertices,faces] = iterativeForwKinematics_local(skel,mot,bonestype) localSystems = cell(skel.njoints,1); localSystems{1} = mot.rotationQuat{1}; jointTrajectories = cell(skel.njoints,1); jointTrajectories{1} = mot.rootTranslation; vertices = cell(skel.njoints,1); for i=1:size(skel.paths,1) for j=2:numel(skel.paths{i}) joint = skel.paths{i}(j); pred = skel.paths{i}(j-1); if isempty(mot.rotationQuat{joint}) localSystems{joint,1} = localSystems{pred}; else localSystems{joint,1} = C_quatmult(double(real(localSystems{pred})),double(real(mot.rotationQuat{joint}))); end jointTrajectories{joint} = jointTrajectories{pred}... + C_quatrot(skel.nodes(joint).offset,localSystems{joint}); [v,faces,nrOfV] = computeVertices_local(skel.nodes(joint).offset,bonestype); v = reshape(v,3,nrOfV); vertices{joint} = zeros(nrOfV*3,mot.nframes); for k=1:nrOfV vertices{joint}(k*3-2:k*3,:) = jointTrajectories{pred}... + C_quatrot(v(:,k),localSystems{joint}); end end end end % % function trajectories = recursive_forwardKinematicsQuat_local(skel, mot, node_id, current_position, current_rotation,trajectories) % % % % trajectories{node_id,1} = current_position; % % vertices_mot = zeros(18,mot.nframes); % % % % for child_id = skel.nodes(node_id).children' % % % % child = skel.nodes(child_id); % % if (~isempty(mot.rotationQuat{child_id})) % % child_rotation = quatmult(current_rotation,mot.rotationQuat{child_id}); % % else % % child_rotation = current_rotation; % % end % % % % % child_rotation = quatmult(current_rotation,mot.rotationQuat{child_id}); % % mot.vertices = computeVertices_local(child.offset); % % % % c=1; % % for i=1:size(mot.vertices,2) % % vertices_mot(c:c+2,:) = C_quatrot(mot.vertices(:,i),child_rotation); % % c=c+3; % % end % % % % child_position = vertices_mot + repmat(current_position(16:18,:),6,1); % % trajectories = recursive_forwardKinematicsQuat_local(skel, mot, child_id, child_position, child_rotation, trajectories); % % end % % % % end function [vertices,faces,nrOfVertices] = computeVertices_local(child_offset,bonestype) switch bonestype case 'diamonds' child_length = sqrt(sum(child_offset.^2)); dir1 = cross(child_offset,[0;1;0]); dir1 = dir1/sqrt(sum(dir1.^2)); dir2 = cross(child_offset,dir1); dir2 = dir2/sqrt(sum(dir2.^2)); off1 = dir1*child_length/10; off2 = dir2*child_length/10; centerOfBone = child_offset/4; vertices = [[0;0;0],... centerOfBone+off1,... centerOfBone+off2,... centerOfBone-off1,... centerOfBone-off2,... child_offset]; faces = [1 2 3;1 3 4;1 4 5;1 5 2;2 3 6;3 4 6;4 5 6;5 2 6]; nrOfVertices = 6; case 'sticks' sidelength = 3; dir1 = cross(child_offset,[0;1;0])/2*sidelength; if ~any(dir1) dir1=[1;0;0]; else dir1 = dir1/sqrt(sum(dir1.^2))/2*sidelength; end dir2 = cross(child_offset,dir1)/2*sidelength; if ~any(dir2) dir2=[1;0;0]; else dir2 = dir2/sqrt(sum(dir2.^2))/2*sidelength; end vertices = [dir1+dir2;... -dir1+dir2;... -dir1-dir2;... dir1-dir2;... dir1+dir2+child_offset;... -dir1+dir2+child_offset;... -dir1-dir2+child_offset;... dir1-dir2+child_offset]; nrOfVertices = 8; faces = [1 2 3 4;1 2 6 5;2 3 7 6;3 4 8 7;1 4 8 5; 5 6 7 8]; case 'tubes' sidelength = 3; spheresize = 5; child_offset_n=child_offset/sqrt(sum(child_offset.^2)); rotaxis = cross([0 0 1],child_offset_n); rotangle = acos(dot(child_offset_n,[0 0 1])); if child_offset_n(3)==1%~any(rotaxis) rotaxis=[0;0;1]; rotangle = 0; end nn=16; l = norm(child_offset); [s.x,s.y,s.z] = cylinder(sidelength,nn); s.z(2,:)=s.z(2,:)*l; s.x=s.x(:); s.y=s.y(:); s.z=s.z(:); vertices = zeros((nn+1)*2*3,1); vertices(1:3:end) = s.x; vertices(2:3:end) = s.y; vertices(3:3:end) = s.z; sina = sin(rotangle/2); q = [cos(rotangle/2);rotaxis(1)*sina;rotaxis(2)*sina;rotaxis(3)*sina]; vertices = reshape(vertices,3,(nn+1)*2); vertices = quatrot(vertices,q); vertices = reshape(vertices,1,(nn+1)*2*3); faces = zeros(nn,4); for f=1:nn ul = f*2-1; faces(f,:)=[ul ul+2 ul+3 ul+1]; end [s.x,s.y,s.z] = sphere(nn); svertices = zeros((nn+1)*(nn+1)*3,1); svertices(1:3:end) = s.x(:)*spheresize; svertices(2:3:end) = s.y(:)*spheresize; svertices(3:3:end) = s.z(:)*spheresize; sfaces = zeros((nn)*(nn),4); for c = 1:nn for r = 1:nn ul = r+(nn+1)*(c-1); sfaces((c-1)*nn+r,:)=[ul ul+nn+1 ul+nn+2 ul+1]; end end faces = [faces;sfaces+numel(vertices)/3]; vertices = [vertices svertices']; nrOfVertices = numel(vertices)/3; case 'spheres' nn = 16; spheresize = 3; [s.x,s.y,s.z] = sphere(nn); svertices = zeros((nn+1)*(nn+1)*3,1); svertices(1:3:end) = s.x(:)*spheresize; svertices(2:3:end) = s.y(:)*spheresize; svertices(3:3:end) = s.z(:)*spheresize; sfaces = zeros((nn)*(nn),4); for c = 1:nn for r = 1:nn ul = r+(nn+1)*(c-1); sfaces((c-1)*nn+r,:)=[ul ul+nn+1 ul+nn+2 ul+1]; end end faces = sfaces; vertices = svertices'; nrOfVertices = numel(vertices)/3; otherwise error('Unknown type of bones!'); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
MPP_start.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionplayerPro/MPP_start.m
20,566
utf_8
a09f5cc60a6440b124c3867424b8d4c7
function MPP_start() global SCENE; % help -------------------------------------------------------------------- helpDlg = {'Key-Bindings:',... '------------------------------------------------------',... '<space>:',' play/pause',... '<leftarrow>:',' move motion back 10 frames',... '<downarrow>:',' move motion back 100 frames',... '<rightarrow>:',' move motion forward 10 frames',... '<uparrow>:',' move motion forward 100 frames',... '<shift>+<mouse>:',' orbit rotate scene',... '<alt>+<mouse>:',' pan scene',... '<mousewheel>:',' zoom scene'}; % figure and camera settings ---------------------------------------------- axisDimensions = renewAxisDimensions(SCENE.boundingBox); axis(axisDimensions); %% control panel----------------------------------------------------------- SCENE.handles.control_Panel = uipanel(... 'Parent',SCENE.handles.fig,... 'Units','pixels',... 'Position',[2 2 799 110],... 'BackgroundColor',[.97 .97 .97]); SCENE.handles.goto_First_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.goto_First,...'String','|<',... 'Units','pixels',... 'Position',[2 80 27 20],... 'TooltipString','go to first frame',... 'BackgroundColor',SCENE.colors.buttons_group1, ... 'CallBack',@gotoFirstFunction); SCENE.handles.play_reverse_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.play_reverse,...'String','<|',... 'Units','pixels',... 'Position',[30 80 27 20],... 'TooltipString','play backwards',... 'BackgroundColor',SCENE.colors.buttons_group1, ... 'CallBack',@playReverseFunction); SCENE.handles.pause_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.pause,...'String','||',... 'Units','pixels',... 'Position',[58 80 27 20],... 'TooltipString','pause',... 'BackgroundColor',SCENE.colors.buttons_group1, ... 'CallBack',@pauseFunction); SCENE.handles.play_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.play,...'String','|>',... 'Units','pixels',... 'Position',[86 80 27 20],... 'TooltipString','play',... 'BackgroundColor',SCENE.colors.buttons_group1, ... 'CallBack',@playFunction); SCENE.handles.goto_Last_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.goto_Last,...'String','>|',... 'Units','pixels',... 'Position',[114 80 27 20],... 'TooltipString','go to last frame',... 'BackgroundColor',SCENE.colors.buttons_group1, ... 'CallBack',@gotoLastFunction); SCENE.handles.slower_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.slower,...'String','<<',... 'Units','pixels',... 'Position',[148 80 27 20],... 'TooltipString','slower',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@slowerFunction); SCENE.handles.loop_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.unlooped,...'String','|--|',... 'Units','pixels',... 'Position',[176 80 27 20],... 'TooltipString','loop',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@loopFunction); SCENE.handles.faster_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.faster,...'String','>>',... 'Units','pixels',... 'Position',[204 80 27 20],... 'TooltipString','faster',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@fasterFunction); SCENE.handles.drawCoordSyst_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.coords+0.5,... 'Units','pixels',... 'Position',[236 80 27 20],... 'TooltipString','draw coordinate system',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@drawCoordinateSystem); SCENE.handles.drawLocalCoordSyst_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.localcoords+0.5,... 'Units','pixels',... 'Position',[264 80 27 20],... 'TooltipString','draw local coordinate systems',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@drawLocalCoordinateSystems2); SCENE.handles.drawGroundPlane_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.groundPlane,... 'Units','pixels',... 'Position',[292 80 27 20],... 'TooltipString','hide ground plane',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@drawGroundPlane); hold all; computeGroundPlane(SCENE.boundingBox); if ~SCENE.status.groundPlane_drawn set(SCENE.handles.drawGroundPlane_Button,'CData',SCENE.buttons.groundPlane+0.5,'TooltipString','draw ground plane'); set(SCENE.handles.groundPlane,'FaceAlpha',0,'EdgeColor','none'); end hold off; SCENE.handles.drawJointIDs_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.jointIDs+0.5,... 'Units','pixels',... 'Position',[320 80 27 20],... 'TooltipString','show joint IDs',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@drawJointIDs); SCENE.handles.drawSensorCoordSyst_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.sensorcoords+0.5,... 'Units','pixels',... 'Position',[348 80 27 20],... 'TooltipString','draw sensor coordinate systems',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@drawSensorCoordinateSystems); % SCENE.handles.drawSensorCoordSyst2_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... % 'CData',SCENE.buttons.sensorcoords+0.5,... % 'Units','pixels',... % 'Position',[348 80 27 20],... % 'TooltipString','draw sensor coordinate systems',... % 'BackgroundColor',SCENE.colors.buttons_group2, ... % 'CallBack',@drawSensorCoordinateSystems2); SCENE.handles.spread_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.spread+0.5,... 'Units','pixels',... 'Position',[376 80 27 20],... 'TooltipString','spread motions',... 'BackgroundColor',SCENE.colors.buttons_group2, ... 'CallBack',@spreadFunction); if SCENE.nmots==1 set(SCENE.handles.spread_Button,'Visible','off'); end SCENE.handles.MotName_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'String','Name',... 'Units','pixels',... 'Position',[SCENE.size(1)-41-7*32 7 30 20],... 'TooltipString','Display Mot Names',... 'BackgroundColor',[0.0 1.0 0.0], ... 'CallBack',@dispMotNames); SCENE.handles.Sketch_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'String','Sketch',... 'Units','pixels',... 'Position',[SCENE.size(1)-41-6*32 7 30 20],... 'TooltipString','sketch a frame',... 'BackgroundColor',[0.0 0.1 0.9], ... 'CallBack',@sketchFrame); SCENE.handles.AutoCam_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.renderScene,... 'Units','pixels',... 'Position',[SCENE.size(1)-41-5*32 7 30 20],... 'TooltipString','compute Auto Camera',... 'BackgroundColor',[0.1 0.8 0.1], ... 'CallBack',@computeAutoCam); SCENE.handles.AutoCam_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.exportFrame,... 'Units','pixels',... 'Position',[SCENE.size(1)-41-4*32 7 30 20],... 'TooltipString','export motions to obj files',... 'BackgroundColor',[0.1 0.8 0.1], ... 'CallBack',@exportMotToObj); SCENE.handles.export_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.exportFrame,... 'Units','pixels',... 'Position',[SCENE.size(1)-41-3*32 7 30 20],... 'TooltipString','export frame to obj files',... 'BackgroundColor',[0.9 0.3 0], ... 'CallBack',@exportObjFiles); SCENE.handles.render_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.renderScene,... 'Units','pixels',... 'Position',[SCENE.size(1)-41-2*32 7 30 20],... 'TooltipString','render Scene to avi',... 'BackgroundColor',[0.9 0.3 0], ... 'CallBack',@renderMPProScene); SCENE.handles.help_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'String','Help',... 'Units','pixels',... 'FontWeight','bold',... 'HorizontalAlignment','center',... 'Position',[SCENE.size(1)-41-32 6 30 22],... 'CallBack',@helpButtonFunction); SCENE.handles.quit_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... 'CData',SCENE.buttons.quit,...'String','Quit',... 'Units','pixels',... 'Position',[SCENE.size(1)-41 7 30 20],... 'TooltipString','quit',... 'BackgroundColor',[0.9,.0,.0], ... 'CallBack',@closeFunction); % SCENE.handles.axis_x_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... % 'String','x',... % 'Units','pixels',... % 'Position',[284 80 20 20],... % 'FontWeight','bold',... % 'TooltipString','set main axis to x',... % 'BackgroundColor',[0.8,0.8,0.8], ... % 'CallBack',@setMainAxisFunction); % % SCENE.handles.axis_y_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... % 'String','y',... % 'Units','pixels',... % 'Position',[306 80 20 20],... % 'FontWeight','bold',... % 'TooltipString','set main axis to y',... % 'BackgroundColor',[0.9,0.9,0.97], ... % 'CallBack',@setMainAxisFunction); % % SCENE.handles.axis_z_Button = uicontrol(SCENE.handles.control_Panel,'Style','Pushbutton', ... % 'String','z',... % 'Units','pixels',... % 'Position',[328 80 20 20],... % 'FontWeight','bold',... % 'TooltipString','set main axis to z',... % 'BackgroundColor',[0.8,0.8,0.8], ... % 'CallBack',@setMainAxisFunction); SCENE.handles.status_Panel = uipanel(... 'Parent',SCENE.handles.control_Panel,'Units','pixels',... 'Position',[2 2 SCENE.size(1)-8 30],... 'BackgroundColor',[.97 .97 .97]); SCENE.handles.curFrameLabel = uicontrol(SCENE.handles.status_Panel,'Style','Text', ... 'String',sprintf(' 1 / %d (%.2f s)', SCENE.nframes,0),... 'Units','pixels',... 'TooltipString','current frame',... 'HorizontalAlignment','left',... 'BackgroundColor',[.97 .97 .97],... 'Position',[1 0 130 22]); SCENE.handles.curSpeedLabel = uicontrol(SCENE.handles.status_Panel,'Style','Text', ... 'String','x 1.000',... 'Units','pixels',... 'TooltipString','current speed',... 'HorizontalAlignment','left',... 'BackgroundColor',[.97 .97 .97],... 'Position',[150 0 40 22]); % add frame markers above slider ------------------------------------------ if(SCENE.nframes > 1) SCENE.handles.sliderHandle = uicontrol(SCENE.handles.control_Panel,'Style','Slider', ... 'String','Current Frame',... 'Units','pixels',... 'Max',SCENE.nframes,... 'Min',1,... 'Value',1,... 'SliderStep',[1/SCENE.nframes (1/SCENE.size(1))*40],... 'Position',[2 35 SCENE.size(1)-8 20],... 'BackgroundColor',[.8 .8 .8], ... 'CallBack',@moveFrameSliderFunction); if SCENE.nframes<=20 numMarks = SCENE.nframes; else numMarks = 15; end for i=20:-1:5 if mod(SCENE.nframes-1,i)==0 numMarks=i+1; break; end end posFromLeft = 11; posFromRight = SCENE.size(1)-62; posFromLeft = posFromLeft-(posFromRight-posFromLeft)/(SCENE.nframes-1); for frameNum = 1:(SCENE.nframes-1)/(numMarks-1):SCENE.nframes uicontrol(SCENE.handles.control_Panel,'Style','Text',... 'String',round(frameNum),'Units','pixels',... 'FontSize',7,'BackgroundColor',[.97 .97 .97],... 'Position',[posFromLeft+(round(frameNum)/SCENE.nframes)*(posFromRight-posFromLeft) 60 45 12]); end end %% callback functions ----------------------------------------------------- function drawGroundPlane(varargin) if SCENE.status.groundPlane_drawn SCENE.status.groundPlane_drawn = false; % set(SCENE.handles.groundPlane,'Visible','off'); set(SCENE.handles.drawGroundPlane_Button,'CData',SCENE.buttons.groundPlane+0.5,'TooltipString','draw ground plane'); set(SCENE.handles.groundPlane,'FaceAlpha',0,'EdgeColor','none'); else SCENE.status.groundPlane_drawn = true; % set(SCENE.handles.groundPlane,'Visible','on'); set(SCENE.handles.drawGroundPlane_Button,'CData',SCENE.buttons.groundPlane,'TooltipString','hide ground plane'); set(SCENE.handles.groundPlane,'FaceAlpha',0.7,'EdgeColor','none'); end end function playReverseFunction(varargin) if (SCENE.status.curFrame == 1) SCENE.status.curFrame = SCENE.nframes; end SCENE.status.reverse = true; SCENE.status.running = true; SCENE.status.timeStamp = (SCENE.status.curFrame)/SCENE.samplingRate; SCENE.timeOffset = SCENE.status.timeStamp; tic; while SCENE.status.running && (SCENE.status.curFrame>1 || SCENE.status.looped) nextFrame = getNextFrame_local(); if SCENE.status.running setFramePro(nextFrame); drawnow; SCENE.status.timeStamp = SCENE.timeOffset-toc*SCENE.status.speed; end end SCENE.status.running = false; end function pauseFunction(varargin) SCENE.status.running = false; end function playFunction(varargin) if (SCENE.status.curFrame == SCENE.nframes) SCENE.status.curFrame = 1; end SCENE.status.reverse = false; SCENE.status.running = true; SCENE.status.timeStamp = (SCENE.status.curFrame)/SCENE.samplingRate; SCENE.timeOffset = SCENE.status.timeStamp; tic; while SCENE.status.running && (SCENE.status.curFrame<SCENE.nframes || SCENE.status.looped) nextFrame = getNextFrame_local(); if SCENE.status.running setFramePro(nextFrame); drawnow; SCENE.status.timeStamp = SCENE.timeOffset+toc*SCENE.status.speed; end end SCENE.status.running = false; end function gotoFirstFunction(varargin) SCENE.status.running = false; SCENE.status.curFrame = 1; setFramePro(1); drawnow(); end function gotoLastFunction(varargin) SCENE.status.running = false; SCENE.status.curFrame = SCENE.nframes; setFramePro(SCENE.nframes); drawnow(); end function closeFunction(varargin) SCENE.status.running = false; close; SCENE.objects = []; SCENE.mots = []; SCENE.nmots = 0; SCENE.skels = []; SCENE.nskels = 0; % clear global SCENE; end function slowerFunction(varargin) if (SCENE.status.speed > 0.125) SCENE.status.speed = SCENE.status.speed/2; set(SCENE.handles.curSpeedLabel,'String',... sprintf('x %1.3f',SCENE.status.speed)); SCENE.status.timeStamp = (SCENE.status.curFrame)/SCENE.samplingRate; SCENE.timeOffset = SCENE.status.timeStamp; tic; end end function fasterFunction(varargin) if (SCENE.status.speed < 8) SCENE.status.speed = SCENE.status.speed*2; set(SCENE.handles.curSpeedLabel,'String',... sprintf('x %1.3f',SCENE.status.speed)); SCENE.status.timeStamp = (SCENE.status.curFrame)/SCENE.samplingRate; SCENE.timeOffset = SCENE.status.timeStamp; tic; end end function loopFunction(varargin) if (SCENE.status.looped) SCENE.status.looped = false; set(SCENE.handles.loop_Button, 'CData',SCENE.buttons.unlooped,'TooltipString','loop'); else SCENE.status.looped = true; set(SCENE.handles.loop_Button, 'CData',SCENE.buttons.looped,'TooltipString','no loop'); end end function drawJointIDs(varargin) if SCENE.status.jointIDs_drawn SCENE.status.jointIDs_drawn = false; for ii=1:SCENE.nmots arrayfun(@(x) delete(x), SCENE.mots{ii}.jointID_handles); end set(SCENE.handles.drawJointIDs_Button,'CData',SCENE.buttons.jointIDs+0.5,'TooltipString','show joint IDs'); else SCENE.status.jointIDs_drawn = true; if ~SCENE.status.running setFramePro(SCENE.status.curFrame); end set(SCENE.handles.drawJointIDs_Button,'CData',SCENE.buttons.jointIDs,'TooltipString','hide joint IDs'); end end function moveFrameSliderFunction(varargin) if (SCENE.status.running) SCENE.status.running = false; end curFrame = round(get(SCENE.handles.sliderHandle,'Value')); SCENE.status.timeStamp = curFrame/SCENE.samplingRate; SCENE.timeOffset = SCENE.status.timeStamp; setFramePro(curFrame); drawnow; end function spreadFunction(varargin) if SCENE.status.spread == false for m=1:SCENE.nmots if SCENE.mots{m}.rotDataAvailable spreadVertices(m); else spreadVerticesPC(m); end end computeBoundingBoxSCENE(); set(SCENE.handles.spread_Button, 'CData',SCENE.buttons.spread,'TooltipString','unspread motions'); SCENE.status.spread = true; if SCENE.status.groundPlane_drawn computeGroundPlane(SCENE.boundingBox); end axisDimensions = renewAxisDimensions(SCENE.boundingBox); axis(axisDimensions); else for m=1:SCENE.nmots if SCENE.mots{m}.rotDataAvailable unspreadVertices(m); end end computeBoundingBoxSCENE(); set(SCENE.handles.spread_Button, 'CData',SCENE.buttons.spread+0.5,'TooltipString','spread motions'); SCENE.status.spread = false; if SCENE.status.groundPlane_drawn computeGroundPlane(SCENE.boundingBox); end axisDimensions = renewAxisDimensions(SCENE.boundingBox); axis(axisDimensions); end setFramePro(SCENE.status.curFrame); end function helpButtonFunction(src,evnt) % msgbox(helpDlg,'Help','help'); helpFig = figure( 'Visible','on',... 'Name','Help',... 'NumberTitle','off',... 'Menu','none',... 'Position',[400,200,250,400],... 'Resize', 'on', ... 'Color',[.92 .95 .95]); uicontrol(helpFig,'Style','Text', ... 'String',helpDlg,... 'Units','pixels',... 'HorizontalAlignment','left',... 'BackgroundColor',[.97 .97 .97],... 'Position',[0 0 250 400]); end end %% local functions -------------------------------------------------------- function nextFrame = getNextFrame_local() global SCENE; framesToDrop = SCENE.status.timeStamp*SCENE.samplingRate-SCENE.status.curFrame; if SCENE.status.reverse nextFrame = SCENE.status.curFrame+round(framesToDrop)-1; else nextFrame = SCENE.status.curFrame+round(framesToDrop)+1; end if nextFrame<=0 if SCENE.status.looped nextFrame = SCENE.nframes; else nextFrame = 1; end elseif nextFrame>SCENE.nframes if SCENE.status.looped nextFrame = 1;%mod(nextFrame,SCENE.nframes); else nextFrame = SCENE.nframes; end end if (framesToDrop<0 && ~SCENE.status.reverse) || (framesToDrop>0 && SCENE.status.reverse) pause(abs(framesToDrop/SCENE.samplingRate)); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
buildDB.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/parser/buildDB.m
19,707
utf_8
f19c88acf9d2fa4fee5ab29432f55770
function res = buildDB(varargin) % optional settings ------------------------------------------------------- origFrameRate = 119.88; minFrameNumber = 30;%origFrameRate; % ensure that no motions shorter than minFrameNumber frames are chosen % HINWEIS: ohne "Orig" sind das die Daten nach "fitRootOrientationsFrameWise"! options.addPosOrig = 1; options.addPos = 1; options.addVelOrig = 1; options.addVel = 1; options.addVelL = 1; options.addAccOrig = 1; options.addAcc = 1; options.addAccL = 1; options.addQuat = 1; options.addEuler = 0; options.addInvRootRot = 1; options.addDeltaRootPos = 1; options.addDeltaRootOri = 1; options.addOrigRootPos = 1; % needed for extractMotFromDBmat options.addOrigRootOri = 1; % needed for extractMotFromDBmat options.addSkel = 1; options.addSensorAccs = 1; % calibrated based on t-pose assumed in first frame of motion options.addMirrors = 0; options.correctWristOrientations = 1; % only affects lwrist and rwrist quats and thus velL and accL options.addFootprints = 0; res_args = checkargins_local(varargin,origFrameRate); global VARS_GLOBAL; % Precomputing number of frames and files --------------------------------- FilesOrFolders = uipickfiles(); pause(0.5); fprintf('Precomputing total number of frames: \t\t\t\t\t\t'); [totalNrOfFrames,totalNrOfAMCFiles,totalNrOfMATFiles] = ... countFiles_local(FilesOrFolders,minFrameNumber,origFrameRate,res_args.newFrameRate); fprintf(' ...finished.'); totalNrOfFiles = totalNrOfAMCFiles+totalNrOfMATFiles; if totalNrOfMATFiles>0 fprintf('\nTotal number of frames could not be computed because of missing amc-files.\n'); fprintf('However, %i mat-files were found.\n',totalNrOfFiles); fprintf('Please enter number of FILES (Press Enter for %i): ',totalNrOfFiles); tmp = input(''); if ~isempty(tmp), totalNrOfFiles = tmp; else fprintf('\b%i\n',totalNrOfFiles); end fprintf('Please enter number of FRAMES (%i were counted in %i files): ',totalNrOfFrames,totalNrOfAMCFiles); totalNrOfFrames = input(''); if isempty(totalNrOfFrames); totalNrOfFrames=1; end end if options.addMirrors totalNrOfFrames = 2*totalNrOfFrames; totalNrOfFiles = 2*totalNrOfFiles; end % ------------------------------------------------------------------------- if options.addPosOrig, res.posOrig = single(zeros(93,totalNrOfFrames)); end if options.addPos, res.pos = single(zeros(93,totalNrOfFrames)); end if options.addVelOrig, res.velOrig = single(zeros(93,totalNrOfFrames)); end if options.addVel, res.vel = single(zeros(93,totalNrOfFrames)); end if options.addVelL, res.velL = single(zeros(93,totalNrOfFrames)); end if options.addAccOrig, res.accOrig = single(zeros(93,totalNrOfFrames)); end if options.addAcc, res.acc = single(zeros(93,totalNrOfFrames)); end if options.addAccL, res.accL = single(zeros(93,totalNrOfFrames)); end if options.addQuat, res.quat = zeros(116,totalNrOfFrames); end if options.addEuler, res.euler = single(zeros(59,totalNrOfFrames)); end if options.addInvRootRot, res.invRootRot = zeros(4,totalNrOfFrames); end if options.addDeltaRootPos, res.deltaRootPos = zeros(3,totalNrOfFrames); end if options.addDeltaRootOri, res.deltaRootOri = zeros(4,totalNrOfFrames); end if options.addOrigRootPos, res.origRootPos = zeros(3,totalNrOfFrames); end if options.addOrigRootOri, res.origRootOri = zeros(4,totalNrOfFrames); end if options.addSkel, res.skels = cell(totalNrOfFiles,1); end if options.addSensorAccs, sensors = defaultSensors(); sensors = fieldnames(sensors); nrOfSensors = numel(sensors); res.sensorAccs = cell2struct(mat2cell(zeros(nrOfSensors*3,totalNrOfFrames),ones(1,nrOfSensors)*3,totalNrOfFrames),sensors); end if options.addFootprints res.footprints = false(2,totalNrOfFrames); res.dbAnnotation = false(1,totalNrOfFiles); % Java class for communication with db server annoqpath = fullfile('..','projects','dynamicMotionGraph','footprints','AnnotationQuery.jar'); postgresspath = fullfile('..','projects','dynamicMotionGraph','footprints','postgresql-8.4-701.jdbc4.jar'); javaaddpath (annoqpath); javaaddpath (postgresspath); import AnnotationQuery.* aq = AnnotationQuery(); end res.motNames = cell(totalNrOfFiles,1); res.motStartIDs = single(zeros(totalNrOfFiles,1)); % ------------------------------------------------------------------------- res.frameRate = res_args.newFrameRate; c = 0; frame = 1; for i=1:length(FilesOrFolders) if isdir(FilesOrFolders{i}) files = dir(fullfile(FilesOrFolders{i},'*.amc')); if isempty(files), files = dir(fullfile(FilesOrFolders{i},'*.mat')); end asffiles = dir(fullfile(FilesOrFolders{i},'*.asf')); pathstr = FilesOrFolders{i}; nrOfFiles = length(files); else [pathstr, name, ext] = fileparts(FilesOrFolders{i}); asffiles = dir(fullfile(pathstr,'*.asf')); clear files; files(1).name = [name ext]; nrOfFiles = 1; end asffiles = arrayfun(@(x) x.name(1:end-4),asffiles,'UniformOutput',0); for j=1:nrOfFiles if strcmp(files(j).name(end-2:end),'mat') amc_filename = files(j).name(1:end-4); else amc_filename = files(j).name; end for f=1:size(asffiles,1) if findstr(asffiles{f},amc_filename) asf_filename = [asffiles{f} '.asf']; break end end mat_filename = [amc_filename '.mat']; h = fopen(fullfile(pathstr,mat_filename)); if (h~=-1) fclose(h); load(fullfile(pathstr,mat_filename), 'skel', 'mot'); else try fprintf('\n'); skel = readASF(fullfile(pathstr,asf_filename)); mot = readAMC(fullfile(pathstr,amc_filename),skel); save(fullfile(pathstr,mat_filename), 'skel', 'mot'); fprintf('Frames read: \t\t\t\t\t\t\t\t\t\t\t\t\t'); catch fprintf('\nCould not read file!\n'); end end mot.samplingRate = origFrameRate; mot.frameTime = 1/origFrameRate; if mot.nframes>=minFrameNumber if ~res_args.individualSkels skel = res_args.FixedSkel; % mot.jointTrajectories = iterativeForwKinematics(skel,mot); elseif ~res_args.individualBoneLengths for k=1:numel(res_args.FixedBoneLengths) skel.nodes(k).length = res_args.FixedBoneLengths(k); skel.nodes(k).offset = skel.nodes(k).direction * res_args.FixedBoneLengths(k); end % mot.jointTrajectories = iterativeForwKinematics(skel,mot); end mot = changeFrameRate(skel,mot,res_args.newFrameRate); for mm=1:1+options.addMirrors c = c+1; if mm==2 [skel,mot] = mirrorMot(skel,mot); % mirrorMot does forward kinematics res.motNames{c} = [amc_filename '.mirrored']; else res.motNames{c} = amc_filename; end if options.correctWristOrientations [mot,res_tmp] = correctOrientationsInMot(skel,mot); mot.jointTrajectories = iterativeForwKinematics(skel,mot); end res.motStartIDs(c) = frame; if options.addSkel res.skels{c} = skel; end if options.addVelOrig, mot = addVelToMot(mot); end; if options.addAccOrig, mot = addAccToMot(mot); end; if options.addFootprints [mot,res.dbAnnotation(j)] = detectFootprints(skel,mot,aq); end sf = frame; ef = frame+mot.nframes-1; if options.addPosOrig, res.posOrig(:,sf:ef) = cell2mat(mot.jointTrajectories); end if options.addVelOrig, res.velOrig(:,sf:ef) = cell2mat(mot.jointVelocities); end if options.addAccOrig, res.accOrig(:,sf:ef) = cell2mat(mot.jointAccelerations); end if options.addOrigRootPos, res.origRootPos(:,sf:ef) = mot.rootTranslation; end if options.addOrigRootOri, res.origRootOri(:,sf:ef) = mot.rotationQuat{1}; end if mm==1 if options.addFootprints, res.footprints(:,sf:ef) = mot.footprints; end else % mirror footprints if options.addFootprints, res.footprints(:,sf:ef) = flipud(mot.footprints); end end if options.addDeltaRootPos t1 = mot.rootTranslation(:,1:end-1); t2 = mot.rootTranslation(:,2:end); res.deltaRootPos(:,sf:ef) = [ [0;0;0] C_quatrot(t2-t1,C_quatinv(mot.rotationQuat{1}(:,2:end)))]; end if options.addDeltaRootOri q1 = mot.rotationQuat{1}(:,1:end-1); q2 = mot.rotationQuat{1}(:,2:end); res.deltaRootOri(:,sf:ef) = [[1;0;0;0] C_quatmult(C_quatinv(q1),q2)]; end if options.addPos || options.addVel || options.addAcc || options.addQuat || options.addEuler || options.addAccL || options.addVelL mot0 = mot; mot0.rootTranslation(:,:) = 0; [mot0,qy,~,q_L2G] = fitRootOrientationsFrameWise(skel,mot0); if options.addInvRootRot res.invRootRot(:,sf:ef) = qy; end if options.addPos res.pos(:,sf:ef) = cell2mat(mot0.jointTrajectories); end if options.addVelL || options.addAccL q_G2L = cellfun(@(x) C_quatinv(x),q_L2G,'UniformOutput',0); end if options.addVel || options.addVelL mot0 = addVelToMot(mot0); if options.addVel res.vel(:,sf:ef) = cell2mat(mot0.jointVelocities); end if options.addVelL res.velL(:,sf:ef) = cell2mat(cellfun(@(x,y) C_quatrot(x,y),mot0.jointVelocities,q_G2L,'UniformOutput',0)); end end if options.addAcc || options.addAccL mot0 = addAccToMot(mot0); if options.addAcc res.acc(:,sf:ef) = cell2mat(mot0.jointAccelerations); end if options.addAccL res.accL(:,sf:ef) = cell2mat(cellfun(@(x,y) C_quatrot(x,y),mot0.jointAccelerations,q_G2L,'UniformOutput',0)); end end if options.addEuler mot0 = convert2euler(skel,mot0); res.euler(:,sf:ef) = real(cell2mat(mot0.rotationEuler(mot0.animated))); end if options.addQuat res.quat(:,sf:ef) = cell2mat(mot0.rotationQuat(mot0.animated)); end end if options.addSensorAccs if ~options.correctWristOrientations || mm==2 res_tmp = simulateLocalAccsFromAMC2(skel,mot); end for s=1:nrOfSensors res.sensorAccs.(sensors{s})(:,sf:ef) = res_tmp.(sensors{s}).acc_L; end end frame = frame + mot.nframes; fprintf('\b\b\b\b\b\b\b%7i',frame-1); end end end end if options.addFootprints % delete Java object clear('aq'); end fprintf(' ...finished.\n'); if frame-1<totalNrOfFrames || c<totalNrOfFiles res = cleanup_local(res,totalNrOfFiles,c,totalNrOfFrames,frame-1); res.nrOfFrames = frame-1; else res.nrOfFrames = frame-1; end end %% local functions function db = cleanup_local(db,totalNrOfFiles,actualNrOfFiles,totalNrOfFrames,actualNrOfFrames) % if c~=totalNrOfFiles % res.motNames = res.motNames(1:c); % res.motStartIDs = res.motStartIDs(1:c); % end % totalNrOfFrames = db.nrOfFrames; % totalNrOfFiles = numel(db.motStartIDs); % mots2keep = 1:actualNrOfFiles; % frames2keep = 1:actualNrOfFrames; fields = fieldnames(db); for f=1:size(fields,1) field = fields{f}; [a,b]=ismember([totalNrOfFiles,totalNrOfFrames],size(db.(field))); if all(a) fprintf('Caution: Field %s is of ambiguous size. Please remove values manually.\n',field); elseif a(1) if b(1)==1 % db.(field)=db.(field)(mots2keep,:); db.(field)(actualNrOfFiles+1:end,:) = []; elseif b(1)==2 db.(field)(:,actualNrOfFiles+1:end) = []; % db.(field)=db.(field)(:,mots2keep); end elseif a(2) if b(2)==1 db.(field)(actualNrOfFrames+1:end,:) = []; % db.(field)=db.(field)(frames2keep,:); elseif b(2)==2 db.(field)(:,actualNrOfFrames+1:end) = []; % db.(field)=db.(field)(:,frames2keep); end elseif isstruct(db.(field)) db.(field) = cleanup_local(db.(field),totalNrOfFiles,actualNrOfFiles,totalNrOfFrames,actualNrOfFrames); end end end function isskel = isSkel_local(var) isskel = isstruct(var) && all(isfield(var,{'njoints','nodes'})); end function isframerate = isFrameRate_local(var) isframerate = isnumeric(var) && numel(var)==1; end function isbonelengthsarray = isBoneLengthsArray_local(var) isbonelengthsarray = isnumeric(var) && numel(var)==31; end function [totalNrOfFrames,totalNrOfAMCFiles,totalNrOfMATFiles] = countFiles_local(FilesOrFolders,minFrameNumber,origFrameRate,newFrameRate) totalNrOfFrames = 0; totalNrOfAMCFiles = 0; totalNrOfMATFiles = 0; for i=1:length(FilesOrFolders) if isdir(FilesOrFolders{i}) files = dir(fullfile(FilesOrFolders{i},'*.amc')); nrOfAMCFiles = numel(files); if nrOfAMCFiles==0 nrOfMATFiles = numel(dir(fullfile(FilesOrFolders{i},'*.mat'))); else nrOfMATFiles = 0; end pathstr = FilesOrFolders{i}; else [pathstr, name, ext] = fileparts(FilesOrFolders{i}); if strcmp(ext,'.amc') nrOfAMCFiles = 1; nrOfMATFiles = 0; clear files; files(1).name = [name ext]; elseif strcmp(ext,'.mat'), if numel((dir(fullfile(pathstr,name))))>0 clear files; files(1).name = name; nrOfAMCFiles = 1; nrOfMATFiles = 0; else nrOfMATFiles = 1; nrOfAMCFiles = 0; end end end if nrOfAMCFiles>0 for j=1:nrOfAMCFiles amc_filename = fullfile(pathstr,files(j).name); nrOfFrames = readNrOfFramesFromFile(amc_filename); if (nrOfFrames >= minFrameNumber) nrOfFrames = numel(1:origFrameRate/newFrameRate:nrOfFrames); totalNrOfFrames = totalNrOfFrames + nrOfFrames; totalNrOfAMCFiles = totalNrOfAMCFiles + 1; end fprintf('\b\b\b\b\b\b\b%7i',totalNrOfFrames); end else totalNrOfMATFiles = totalNrOfMATFiles + nrOfMATFiles; end end end function res = checkargins_local(argins,origFrameRate) % Checking nargins -------------------------------------------------------- switch numel(argins) case 0 res.newFrameRate = origFrameRate; res.individualSkels = true; case 1 if isSkel_local(argins{1}) res.individualSkels = false; res.individualBoneLengths = false; res.FixedSkel = argins{1}; elseif isFrameRate_local(argins{1}) res.individualSkels = true; res.individualBoneLengths = true; res.newFrameRate = argins{1}; elseif isBoneLengthsArray_local(argins{1}) res.individualSkels = true; res.individualBoneLengths = false; res.FixedBoneLengths = argins{1}; else error('Wrong types of argins!'); end case 2 if isSkel_local(argins{1}) && isFrameRate_local(argins{2}) res.individualSkels = false; res.individualBoneLengths = false; res.FixedSkel = argins{1}; res.newFrameRate = argins{2}; elseif isSkel_local(argins{2}) && isFrameRate_local(argins{1}) res.individualSkels = false; res.individualBoneLengths = false; res.FixedSkel = argins{2}; res.newFrameRate = argins{1}; elseif isFrameRate_local(argins{1}) && isBoneLengthsArray_local(argins{2}) res.individualSkels = true; res.individualBoneLengths = false; res.newFrameRate = argins{1}; res.FixedBoneLengths = argins{2}; elseif isFrameRate_local(argins{2}) && isBoneLengthsArray_local(argins{1}) res.individualSkels = true; res.individualBoneLengths = false; res.newFrameRate = argins{2}; res.FixedBoneLengths = argins{1}; else error('Wrong types of argins!'); end otherwise error('Wrong number of argins!'); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
emptyMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/parser/emptyMotion.m
6,695
utf_8
8b76a6adb6c20591b900c33d82bc4bd4
function mot = emptyMotion(varargin) switch nargin case 0 mot = struct('njoints',0,... % number of joints 'nframes',0,... % number of frames 'frameTime',nan,... % inverse sampling rate: time per frame (in seconds) 'samplingRate',nan,... % sampling rate (in Hertz) (120 Hertz is Carnegie-Mellon Mocap-DB standard) 'jointTrajectories',cell(1,1),... % 3D joint trajectories 'rootTranslation',[],... % global translation data stream of the root 'rotationEuler',cell(1,1),... % rotational data streams for all joints, including absolute root rotation at pos. 1, Euler angles 'rotationQuat',cell(1,1),... % rotational data streams for all joints, including absolute root rotation at pos. 1, quaternions 'jointNames',cell(1,1),... % cell array of joint names: maps node ID to joint name 'boneNames',cell(1,1),... % cell array of bone names: maps bone ID to node name. ID 1 is the root. 'nameMap',cell(1,1),... % cell array mapping standard joint names to DOF IDs and trajectory IDs 'animated',[],... % vector of IDs for animated joints/bones 'unanimated',[],... % vector of IDs for unanimated joints/bones 'boundingBox',[],... % bounding box (given a specific skeleton) 'filename','',... % source filename 'documentation','',... % documentation from source file 'angleUnit','deg'); % angle unit, either deg or rad case 1 if ismot_local(varargin{1}) refmot = varargin{1}; mot = struct('njoints',refmot.njoints,... % number of joints 'nframes',0,... % number of frames 'frameTime',refmot.frameTime,... % inverse sampling rate: time per frame (in seconds) 'samplingRate',refmot.samplingRate,... % sampling rate (in Hertz) (120 Hertz is Carnegie-Mellon Mocap-DB standard) 'jointTrajectories',[],...cell(refmot.njoints,1),...% 3D joint trajectories 'rootTranslation',[],... % global translation data stream of the root 'rotationEuler',[],...{cell(refmot.njoints,1)},...% rotational data streams for all joints, including absolute root rotation at pos. 1, Euler angles 'rotationQuat',[],...{cell(refmot.njoints,1)},...% rotational data streams for all joints, including absolute root rotation at pos. 1, quaternions 'jointNames',{refmot.jointNames},... % cell array of joint names: maps node ID to joint name 'boneNames',{refmot.boneNames},... % cell array of bone names: maps bone ID to node name. ID 1 is the root. 'nameMap',{refmot.nameMap},... % cell array mapping standard joint names to DOF IDs and trajectory IDs 'animated',refmot.animated,... % vector of IDs for animated joints/bones 'unanimated',refmot.unanimated,... % vector of IDs for unanimated joints/bones 'boundingBox',[],... % bounding box (given a specific skeleton) 'filename','',... % source filename 'documentation','',... % documentation from source file 'angleUnit','deg'); % angle unit, either deg or rad elseif isskel_local(varargin{1}) skel = varargin{1}; mot = struct('njoints',skel.njoints,... % number of joints 'nframes',0,... % number of frames 'frameTime',nan,... % inverse sampling rate: time per frame (in seconds) 'samplingRate',nan,... % sampling rate (in Hertz) (120 Hertz is Carnegie-Mellon Mocap-DB standard) 'jointTrajectories',[],...{cell(skel.njoints,1)},...% 3D joint trajectories 'rootTranslation',[],... % global translation data stream of the root 'rotationEuler',[],...{cell(skel.njoints,1)},... % rotational data streams for all joints, including absolute root rotation at pos. 1, Euler angles 'rotationQuat',[],...{cell(skel.njoints,1)},... % rotational data streams for all joints, including absolute root rotation at pos. 1, quaternions 'jointNames',{skel.jointNames},... % cell array of joint names: maps node ID to joint name 'boneNames',{skel.boneNames},... % cell array of bone names: maps bone ID to node name. ID 1 is the root. 'nameMap',{skel.nameMap},... % cell array mapping standard joint names to DOF IDs and trajectory IDs 'animated',skel.animated,... % vector of IDs for animated joints/bones 'unanimated',skel.unanimated,... % vector of IDs for unanimated joints/bones 'boundingBox',[],... % bounding box (given a specific skeleton) 'filename','',... % source filename 'documentation','',... % documentation from source file 'angleUnit','deg'); % angle unit, either deg or rad end end end %% local functions function ismot_bool = ismot_local(arg) if isfield(arg,'nframes') && isfield(arg,'rotationQuat') ismot_bool = true; else ismot_bool = false; end end function isskel_bool = isskel_local(arg) if isfield(arg,'njoints') && isfield(arg,'nodes') isskel_bool = true; else isskel_bool = false; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
amc_to_matrix.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/parser/ASFAMCparser/amc_to_matrix.m
2,671
utf_8
32da4a50441d0da713b0bb6ea3349c22
% Reads data from an AMC motion file into a Matlab matrix variable. % AMC file has to be in the AMC format used in the online CMU motion capture library. % number of dimensions = number of columns = 62 % function D = amc_to_matrix(fname) % fname = name of disk input file, in AMC format % Example: % D = amc_to_matrix(fname) % % Jernej Barbic % CMU % March 2003 % Databases Course function [D] = amc_to_matrix(fname) fid=fopen(fname, 'rt'); if fid == -1, fprintf('Error, can not open file %s.\n', fname); return; end; % read-in header line=fgetl(fid); while ~strcmp(line,':DEGREES') line=fgetl(fid); end D=[]; dims =[6 3 3 3 3 3 3 2 3 1 1 2 1 2 2 3 1 1 2 1 2 3 1 2 1 3 1 2 1]; locations = [1 7 10 13 16 19 22 25 27 30 31 32 34 35 37 39 42 43 44 46 47 49 52 53 55 56 59 60 62]; % read-in data % labels can be in any order frame=1; while ~feof(fid) if rem(frame,100) == 0 disp('Reading frame: '); disp(frame); end; row = zeros(62,1); % read frame number line = fscanf(fid,'%s\n',1); for i=1:29 % read angle label id = fscanf (fid,'%s',1); switch (id) case 'root', index = 1; case 'lowerback', index = 2; case 'upperback', index = 3; case 'thorax', index = 4; case 'lowerneck', index = 5; case 'upperneck', index = 6; case 'head', index = 7; case 'rclavicle', index = 8; case 'rhumerus', index = 9; case 'rradius', index = 10; case 'rwrist', index = 11; case 'rhand', index = 12; case 'rfingers', index = 13; case 'rthumb', index = 14; case 'lclavicle', index = 15; case 'lhumerus', index = 16; case 'lradius', index = 17; case 'lwrist', index = 18; case 'lhand', index = 19; case 'lfingers', index = 20; case 'lthumb', index = 21; case 'rfemur', index = 22; case 'rtibia', index = 23; case 'rfoot', index = 24; case 'rtoes', index = 25; case 'lfemur', index = 26; case 'ltibia', index = 27; case 'lfoot', index = 28; case 'ltoes', index = 29; otherwise fprintf('Error, labels in the amc are not correct.\n'); return; end % where to put the data location = locations(index); len = dims(index); if len == 6 x = fscanf (fid,'%f %f %f %f %f %f\n',6); else if len == 3 x = fscanf (fid,'%f %f %f\n',3); else if len == 2 x = fscanf (fid,'%f %f\n',2); else if len == 1 x = fscanf (fid,'%f\n',1); end end end end row(location:location+len-1,1) = x; end row = row'; D = [D; row]; frame = frame + 1; end disp('Total number of frames read: '); disp(frame-1); fclose(fid);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
matrix_to_amc.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/parser/ASFAMCparser/matrix_to_amc.m
2,225
utf_8
3d0a06d61f8d69c60c6e78641144ea64
% Writes motion data from matrix D to an AMC file on disk. % The ACM format is the format used in the CMU online motion capture database % function [] = matrix_to_amc(fname, D) % fname = output disk file name for AMC file % D = input Matlab data matrix % Example: % matrix_to_amc('running1.amc', D) % % % Jernej Barbic % CMU % March 2003 % Databases Course function [] = matrix_to_amc(fname, D) fid=fopen(fname, 'wt'); if fid == -1, fprintf('Error, can not open file %s.\n', fname); return; end; % print header fprintf(fid,'#!Matlab matrix to amc conversion\n'); fprintf(fid,':FULLY-SPECIFIED\n'); fprintf(fid,':DEGREES\n'); [rows, cols] = size(D); % print data for frame=1:rows fprintf(fid,'%d\n',frame); fprintf(fid,'root %f %f %f %f %f %f\n', D(frame,1:6)); fprintf(fid,'lowerback %f %f %f\n', D(frame,7:9)); fprintf(fid,'upperback %f %f %f\n', D(frame,10:12)); fprintf(fid,'thorax %f %f %f\n', D(frame,13:15)); fprintf(fid,'lowerneck %f %f %f\n', D(frame,16:18)); fprintf(fid,'upperneck %f %f %f\n', D(frame,19:21)); fprintf(fid,'head %f %f %f\n', D(frame,22:24)); fprintf(fid,'rclavicle %f %f\n', D(frame,25:26)); fprintf(fid,'rhumerus %f %f %f\n', D(frame,27:29)); fprintf(fid,'rradius %f\n', D(frame,30)); fprintf(fid,'rwrist %f\n', D(frame,31)); fprintf(fid,'rhand %f %f\n', D(frame,32:33)); fprintf(fid,'rfingers %f\n', D(frame,34)); fprintf(fid,'rthumb %f %f\n', D(frame,35:36)); fprintf(fid,'lclavicle %f %f\n', D(frame,37:38)); fprintf(fid,'lhumerus %f %f %f\n', D(frame,39:41)); fprintf(fid,'lradius %f\n', D(frame,42)); fprintf(fid,'lwrist %f\n', D(frame,43)); fprintf(fid,'lhand %f %f\n', D(frame,44:45)); fprintf(fid,'lfingers %f\n', D(frame,46)); fprintf(fid,'lthumb %f %f\n', D(frame,47:48)); fprintf(fid,'rfemur %f %f %f\n', D(frame,49:51)); fprintf(fid,'rtibia %f\n', D(frame,52)); fprintf(fid,'rfoot %f %f\n', D(frame,53:54)); fprintf(fid,'rtoes %f\n', D(frame,55)); fprintf(fid,'lfemur %f %f %f\n', D(frame,56:58)); fprintf(fid,'ltibia %f\n', D(frame,59)); fprintf(fid,'lfoot %f %f\n', D(frame,60:61)); fprintf(fid,'ltoes %f\n', D(frame,62)); end fclose(fid);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
filterR4.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/quaternions/filterR4.m
2,217
utf_8
c795e21bddf40ecb117cc6e70f7f575c
function [Y,t] = filterR4(varargin) % Y = filterR4(w,X,step,padding_method) % Filters curves embedded in the unit quaternion sphere with a sliding window. % Simply views quats as 4D data without additional structure and renormalizes % to S^3 after filtering % % Input: w, weight vector % X, 4xN matrix of input unit quaternions % optional: step, step size for window (window length is length(w)), default is step=1. % ->!! Length of output sequence is ceil(N/step). !! <- % optional: padding method, one of {'symmetric', 'zero'}. default is 'symmetric' % % Output: Y, Filtered version of X % t, running time for filter. % switch (nargin) case 2 w = varargin{1}; X = varargin{2}; step = 1; padding_method = 'symmetric'; case 3 w = varargin{1}; X = varargin{2}; step = varargin{3}; padding_method = 'symmetric'; case 4 w = varargin{1}; X = varargin{2}; step = varargin{3}; padding_method = varargin{4}; otherwise error('Wrong number of arguments!'); end L = size(w,2); N = size(X,2); if (L>N) error('Filter length must not be larger than number of data points!'); end %%%% prepare data set X by means of pre- and postpadding switch mod(L,2) case 0 % even filter length prepad_length = L/2; postpad_length = L/2 - 1; case 1 % odd filter length prepad_length = (L - 1)/2; postpad_length = (L - 1)/2; end tic; if (strncmp(padding_method,'symmetric',1)) pre = fliplr(X(:,1:prepad_length)); post = fliplr(X(:,N-postpad_length+1:N)); elseif (strncmp(padding_method,'zero',1)) pre = [ones(1,prepad_length);zeros(3,prepad_length)]; post = [ones(1,postpad_length);zeros(3,postpad_length)];; else error('Unknown padding option!'); end X = [pre X post]; Y = zeros(4,ceil(N/step)); for (i=1:ceil(N/step)) pos = step*(i-1)+1; Y(:,i) = bruteForceAverageR4(X(:,pos:pos+L-1),w); end t = toc; %%%%%%%%%%% function Y = bruteForceAverageR4(X,w) Y = sum(X.*repmat(w,4,1),2); Y = Y./sqrt(sum(Y.^2,1));
github
umariqb/3D_Pose_Estimation_CVPR2016-master
isColor.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionplayer/isColor.m
295
utf_8
e20f1469401335aa9acac9aed8ad5f54
%% validator for color % returns true if x is a 1x3 matrix of doubles between 0.0 and 1.0 function val = isColor(x) if(... min(min(x)) >= 0.0 && ... max(max(x)) <= 1.0 && ... size(x,1) == 1 && ... size(x,2) == 3) val = 1; else val = 0; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
removeDupVerts.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionplayer/removeDupVerts.m
788
utf_8
8a886ae550cf2eca76d4d94c848de739
% remove duplicate vertices and replace indices in patch with new % vertex indices function [vertsOut,patchesOut] = removeDupVerts(vertsIn, patchesIn) patchesOut = patchesIn'; index = [1:size(vertsIn,1);zeros(1,size(vertsIn,1))]'; for i = 1:size(vertsIn,1) for j = 1:size(vertsIn,1) if(~index(j,2)) if(vertsIn(i,1) == vertsIn(j,1) &&... vertsIn(i,2) == vertsIn(j,2) &&... vertsIn(i,3) == vertsIn(j,3)) index(j,1) = i; index(j,2) = 1; end end end end vertsUsed = intersect(1:size(vertsIn,1), index(:,1)); vertsOut = vertsIn(vertsUsed,:); for i = 1:size(index,1) patchesOut(i) = find(vertsUsed == index(i,1)); end patchesOut = patchesOut'; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
isMot.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionplayer/isMot.m
1,399
utf_8
eea71926a8ea8e1bbe6cb280b10db8e5
function out = isMot(mot) % returns true if given argument is a motion-type structure % this function tests if mot is of type struct and contains the % following fields % fieldsRequired = {... % 'njoints', 'nframes', 'frameTime', 'samplingRate'... % 'jointTrajectories', 'rootTranslation', 'rotationEuler',... % 'rotationQuat', 'jointNames', 'boneNames', 'nameMap',... % 'animated', 'unanimated', 'boundingBox', 'filename',... % 'documentation', 'angleUnit'}; fieldsRequired = {... 'njoints', 'nframes', 'frameTime', 'samplingRate'... 'jointTrajectories', 'boundingBox', 'filename'}; for i = 1:size(mot,2) m = mot{1,i}; if(isstruct(m)) fieldsInMot = fieldnames(m); for f = fieldsRequired if (any(strcmp(f,fieldsInMot))) else out = false; fprintf('motion is not valid: \n\t field ''%s'' is missing\n', f{1,1}); break; end out = true; end else out = false; fprintf('type mismatch on ''mot'': type struct expected\n'); break; end end if(out == false) r = ''; for f = fieldsRequired r = strcat('''',f{1,1},'''',',', r); end r = strcat('fields required for mot: \n\t(',r,')\n'); fprintf(r); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
plotMultiLayerResult2Fig_forVideo.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionplayer/video/plotMultiLayerResult2Fig_forVideo.m
7,956
utf_8
ee68b584f34ba9d1d719815af8bd9f60
function plotMultiLayerResult2Fig_forVideo(annotation,hits4File, parameter) if nargin < 3 parameter = struct; end if isfield(parameter, 'printFigure') == 0 parameter.printFigure = 0; end if isfield(parameter, 'filenamePrefix') == 0 parameter.filenamePrefix = 'figures/tensorClassification_'; end if isfield(parameter, 'paperPositionClassification') == 0 parameter.paperPositionClassification = [1,1,6.3,2.5]; end if isfield(parameter, 'paperPositionPartDTW') == 0 parameter.paperPositionPartDTW = [1,1,6.3,2.5]; end if isfield(parameter, 'omitTitle') == 0 parameter.omitTitle = 0; end if isfield(parameter, 'drawFineAnnotations') == 0 parameter.drawFineAnnotations = 1; end if isfield(parameter,'highlightFrame')==0 parameter.highlightFrame = 0; end if isfield(parameter,'position')==0 parameter.position = [ 200 200 1000 440]; end global VARS_GLOBAL; motClasses = flipud(fieldnames(annotation)); document=hits4File.amc; docLength = hits4File.orgNumFrames; figure(); set(gcf, 'renderer', 'painters') ; set(gcf, 'name', [document]); [temp, docShortName] = fileparts(document); set(gcf, 'position', parameter.position) subplot(7,1,1:4); set(gcf, 'color', [1, 1, 1]); %% Collect Annotations for document. % hitData = classificationResult.(class)((classificationResult.(class)(:,1) == currentDocument), [2:3, 6]); % h1=subplot(2,1,1); set(gca, 'ytick', [1.5:2:length(motClasses)*2]); set(gca, 'yticklabel', motClasses); % set(gca, 'XTick',1:100:hits4File.orgNumFrames); % set(gca, 'XTickLabel',0:100:hits4File.orgNumFrames); axis([0 hits4File.orgNumFrames 0.5 length(motClasses)*2+0.5]); for mClass=1:size(motClasses,1); line([1, hits4File.orgNumFrames], [2*mClass+0.5, 2*mClass+0.5]); hitData=zeros(1,2); count=1; if ~isempty(annotation.(motClasses{mClass})) for i=1:size(annotation.(motClasses{mClass}),1); if strcmp(strcat(VARS_GLOBAL.dir_root,annotation.(motClasses{mClass})(i,3)),document) hitData(count,:)=cell2mat(annotation.(motClasses{mClass})(i,1:2)); files{count}=annotation.(motClasses{mClass})(i,3); count=count+1; end end end for h=1:size(hitData, 1) hitStart = hitData(h, 1); hitEnd = hitData(h, 2); % remap from 30Hz to 120 Hz % animationStart = hitStart * 4 - 4 + 1; % animationEnd = hitEnd * 4 - 4 + 1; %draw rectangle color = [1 0 0]; %[0 127 14]/255; yPosition = mClass*2; if ~parameter.drawFineAnnotations && parameter.highlightFrame >= hitStart && parameter.highlightFrame <= hitEnd color = [0,1,1]; % cyan end hitWidth = hitStart-hitEnd; if hitWidth == 0 handle = line([hitStart, hitStart], [yPosition-0.3, yPosition+0.3], 'Color', [0,0,0], 'LineWidth', 1); else handle = rectangle('Position', [hitStart, yPosition-0.3,... hitEnd - hitStart+1, 0.6],... 'EdgeColor', [0 0 0],... 'FaceColor', color,... 'LineWidth', 0.1); end % set(handle,'ButtonDownFcn',{@animateRectOnClick,... % docName,... % animationStart,... % animationEnd, ... % cost,... % hitStart,... % hitEnd,... % }); end end if (parameter.drawFineAnnotations) for hit=1:hits4File.numHits mClassStr = hits4File.hitProperties{1,hit}.motionClass; tmp=strfind(motClasses,cell2mat(mClassStr)); mClass=1; while isempty(cell2mat(tmp(mClass))) mClass=mClass+1; end hitStart=hits4File.startFrames(hit); hitEnd =hits4File.endFrames (hit); color = [0 0.7 0]; yPosition = 2*mClass-1; hitWidth = hitStart-hitEnd; if hitWidth == 0 handle = line([hitStart, hitStart], [yPosition-0.3, yPosition+0.3], 'Color', [0,0,0], 'LineWidth', 1); else if parameter.highlightFrame >= hitStart && parameter.highlightFrame <= hitEnd color = [0,1,1]; % cyan end handle = rectangle('Position', [hitStart, yPosition-0.3,... hitEnd - hitStart+1, 0.6],... 'EdgeColor', [0 0 0],... 'FaceColor', color,... 'LineWidth', 0.1); end end end line([docLength, docLength], [0.5, 2*length(motClasses)+0.5], 'Color', [0,0,0]); line([1, docLength], [2*length(motClasses)+0.5, 2*length(motClasses)+0.5], 'Color', [0,0,0]); if parameter.highlightFrame > 0 line([parameter.highlightFrame, parameter.highlightFrame], [0.5, 2*length(motClasses)+0.5], 'Color', [0,1,1]); end %% Collect PartDTW Hits for Document! if (parameter.drawFineAnnotations) subplot(7,1,6:7); set(gcf, 'renderer', 'painters') ; set(gcf, 'name', [document]); %create styleList [numHits,coeffs,styleList]=countHitsPerFrameAndCoefs(hits4File); ylabels = renameSubclasses(styleList); set(gca, 'ytick', 1:1:size(styleList,2)); set(gca, 'yticklabel', ylabels); % set(gca, 'XTick',1:100:hits4File.orgNumFrames); % set(gca, 'XTickLabel',0:100:hits4File.orgNumFrames); for styInd=1:size(styleList,2) line([1, hits4File.orgNumFrames], [styInd+0.5, styInd+0.5]); end axis([0 hits4File.orgNumFrames 0.5 size(styleList,2)+0.5]); for hit=1:hits4File.numHits [maxval,maxPos]=max(hits4File.hitProperties{1,hit}.res.coeffsX{1}); subClass=hits4File.hitProperties{1,hit}.styles{maxPos}; tmp=strfind(styleList,subClass); mClass=1; while isempty(cell2mat(tmp(mClass))) mClass=mClass+1; end hitStart=hits4File.startFrames(hit); hitEnd =hits4File.endFrames (hit); if maxval>0.0 color=[0 0.7 0]; else color=[0 1 0]; end yPosition = mClass; hitWidth = hitStart-hitEnd; if hitWidth == 0 handle = line([hitStart, hitStart], [yPosition-0.3, yPosition+0.3], 'Color', [0,0,0], 'LineWidth', 1); else if parameter.highlightFrame >= hitStart && parameter.highlightFrame <= hitEnd color = [0,1,1]; % cyan end handle = rectangle('Position', [hitStart, yPosition-0.3,... hitEnd - hitStart+1, 0.6],... 'EdgeColor', [0 0 0],... 'FaceColor', color,... 'LineWidth', 0.1); set(handle,'ButtonDownFcn',{@motionPlayerCallback2, ... hits4File.hitProperties{1,hit}.res.skel, ... hits4File.hitProperties{1,hit}.orgMot, ... hits4File.hitProperties{1,hit}.res.skel, ... hits4File.hitProperties{1,hit}.recMotUnWarp}); end end line([docLength, docLength], [0.5, 2*length(styleList)+0.5], 'Color', [0,0,0]); line([1, docLength], [length(styleList)+0.5, length(styleList)+0.5], 'Color', [0,0,0]); if parameter.highlightFrame > 0 line([parameter.highlightFrame, parameter.highlightFrame], [0.5, 2*length(styleList)+0.5], 'Color', [0,1,1]); end end end function motionPlayerCallback1(src, eventdata, skel1, mot1) motionplayer('skel',{skel1}, 'mot', {mot1}); end function motionPlayerCallback2(src, eventdata, skel1, mot1, skel2, mot2) motionplayer('skel',{skel1 skel2}, 'mot', {mot1 mot2}); end function motionPlayerCallbackLoad(src, eventdata, amc, startF, endF) infos=filename2info(amc); [skel,mot] =readMocap(fullfile(infos.amcpath,infos.asfname),amc); mot=cutMotion(mot,startF,endF); motionplayer('skel',{skel}, 'mot', {mot}); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
reverseMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/reverseMotion.m
379
utf_8
645f63d913001e86ef960cb567c449c1
% function reverseMotion % author: Jochen Tautges ([email protected]) function mot = reverseMotion(skel,mot) mot.rotationQuat = cellfun(@(x) fliplr(x),mot.rotationQuat,'UniformOutput',0); mot.filename = [mot.filename '.reversed']; mot.rootTranslation = fliplr(mot.rootTranslation); mot.jointTrajectories = iterativeForwKinematics(skel,mot);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
fitMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/fitMotion.m
1,137
utf_8
6699036712fc3b7a111e64eebc7a4d0b
% FUNCTION fitMotion applays a translation and a rotation around y-axis to % a given motion. The motion is moved with root position to the origin with % the first frame. And rotated that the main direction goes along the % x-Axis. % INPUT: % skel: struct: skeleton definition for the motion % mot: struct: function [mot,angle,x0,z0]=fitMotion(skel,mot) % Spatial correspondence ------------------------------------------- % translation into y-axis x0=mot.rootTranslation(1,1); z0=mot.rootTranslation(3,1); mot.rootTranslation(1,:)=mot.rootTranslation(1,:)-x0; mot.rootTranslation(3,:)=mot.rootTranslation(3,:)-z0; if (sqrt(mot.rootTranslation(1,mot.nframes)^2+mot.rootTranslation(3,mot.nframes)^2)>10) u=[mot.rootTranslation(1,mot.nframes);mot.rootTranslation(3,mot.nframes)]; v=[1;0]; angle=acos((u'*v)/(sqrt(u'*u))); if u(2)<0 angle=-angle; end else m=quatrot([0;0;1],mot.rotationQuat{1}(:,1)); u=[m(1);m(3)]; v=[1;0]; angle=acos((u'*v)/(sqrt(u'*u))); if u(2)<0 angle=-angle; end end mot=rotateMotion(skel,mot,angle,'y');
github
umariqb/3D_Pose_Estimation_CVPR2016-master
translateMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/translateMotion.m
953
utf_8
e96682ed915c35d67d8dec51f6cf98c1
% function translateMotion % translates a motion with specified translation % mot = translateMotion(skel,mot,x,y,z) % author: Jochen Tautges ([email protected]) function mot = translateMotion(skel,mot,x,y,z,varargin) computetrajsbb=true; if (nargin == 6) computetrajsbb=varargin{1}; end mot.rootTranslation(1,:) = mot.rootTranslation(1,:)+x; mot.rootTranslation(2,:) = mot.rootTranslation(2,:)+y; mot.rootTranslation(3,:) = mot.rootTranslation(3,:)+z; if (computetrajsbb) mot.jointTrajectories = C_forwardKinematicsQuat(skel,mot); mot.boundingBox = computeBoundingBox(mot); end if (isfield(mot,'jointVelocities')&&~isempty(mot.jointVelocities) && mot.nframes>1) mot = addVelToMot(mot); end if (isfield(mot,'jointAccelerations')&&~isempty(mot.jointAccelerations) && mot.nframes>1) mot = addAccToMot(mot); end %fprintf('Motion successfully translated with x=%.2f, y=%.2f, z=%.2f.\n',x,y,z);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
removeSkating.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/removeSkating.m
999
utf_8
4a6011f9d697887866ed98d58c66ecea
% function removeSkating % performs simple (naive) clean up of skating effects % mot = removeSkating(skel,mot) % author: Jochen Tautges ([email protected]) function mot = removeSkating(skel,mot) leftJoint = 4; rightJoint = 7; badTranslation=0; for i=2:mot.nframes if mot.jointTrajectories{leftJoint}(2,i)<=mot.jointTrajectories{rightJoint}(2,i) % left foot on floor joint = leftJoint; else joint = rightJoint; end badTranslation = badTranslation + mot.jointTrajectories{joint}([1,3],i)... - mot.jointTrajectories{joint}([1,3],i-1); mot.rootTranslation([1,3],i) = mot.rootTranslation([1,3],i) - badTranslation; end pos = cell2mat(mot.jointTrajectories([leftJoint,rightJoint])); minY = min(min(pos(2:3:end,:))); mot.rootTranslation(2,:) = mot.rootTranslation(2,:)-minY; mot.jointTrajectories = forwardKinematicsQuat(skel,mot); mot.boundingBox = computeBoundingBox(mot);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
removeOrientation.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/removeOrientation.m
744
utf_8
60ebeb2fc2ab79ed3130e0cd080802c0
% function removeOrientation % removes the global orientation (root orientation) of a motion % mot = removeOrientation(skel,mot) % author: Jochen Tautges ([email protected]) function mot = removeOrientation(skel,mot) if ~(isempty(mot.rotationQuat)) mot.rotationQuat{1}=[ones(1,mot.nframes);zeros(3,mot.nframes)]; end if ~(isempty(mot.rotationEuler)) mot.rotationEuler{1}=zeros(size(mot.rotationEuler{1})); end mot.jointTrajectories=forwardKinematicsQuat(skel,mot); mot.boundingBox=computeBoundingBox(mot); if (isfield(mot,'jointVelocities')&&~isempty(mot.jointVelocities)) mot=addVelToMot(mot); end if (isfield(mot,'jointAccelerations')&&~isempty(mot.jointAccelerations)) mot=addAccToMot(mot); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
addVelToMot.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/addVelToMot.m
1,798
utf_8
8972ec6857f06618cd7591854f8fd178
% function mot = addVelToMot(mot) % computes joint velocities in each frame and adds the field % 'jointVelocities' to mot structure % additionally filters the computed velocities with binomial filter % author: Jochen Tautges ([email protected]) function mot = addVelToMot(mot,varargin) if nargin==2 filterSize = varargin{1}; else filterSize = min(floor(mot.samplingRate/10),floor(mot.nframes/2)); end if iscell(mot.jointTrajectories) jointTrajectories = double(cell2mat(mot.jointTrajectories)); else jointTrajectories = mot.jointTrajectories; end jointVelocities = zeros(size(jointTrajectories)); if mot.nframes>1 % padding jointTrajectories = [ 3*jointTrajectories(:,1)-2*jointTrajectories(:,2),... 2*jointTrajectories(:,1)-jointTrajectories(:,2),... jointTrajectories,... 2*jointTrajectories(:,end)-jointTrajectories(:,end-1),... 3*jointTrajectories(:,end)-2*jointTrajectories(:,end-1)]; % 5-point derivation weights = [1 -8 0 8 -1]; for frame = 3:mot.nframes+2 jointVelocities(:,frame-2) = ... weights(1) * jointTrajectories(:,frame-2) ... + weights(2) * jointTrajectories(:,frame-1) ... + weights(3) * jointTrajectories(:,frame) ... + weights(4) * jointTrajectories(:,frame+1) ... + weights(5) * jointTrajectories(:,frame+2); end jointVelocities = jointVelocities / (12 * mot.frameTime); % filtering velocities jointVelocities = filterTimeline(jointVelocities,filterSize,'bin'); end mot.jointVelocities = mat2cell(jointVelocities,3*ones(1,mot.njoints),mot.nframes);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
rotateMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/rotateMotion.m
1,232
utf_8
d412c25a6076da06f2bf3ca4ee7d6ab7
% function rotateMotion % rotates a motion with specified angle (in radians) around specified axis % mot = rotateMotion(skel,mot,angle,axis,varargin) % if varargin = false, jointTrajectories and boundingBox won't be computed % author: Jochen Tautges ([email protected]) function [mot,Q] = rotateMotion(skel,mot,angle,axis,varargin) computetrajsbb=true; if (nargin == 5) computetrajsbb=varargin{1}; end Q = rotquat(angle,axis); mot.rootTranslation = C_quatrot(mot.rootTranslation,Q); mot.rotationQuat{1} = C_quatmult(Q,mot.rotationQuat{1}); if (computetrajsbb) mot.jointTrajectories = C_forwardKinematicsQuat(skel,mot); mot.boundingBox = computeBoundingBox(mot); end if ~(isempty(mot.rotationEuler)) mot = convert2euler(skel,mot); % mot.rotationEuler{1} = flipud(quat2euler(mot.rotationQuat{1},'zyx'))*180/pi; end if (isfield(mot,'jointVelocities') && ~isempty(mot.jointVelocities) && mot.nframes>1) mot = addVelToMot(mot); end if (isfield(mot,'jointAccelerations') && ~isempty(mot.jointAccelerations) && mot.nframes>1) mot = addAccToMot(mot); end %fprintf('Motion successfully rotated with %.2f degrees around %c-axis.\n',angle*180/pi,axis);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
addBonesToMot.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/addBonesToMot.m
6,776
utf_8
31dba400ca97caa43ee8cd68534b3bb7
% mot = addBonesToMot(mot); % adds field "bones" to struct "mot" with the following columns: % - name: name of the bone (cf. struct "skel") % - bone vectors: father to son oriented vector for each frame % - bone length: length of the bone (cf. struct "skel") % - normalized bone vectors % - father and son joints related to the bone function mot=addBonesToMot(mot) % % 17 % | head % 16 % | upperneck % 15 % | lowerneck % lhand lradius lclavicle | rclavicle rradius rhand % lfingers 23-22-21-20-----19------18--14--25------26-----27-28-29-30 rfingers % lthumb | lwrist lhumerus | rhumerus rwrist | rthumb % 24 | thorax 31 % 13 % | upperback % | % 12 % | lowerback % | % lhip 2--1--7 rhip % / \ % / \ % lfemur / \ rfemur % / \ % / \ % 3 8 % | | % | | % ltibia | | rtibia % | | % 4 9 % / lfoot rfoot \ % ltoes 6--5 10-11 rtoes mot.bones.names{1,1} = 'lhip'; mot.bones.vectors{1,1} = mot.jointTrajectories{2}-mot.jointTrajectories{1}; mot.bones.joints{1,1} = [1,2]; mot.bones.names{2,1} = 'lfemur'; mot.bones.vectors{2,1} = mot.jointTrajectories{3}-mot.jointTrajectories{2}; mot.bones.joints{2,1} = [2,3]; mot.bones.names{3,1} = 'ltibia'; mot.bones.vectors{3,1} = mot.jointTrajectories{4}-mot.jointTrajectories{3}; mot.bones.joints{3,1} = [3,4]; mot.bones.names{4,1} = 'lfoot'; mot.bones.vectors{4,1} = mot.jointTrajectories{5}-mot.jointTrajectories{4}; mot.bones.joints{4,1} = [4,5]; mot.bones.names{5,1} = 'ltoes'; mot.bones.vectors{5,1} = mot.jointTrajectories{6}-mot.jointTrajectories{5}; mot.bones.joints{5,1} = [5,6]; mot.bones.names{6,1} = 'rhip'; mot.bones.vectors{6,1} = mot.jointTrajectories{7}-mot.jointTrajectories{1}; mot.bones.joints{6,1} = [1,7]; mot.bones.names{7,1} = 'rfemur'; mot.bones.vectors{7,1} = mot.jointTrajectories{8}-mot.jointTrajectories{7}; mot.bones.joints{7,1} = [7,8]; mot.bones.names{8,1} = 'rtibia'; mot.bones.vectors{8,1} = mot.jointTrajectories{9}-mot.jointTrajectories{8}; mot.bones.joints{8,1} = [8,9]; mot.bones.names{9,1} = 'rfoot'; mot.bones.vectors{9,1} = mot.jointTrajectories{10}-mot.jointTrajectories{9}; mot.bones.joints{9,1} = [9,10]; mot.bones.names{10,1} = 'rtoes'; mot.bones.vectors{10,1} = mot.jointTrajectories{11}-mot.jointTrajectories{10}; mot.bones.joints{10,1} = [10,11]; mot.bones.names{11,1} = 'lowerback'; mot.bones.vectors{11,1} = mot.jointTrajectories{12}-mot.jointTrajectories{1}; mot.bones.joints{11,1} = [1,12]; mot.bones.names{12,1} = 'upperback'; mot.bones.vectors{12,1} = mot.jointTrajectories{13}-mot.jointTrajectories{12}; mot.bones.joints{12,1} = [12,13]; mot.bones.names{13,1} = 'thorax'; mot.bones.vectors{13,1} = mot.jointTrajectories{14}-mot.jointTrajectories{13}; mot.bones.joints{13,1} = [13,14]; mot.bones.names{14,1} = 'lowerneck'; mot.bones.vectors{14,1} = mot.jointTrajectories{15}-mot.jointTrajectories{14}; mot.bones.joints{14,1} = [14,15]; mot.bones.names{15,1} = 'upperneck'; mot.bones.vectors{15,1} = mot.jointTrajectories{16}-mot.jointTrajectories{15}; mot.bones.joints{15,1} = [15,16]; mot.bones.names{16,1} = 'head'; mot.bones.vectors{16,1} = mot.jointTrajectories{17}-mot.jointTrajectories{16}; mot.bones.joints{16,1} = [16,17]; mot.bones.names{17,1} = 'lclavicle'; mot.bones.vectors{17,1} = mot.jointTrajectories{18}-mot.jointTrajectories{14}; mot.bones.joints{17,1} = [14,18]; mot.bones.names{18,1} = 'lhumerus'; mot.bones.vectors{18,1} = mot.jointTrajectories{19}-mot.jointTrajectories{18}; mot.bones.joints{18,1} = [18,19]; mot.bones.names{19,1} = 'lradius'; mot.bones.vectors{19,1} = mot.jointTrajectories{20}-mot.jointTrajectories{19}; mot.bones.joints{19,1} = [19,20]; mot.bones.names{20,1} = 'lwrist'; mot.bones.vectors{20,1} = mot.jointTrajectories{21}-mot.jointTrajectories{20}; mot.bones.joints{20,1} = [20,21]; mot.bones.names{21,1} = 'lhand'; mot.bones.vectors{21,1} = mot.jointTrajectories{22}-mot.jointTrajectories{21}; mot.bones.joints{21,1} = [21,22]; mot.bones.names{22,1} = 'lfingers'; mot.bones.vectors{22,1} = mot.jointTrajectories{23}-mot.jointTrajectories{22}; mot.bones.joints{22,1} = [22,23]; mot.bones.names{23,1} = 'lthumb'; mot.bones.vectors{23,1} = mot.jointTrajectories{24}-mot.jointTrajectories{21}; mot.bones.joints{23,1} = [21,24]; mot.bones.names{24,1} = 'rclavicle'; mot.bones.vectors{24,1} = mot.jointTrajectories{25}-mot.jointTrajectories{14}; mot.bones.joints{24,1} = [14,25]; mot.bones.names{25,1} = 'rhumerus'; mot.bones.vectors{25,1} = mot.jointTrajectories{26}-mot.jointTrajectories{25}; mot.bones.joints{25,1} = [25,26]; mot.bones.names{26,1} = 'rradius'; mot.bones.vectors{26,1} = mot.jointTrajectories{27}-mot.jointTrajectories{26}; mot.bones.joints{26,1} = [26,27]; mot.bones.names{27,1} = 'rwrist'; mot.bones.vectors{27,1} = mot.jointTrajectories{28}-mot.jointTrajectories{27}; mot.bones.joints{27,1} = [27,28]; mot.bones.names{28,1} = 'rhand'; mot.bones.vectors{28,1} = mot.jointTrajectories{29}-mot.jointTrajectories{28}; mot.bones.joints{28,1} = [28,29]; mot.bones.names{29,1} = 'rfingers'; mot.bones.vectors{29,1} = mot.jointTrajectories{30}-mot.jointTrajectories{29}; mot.bones.joints{29,1} = [29,30]; mot.bones.names{30,1} = 'rthumb'; mot.bones.vectors{30,1} = mot.jointTrajectories{31}-mot.jointTrajectories{28}; mot.bones.joints{30,1} = [28,31]; for i=1:30 mot.bones.length{i,1}=normOfColumns(mot.bones.vectors{i,1}(:,1)); end for i=1:30 mot.bones.normalizedVectors{i,1}=mot.bones.vectors{i,1}/mot.bones.length{i,1}; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
C_rotateMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/C_rotateMotion.m
1,344
utf_8
84fd698ee9ee92ec250403e41ed0aa23
% function C_rotateMotion % rotates a motion with specified angle (in radians) around specified axis % mot = rotateMotion(skel,mot,angle,axis,varargin) % if varargin = false, jointTrajectories and boundingBox won't be computed % author: Jochen Tautges ([email protected]), % some modifications by Tim Golla ([email protected]) function mot = C_rotateMotion(skel,mot,angle,axis,varargin) computetrajsbb=true; if (nargin == 5) computetrajsbb=varargin{1}; end Q = rotquat(angle,axis); for i=1:mot.nframes mot.rootTranslation(:,i) = C_quatrot(mot.rootTranslation(:,i),Q); mot.rotationQuat{1}(:,i) = C_quatmult(Q,mot.rotationQuat{1}(:,i)); end if (computetrajsbb) mot.jointTrajectories = C_forwardKinematicsQuat(skel,mot); mot.boundingBox = computeBoundingBox(mot); end if ~(isempty(mot.rotationEuler)) mot = C_convert2euler(skel,mot); % mot.rotationEuler{1} = flipud(quat2euler(mot.rotationQuat{1},'zyx'))*180/pi; end if (isfield(mot,'jointVelocities') && ~isempty(mot.jointVelocities) && mot.nframes>1) mot = addVelToMot(mot); end if (isfield(mot,'jointAccelerations') && ~isempty(mot.jointAccelerations) && mot.nframes>1) mot = addAccToMot(mot); end %fprintf('Motion successfully rotated with %.2f degrees around %c-axis.\n',angle*180/pi,axis);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
removeTranslation.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/removeTranslation.m
1,318
utf_8
be462a31fcc4d7cdadf1d40f9c721fd6
% function removeTranslation % removes the global translation (root translation) of a motion % mot = removeTranslation([skel,]mot) % if skel is specified function uses forward kinematics, otherwise simple % subtraction of root positions from all joint positions % author: Jochen Tautges ([email protected]) function mot = removeTranslation(varargin) switch nargin case 1 mot=varargin{1}; mot.jointTrajectories{1}(:,:) = 0; for i=2:mot.njoints mot.jointTrajectories{i} = mot.jointTrajectories{i}-mot.rootTranslation; end mot.rootTranslation = zeros(size(mot.rootTranslation)); case 2 if isfield(varargin{1},'jointTrajectories'); mot=varargin{1}; skel=varargin{2}; else skel=varargin{1}; mot=varargin{2}; end mot.rootTranslation = zeros(size(mot.rootTranslation)); mot.jointTrajectories = forwardKinematicsQuat(skel,mot); otherwise error('Wrong number of argins!'); end mot.boundingBox=computeBoundingBox(mot); if (isfield(mot,'jointVelocities')&&~isempty(mot.jointVelocities)) mot=addVelToMot(mot); end if (isfield(mot,'jointAccelerations')&&~isempty(mot.jointAccelerations)) mot=addAccToMot(mot); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
addAccToMot.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/motionTools/addAccToMot.m
1,726
utf_8
ae87460bf938a441c2cf7fd2ec602fd1
% function mot = addAccToMot(mot) % computes joint accelerations in each frame and adds the field % 'jointAccelerations' to mot structure % additionally filters the computed accelerations with binomial filter % author: Jochen Tautges ([email protected]) function mot = addAccToMot(mot,varargin) if nargin==2 filterSize = varargin{1}; else filterSize = min(floor(mot.samplingRate/10),floor(mot.nframes/2)); end if iscell(mot.jointTrajectories) jointTrajectories = cell2mat(mot.jointTrajectories); else jointTrajectories = mot.jointTrajectories; end jointAccelerations = zeros(size(jointTrajectories)); % padding jointTrajectories = [ 3*jointTrajectories(:,1)-2*jointTrajectories(:,2),... 2*jointTrajectories(:,1)-jointTrajectories(:,2),... jointTrajectories,... 2*jointTrajectories(:,end)-jointTrajectories(:,end-1),... 3*jointTrajectories(:,end)-2*jointTrajectories(:,end-1)]; % 5-point derivation weights = [-1 16 -30 16 -1]; for frame = 3:mot.nframes+2 jointAccelerations(:,frame-2) = ... weights(1) * jointTrajectories(:,frame-2) ... + weights(2) * jointTrajectories(:,frame-1) ... + weights(3) * jointTrajectories(:,frame) ... + weights(4) * jointTrajectories(:,frame+1) ... + weights(5) * jointTrajectories(:,frame+2); end jointAccelerations = jointAccelerations / (12 * mot.frameTime^2); % filtering accelerations jointAccelerations = filterTimeline(jointAccelerations,filterSize,'bin'); mot.jointAccelerations = mat2cell(jointAccelerations,3*ones(1,mot.njoints),mot.nframes);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
myaa.m
.m
3D_Pose_Estimation_CVPR2016-master/tools/plotTools/myaa.m
11,141
utf_8
a66dd7fc188c3f6a1a0a0c07623cf831
function [varargout] = myaa(varargin) %MYAA Render figure with anti-aliasing. % MYAA % Anti-aliased rendering of the current figure. This makes graphics look % a lot better than in a standard matlab figure, which is useful for % publishing results on the web or to better see the fine details in a % complex and cluttered plot. Some simple keyboard commands allow % the user to set the rendering quality interactively, zoom in/out and % re-render when needed. % % Usage: % myaa: Renders an anti-aliased version of the current figure. % % myaa(K): Sets the supersampling factor to K. Using a % higher K yields better rendering but takes longer time. If K is % omitted, it defaults to 4. It may be useful to run e.g. myaa(2) to % make a low-quality rendering as a first try, because it is a lot % faster than the default. % % myaa([K D]): Sets supersampling factor to K but downsamples the % image by a factor of D. If D is larger than K, the rendered image % will be smaller than the original. If D is smaller than K, the % rendering will be bigger. % % myaa('publish'): An experimental parameter, useful for publishing % matlab programs (see example 3). Beware, it kills the current figure. % % Interactivity: % The anti-aliased figure can be updated with the following keyboard % commands: % % <space> Re-render image (to reflect changes in the figure) % + Zoom in (decrease downsampling factor) % - Zoom out (increase downsampling factor) % 1 ... 9 Change supersampling and downsampling factor to ... % q Quit, i.e. close the anti-aliased figure % % Myaa can also be called with up to 3 parameters. % FIG = MYAA(K,AAMETHOD,FIGMODE) % Parameters and output: % K Subsampling factor. If a vector is specified, [K D], then % the second element will describe the downsampling factor. % Default is K = 4 and D = 4. % AAMETHOD Downsampling method. Normally this is chosen automatically. % 'standard': convolution based filtering and downsampling % 'imresize': downsampling using the imresize command from % the image toolbox. % 'noshrink': used internally % FIGMODE Display mode % 'figure': the normal mode, a new figure is created % 'update': internally used for interactive sessions % 'publish': used internally % FIG A handle to the new anti-aliased figure % % Example 1: % spharm2; % myaa; % % Press '1', '2' or '4' and try '+' and '-' % % Press 'r' or <space> to update the anti-aliased rendering, e.g. % % after rotating the 3-D object in the original figure. % % Example 2: % line(randn(2500,2)',randn(2500,2)','color','black','linewidth',0.01) % myaa(8); % % Example 3: % xpklein; % myaa(2,'standard'); % % Example 3: % Put the following in test.m % %% My test publish % % Testing to publish some anti-aliased images % % % spharm2; % Produce some nice graphics % myaa('publish'); % Render an anti-aliased version % % Then run: % publish test.m; % showdemo test; % % % BUGS: % Dotted and dashed lines in plots are not rendered correctly. This is % probably due to a bug in Matlab and it will hopefully be fixed in a % future version. % The OpenGL renderer does not always manage to render an image large % enough. Try the zbuffer renderer if you have problems or decrease the % K factor. You can set the current renderer to zbuffer by running e.g. % set(gcf,'renderer','zbuffer'). % % See also PUBLISH, PRINT % % Version 1.1, 2008-08-21 % Version 1.0, 2008-08-05 % % Author: Anders Brun % [email protected] % %% Force drawing of graphics drawnow; %% Find out about the current DPI... screen_DPI = get(0,'ScreenPixelsPerInch'); %% Determine the best choice of convolver. % If IPPL is available, imfilter is much faster. Otherwise it does not % matter too much. try if ippl() myconv = @imfilter; else myconv = @conv2; end catch myconv = @conv2; end %% Set default options and interpret arguments if isempty(varargin) self.K = [4 4]; try imfilter(zeros(2,2),zeros(2,2)); self.aamethod = 'imresize'; catch self.aamethod = 'standard'; end self.figmode = 'figure'; elseif strcmp(varargin{1},'publish') self.K = [4 4]; self.aamethod = 'noshrink'; self.figmode = 'publish'; elseif strcmp(varargin{1},'update') self = get(gcf,'UserData'); figure(self.source_fig); drawnow; self.figmode = 'update'; elseif strcmp(varargin{1},'lazyupdate') self = get(gcf,'UserData'); self.figmode = 'lazyupdate'; elseif length(varargin) == 1 self.K = varargin{1}; if length(self.K) == 1 self.K = [self.K self.K]; end if self.K(1) > 16 error('To avoid excessive use of memory, K has been limited to max 16. Change the code to fix this on your own risk.'); end try imfilter(zeros(2,2),zeros(2,2)); self.aamethod = 'imresize'; catch self.aamethod = 'standard'; end self.figmode = 'figure'; elseif length(varargin) == 2 self.K = varargin{1}; self.aamethod = varargin{2}; self.figmode = 'figure'; elseif length(varargin) == 3 self.K = varargin{1}; self.aamethod = varargin{2}; self.figmode = varargin{3}; if strcmp(self.figmode,'publish') && ~strcmp(varargin{2},'noshrink') printf('\nThe AAMETHOD was not set to ''noshrink'': Fixed.\n\n'); self.aamethod = 'noshrink'; end else error('Wrong syntax, run: help myaa'); end if length(self.K) == 1 self.K = [self.K self.K]; end %% Capture current figure in high resolution if ~strcmp(self.figmode,'lazyupdate'); tempfile = 'myaa_temp_screendump.png'; self.source_fig = gcf; current_paperpositionmode = get(self.source_fig,'PaperPositionMode'); current_inverthardcopy = get(self.source_fig,'InvertHardcopy'); set(self.source_fig,'PaperPositionMode','auto'); set(self.source_fig,'InvertHardcopy','off'); print(self.source_fig,['-r',num2str(screen_DPI*self.K(1))], '-dpng', tempfile); set(self.source_fig,'InvertHardcopy',current_inverthardcopy); set(self.source_fig,'PaperPositionMode',current_paperpositionmode); self.raw_hires = imread(tempfile); delete(tempfile); end %% Start filtering to remove aliasing w = warning; warning off; if strcmp(self.aamethod,'standard') || strcmp(self.aamethod,'noshrink') % Subsample hires figure image with standard anti-aliasing using a % butterworth filter kk = lpfilter(self.K(2)*3,self.K(2)*0.9,2); mm = myconv(ones(size(self.raw_hires(:,:,1))),kk,'same'); a1 = max(min(myconv(single(self.raw_hires(:,:,1))/(256),kk,'same'),1),0)./mm; a2 = max(min(myconv(single(self.raw_hires(:,:,2))/(256),kk,'same'),1),0)./mm; a3 = max(min(myconv(single(self.raw_hires(:,:,3))/(256),kk,'same'),1),0)./mm; if strcmp(self.aamethod,'standard') if abs(1-self.K(2)) > 0.001 raw_lowres = double(cat(3,a1(2:self.K(2):end,2:self.K(2):end),a2(2:self.K(2):end,2:self.K(2):end),a3(2:self.K(2):end,2:self.K(2):end))); else raw_lowres = self.raw_hires; end else raw_lowres = double(cat(3,a1,a2,a3)); end elseif strcmp(self.aamethod,'imresize') % This is probably the fastest method available at this moment... raw_lowres = single(imresize(self.raw_hires,1/self.K(2),'bilinear'))/256; end warning(w); %% Place the anti-aliased image in some image on the screen ... if strcmp(self.figmode,'figure'); % Create a new figure at the same place as the previous % The content of this new image is just a bitmap... oldpos = get(gcf,'Position'); self.myaa_figure = figure; fig = self.myaa_figure; set(fig,'Menubar','none'); set(fig,'Resize','off'); sz = size(raw_lowres); set(fig,'Units','pixels'); pos = [oldpos(1:2) sz(2:-1:1)]; set(fig,'Position',pos); ax = axes; image(raw_lowres); set(ax,'Units','pixels'); set(ax,'Position',[1 1 sz(2) sz(1)]); axis off; elseif strcmp(self.figmode,'publish'); % Create a new figure at the same place as the previous % The content of this new image is just a bitmap... self.myaa_figure = figure; fig = self.myaa_figure; current_units = get(self.source_fig,'Units'); set(self.source_fig,'Units','pixels'); pos = get(self.source_fig,'Position'); set(self.source_fig,'Units',current_units); set(fig,'Position',[pos(1) pos(2) pos(3) pos(4)]); ax = axes; image(raw_lowres); set(ax,'Units','normalized'); set(ax,'Position',[0 0 1 1]); axis off; close(self.source_fig); elseif strcmp(self.figmode,'update'); fig = self.myaa_figure; figure(fig); clf; set(fig,'Menubar','none'); set(fig,'Resize','off'); sz = size(raw_lowres); set(fig,'Units','pixels'); pos = get(fig,'Position'); pos(3:4) = sz(2:-1:1); set(fig,'Position',pos); ax = axes; image(raw_lowres); set(ax,'Units','pixels'); set(ax,'Position',[1 1 sz(2) sz(1)]); axis off; elseif strcmp(self.figmode,'lazyupdate'); clf; fig = self.myaa_figure; sz = size(raw_lowres); pos = get(fig,'Position'); pos(3:4) = sz(2:-1:1); set(fig,'Position',pos); ax = axes; image(raw_lowres); set(ax,'Units','pixels'); set(ax,'Position',[1 1 sz(2) sz(1)]); axis off; end %% Store current state set(gcf,'userdata',self); set(gcf,'KeyPressFcn',@keypress); set(gcf,'Interruptible','off'); %% Avoid unnecessary console output if nargout == 1 varargout(1) = {fig}; end %% A simple lowpass filter kernel (Butterworth). % sz is the size of the filter % subsmp is the downsampling factor to be used later % n is the degree of the butterworth filter function kk = lpfilter(sz, subsmp, n) sz = 2*floor(sz/2)+1; % make sure the size of the filter is odd cut_frequency = 0.5 / subsmp; range = (-(sz-1)/2:(sz-1)/2)/(sz-1); [ii,jj] = ndgrid(range,range); rr = sqrt(ii.^2+jj.^2); kk = ifftshift(1./(1+(rr./cut_frequency).^(2*n))); kk = fftshift(real(ifft2(kk))); kk = kk./sum(kk(:)); function keypress(src,evnt) if isempty(evnt.Character) return end recognized = 0; self = get(gcf,'userdata'); if evnt.Character == '+' self.K(2) = max(self.K(2).*0.5^(1/2),1); recognized = 1; set(gcf,'userdata',self); myaa('lazyupdate'); elseif evnt.Character == '-' self.K(2) = min(self.K(2).*2^(1/2),16); recognized = 1; set(gcf,'userdata',self); myaa('lazyupdate'); elseif evnt.Character == ' ' || evnt.Character == 'r' || evnt.Character == 'R' set(gcf,'userdata',self); myaa('update'); elseif evnt.Character == 'q' close(gcf); elseif find('123456789' == evnt.Character) self.K = [str2double(evnt.Character) str2double(evnt.Character)]; set(gcf,'userdata',self); myaa('update'); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
H_writeImageTest2.m
.m
3D_Pose_Estimation_CVPR2016-master/code/H_writeImageTest2.m
1,356
utf_8
900cb28147fd72b40923c1c56db8fdf0
function H_writeImageTest2(opts,inp2d,est2dRt,vFile,f,bodyType) ifr = opts.sFrame + f - 1; if(isobject(vFile)) rgbIm = read(vFile,ifr); else imn = [vFile opts.subject '_' opts.action '_' num2str(opts.frameNo(1,f)) '_' num2str(opts.frameNo(2,f)) '.png']; rgbIm = imread(imn); end clf imshow(rgbIm,'Border','tight'); %% xgt = inp2d(1:2:end,f); ygt = inp2d(2:2:end,f); xObj = est2dRt(1:2:end,f); % pose yObj = est2dRt(2:2:end,f); hold on %% H_drawLine(xgt,ygt); plot(xgt,ygt,'o','MarkerSize',6,'MarkerEdgeColor','r','MarkerFaceColor','y','LineWidth',2); %plot(xgt(13),ygt(13),'o','MarkerSize',6,'MarkerEdgeColor','r','MarkerFaceColor','r','LineWidth',2); plot(xObj,yObj,'*','MarkerSize',4,'MarkerEdgeColor','g'); xm = get(gca,'xLim'); ym = get(gca,'yLim'); text (xm(1) + 20,ym(1) + 20,['Frame # ' num2str(ifr)],'Color','y', 'FontWeight','bold', 'FontSize',15); %text (xm(1) + 20,ym(1) + 40,['Count # ' num2str(f)],'Color','y', 'FontWeight','bold', 'FontSize',15); pause(0.4); %% imPath = [opts.saveResPath 'optimTestIm\']; if ~exist(imPath,'dir') mkdir(imPath); end imName = [imPath opts.subject '_' opts.actName '_' num2str(opts.knn) '_' bodyType '_' num2str(ifr) '_' num2str(f) '.png']; frm = getframe(gcf); im = frame2im(frm); imwrite(im, imName); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
H_text2MotFile.m
.m
3D_Pose_Estimation_CVPR2016-master/code/H_text2MotFile.m
3,893
utf_8
0d21eef1f64aae54f67fb40229623cc7
function H_text2MotFile(dataName, strPath,dimInfo) motIn = emptyMotionLocal; strName = [strPath dataName]; fid = fopen(strName); cSpace = char('\n'); txtData = fscanf(fid, ['%f', cSpace]); token = textscan(dataName, '%s', 'delimiter', '_'); motIn.njoints = 14; frmInfo = 2; % video data and mocap data incr = motIn.njoints * dimInfo + frmInfo; if(mod(length(txtData),incr)) txtData(1) = []; end motIn.nframes = length(txtData)/incr; txtData = reshape(txtData, incr, length(txtData)/incr); i = 3; for k = 1:motIn.njoints motIn.jointTrajectories{k,1}(:,:) = txtData(i:i+2,:); i = i + 3; end %% % mot.jointNames = {'Right Ankle'; 'Right Knee'; 'Right Hip'; 'Left Hip'; 'Left Knee'; 'Left Ankle';... % 'Right Wrist'; 'Right Elbow'; 'Right Shoulder'; 'Left Shoulder';'Left Elbow';... % 'Left Wrist'; 'Neck'; 'Head'}; motIn.jointNames = {'Left Ankle'; 'Left Knee'; 'Left Hip'; 'Right Hip'; 'Right Knee'; 'Right Ankle';... 'Left Wrist'; 'Left Elbow'; 'Left Shoulder'; 'Right Shoulder';'Right Elbow';... 'Right Wrist'; 'Neck'; 'Head'}; motIn.markerNames = {'RTIO'; 'RFEO'; 'RFEP'; 'LFEP'; 'LFEO'; 'LTIO'; 'RRAO'; 'RHUO'; ... 'RCLO'; 'LCLO'; 'LHUO'; 'LRAO'; 'TRXO'; 'LFHD'; 'RFHD'}; motIn.samplingRate = 120; motIn.frameTime = 1/motIn.samplingRate; motIn.subject = token{1,1}{1,1}; motIn.action = token{1,1}{2,1}; motIn.trail = token{1,1}{3,1}; motIn.camera = strtok(token{1,1}{4,1}, '.'); motIn.filename = dataName; motIn.frameNumbers(1,:) = txtData(1,:); motIn.frameNumbers(2,:) = txtData(2,:); motIn.vidStartFrame = txtData(1); motIn.vidEndFrame = txtData(1,motIn.nframes); motIn.mocStartFrame = txtData(2); motIn.mocEndFrame = txtData(2,motIn.nframes); if(motIn.vidStartFrame == motIn.vidEndFrame) motIn.vidEndFrame = motIn.vidStartFrame + motIn.nframes - 1; end if (dimInfo == 2) motIn.dimData = '2D'; else motIn.dimData = '3D'; end motIn.boundingBox = computeBoundingBox(motIn); for i = 1:length(motIn.markerNames) motIn.nameMap{i,1} = char(motIn.markerNames(i)); motIn.nameMap{i,2} = 0; motIn.nameMap{i,3} = i; end %% filp the left side towards right side % qy = rotquat(180,'y'); % for m = 1:mot.njoints % mot.jointTrajectories{m}(:,:) = quatrot(mot.jointTrajectories{m}(:,:),qy); % end %% strRes = strtok(dataName, '.'); save(fullfile(strPath,[strRes '.mat']),'motIn','-v7.3'); end function mot = emptyMotionLocal %% mot = struct('name','pgIlya',... 'njoints',0,... % number of joints 'nframes',0,... % number of frames 'frameTime',nan,... % inverse sampling rate: time per frame (in seconds) 'samplingRate',nan,... % sampling rate (in Hertz) (120 Hertz is Carnegie-Mellon Mocap-DB standard) 'jointTrajectories',cell(1,1),... % 3D joint trajectories 'rootTranslation',[],... % global translation data stream of the root 'rotationEuler',cell(1,1),... % rotational data streams for all joints, including absolute root rotation at pos. 1, Euler angles 'rotationQuat',cell(1,1),... % rotational data streams for all joints, including absolute root rotation at pos. 1, quaternions 'jointNames',cell(1,1),... % cell array of joint names: maps node ID to joint name 'markerNames',cell(1,1),... % cell array of marker names: 'boundingBox',[],... % bounding box (given a specific skeleton) 'filename',''); % source filename end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
optimCamMtxPerspSepWinH30Mbm.m
.m
3D_Pose_Estimation_CVPR2016-master/code/optimCamMtxPerspSepWinH30Mbm.m
5,937
utf_8
71e484e9935760067294b595c9b74540
function [est2dRt, est3dRt, X] = optimCamMtxPerspSepWinH30Mbm(inp2d,knn3d,cm,opts, singleDim, varargin) if(nargin > 5) vFile = varargin{1}; end if (exist('vFile','var')) if(~isobject(vFile)) vFilePath = vFile; end testIm = 1; dirFiles = dir([vFile '*.png']); drnm = char(dirFiles.name); % orginizing order drnmCell = cellstr(drnm); drnmCell = sort_nat(drnmCell); else testIm = 0; end windowsize = 2; % for 5 we have to select 4 optimOpts = optimset(... 'Display','off',... % 'Display','iter' 'MaxIter',10000,... 'MaxFunEvals',10000,... % 'PlotFcns', @optimplotx, ... 'Algorithm' ,'trust-region-reflective',... %'levenberg-marquardt' , ... 'TolX',0.001); lb = []; ub = []; %% Loading Camera matx already optimized and save previously pload = '../Datatest/'; camLoad = [pload opts.subject '_' opts.actName '_' num2str(opts.knn) '_pose_camMtxdfgff.mat']; if(exist(camLoad,'file')) load(camLoad); end if(exist('camMtx','var')) camMtxLoad = true; else camMtxLoad = false; startValue = [0;0;0;0;0;0]; end %% %--------------------------------------------------------------------------%Loading cam mtx given cam = 2; % cam = 1 optimal Sequence = H36MSequence(11, 1, 1, cam, 1); obj = Sequence.getCamera(); cm.R = obj.R; cm.T = obj.T; cm = obj; %% nJoints = length(opts.allJoints); knn3dv = knn3d(opts.cJidx3,:,:); inp2dv = inp2d(opts.cJidx2,:); X = cell(size(inp2d,2),1); rn = nan(size(inp2d,2),1); % X2 = cell(size(inp2d,2),1); % rn2 = nan(size(inp2d,2),1); act = 1; if((ndims(knn3d)==3) || (singleDim == 1)) %% all knn simultaneously est2dRt = nan(2*nJoints*opts.knn,size(inp2d,2)); est3dRt = nan(3*nJoints*opts.knn,size(inp2d,2)); fprintf('Optimization: Frame no. ... '); count = 1; tic rot = true; for f = 1:size(inp2d,2) fprintf('%5d ', f); %------------------------------------------------------------------% all 14 joints est3d = H_regularize(knn3d,f); %------------------------------------------------------------------% optimize with selective joints (opts.cJoints) est3dv = H_regularize(knn3dv,f); inp2dRev = reshape(inp2dv(:,f),2,[]); inp2dRev = repmat(inp2dRev,1,size(knn3d,2)); %------------------------------------------------------------------% optimize and getting R,t parameters %startValue0 = [0;0;0;0;0;0]; if(camMtxLoad) startValue = camMtx{f}; end % % % if(act<opts.act(f)) % % % startValue = [0;0;0;0;0;0]; % % % end [X{count,1},rn(count,1)] = lsqnonlin(@(x) objfunLocal(x,inp2dRev,est3dv,cm),startValue,lb,ub,optimOpts); %startValue = X{count,1}; % % % if(startValue ~= [0;0;0;0;0;0]) % % % if(rn(count,1) > 9.0e5) % % % startValue = [0;0;0;0;0;0]; % % % [x2,rnn2] = lsqnonlin(@(x) objfunLocal(x,inp2dRev,est3dv,cm),startValue,lb,ub,optimOpts); % % % if(rn(count,1) > rnn2) % % % X{count,1} = x2; % % % rn(count,1)= rnn2; % % % end % % % end % % % end % % % startValue = X{count,1}; % if(camMtxLoad) % startValue = camMtx{f}; % [X2{count,1},rn2(count,1)] = lsqnonlin(@(x) objfunLocal(x,inp2dRev,est3dv,cm),startValue,lb,ub,optimOpts); % end % if(rn2(count,1) < rn(count,1)) % Xm = X2{count,1}; % else % Xm = X{count,1}; % end Xm = X{count,1}; %------------------------------------------------------------------ [est2d,j3d] = H_proj(Xm,est3d,cm); tm2d = reshape(est2d,2*nJoints,[]); est2dRt(:,f) = tm2d(:); %est3d(1,:) = -est3d(1,:); j3d([2 3],:) = flipud(j3d([2 3],:)); tm3d = reshape(j3d,3*nJoints,[]); est3dRt(:,f) = tm3d(:); camMtx{count,1} = Xm; fprintf('\b\b\b\b\b\b'); %% if(testIm) bodyType = opts.bodyType; if(~isobject(vFile)) vFile = [vFilePath drnmCell{f}]; end H_writeImageTest(opts,inp2d(:,f),est2dRt(:,f),vFile,f,bodyType) end %% count = count + 1; %act = opts.act(f); end toc end camName = [opts.subject '_' opts.actName '_' num2str(opts.knn) '_' opts.bodyType '_camMtx.mat']; save(fullfile(opts.saveResPath,camName),'camMtx','-v7.3'); end function f = objfunLocal(x,in2d,est3d,cm) [est2d,~] = H_proj(x,est3d,cm); f = sqrt(sum((est2d - in2d).^2)); %f = norm(est2d - in2d,1); % f = repmat(sum(sqrt(sqrt(sum((est2d - in2d).^2)))),size(x)); end function [est2d,j3d] = H_proj(x,est3d,cm) R = makehgtform('xrotate',deg2rad(x(1)),'yrotate',deg2rad(x(2)),'zrotate',deg2rad(x(3))); R = R(1:3,1:3); T = [x(4); x(5); x(6)]; R = [R T]; j3d = R*est3d; % T = T'; % j3d = est3d(1:3,:); [est2d, ~] = ProjectPointRadial(j3d', cm.R, cm.T, cm.f, cm.c, cm.k, cm.p); est2d = est2d'; end function est3d = H_rotFlip(est3d,rot) if(rot) %R = makehgtform('xrotate',H_deg2rad(180)); R = makehgtform('xrotate',deg2rad(90)); est3d = R * est3d; end end function est3d = H_regularize(knn3d,f) %% est3d = knn3d(:,:,f); est3d = squeeze(est3d); est3d = reshape(est3d,3,[]); est3d([2 3],:) = flipud(est3d([2 3],:)); % est3d(2,:) = -est3d(2,:); est3d(1,:) = -est3d(1,:); % used for h36m est3d(4,:) = 1; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
optimCamMtxPerspSepWin.m
.m
3D_Pose_Estimation_CVPR2016-master/code/optimCamMtxPerspSepWin.m
6,857
utf_8
9f8e6572075ba03fd71b8a7a17dcc258
function [est2dRt, est3dRt, X] = optimCamMtxPerspSepWin(inp2d,knn3d,cm,opts,varargin) %% Hashim Yasin strtOp = 1; windowsize = 4; % for 5 we have to select 4 if(nargin > 4) vFile = varargin{1}; end if (exist('vFile','var')) testIm = 1; else testIm = 0; end optimOpts = optimset(... 'Display','off',... % 'Display','iter' 'MaxIter',10000,... 'MaxFunEvals',10000,... % 'PlotFcns', @optimplotx, ... 'Algorithm' , 'trust-region-reflective' , ...%'trust-region-reflective',... %'levenberg-marquardt' , ... 'TolX',0.001); startValue = [0;0;0;0;0;0]; lb = []; ub = []; nJoints = length(opts.allJoints); knn3dv = knn3d(opts.cJidx3,:,:); inp2dv = inp2d(opts.cJidx2,:); % idx2 = H_getSingleJntIdx({'Head';'Left Shoulder'; 'Right Shoulder'; 'Left Hip'; 'Right Hip'; 'Neck'},2,opts.allJoints); % idx3 = H_getSingleJntIdx({'Head';'Left Shoulder'; 'Right Shoulder'; 'Left Hip'; 'Right Hip'; 'Neck'},3,opts.allJoints); % knn3dv = knn3d(idx3,:,:); % inp2dv = inp2d(idx2,:); cnt = 0; if(ndims(knn3d)==3) %% all knn simultaneously %---------------------------------------------------------------------- starting options if(strtOp) fprintf('Initialization Step: ... '); c = 1; for s = 1:10 optimOpts2 = optimset(... 'Display','off',... % 'Display','iter' 'MaxIter',10000,... 'MaxFunEvals',10000,... % 'PlotFcns', @optimplotx, ... 'Algorithm' , 'levenberg-marquardt' , ...%'trust-region-reflective',... %'levenberg-marquardt' , ... 'TolX',0.001); lb2 = [0,0,0,-10000,-10000,-10000]; ub2 = [360,360,360,10000,10000,10000]; est3dv = H_regularize(knn3d,s); inp2dRev = reshape(inp2d(:,s),2,[]); inp2dRev = repmat(inp2dRev,1,size(knn3d,2)); [Xt{c,1},rnt(c,1)] = lsqnonlin(@(x) objfunLocal(x,inp2dRev,est3dv,cm),startValue,lb2,ub2,optimOpts2); startValue = Xt{c,1}; c = c + 1; end [~,ind] = min(rnt(:)); startValue = Xt{ind,1}; end %---------------------------------------------------------------------- est2dRt = nan(2*nJoints*opts.knn,size(inp2d,2)); est3dRt = nan(3*nJoints*opts.knn,size(inp2d,2)); fprintf('Optimization: Frame no. ... '); tic for f = 1:size(inp2d,2) fprintf('%3d ', f); %------------------------------------------------------------------% all 14 joints est3d = H_regularize(knn3d,f); % inp2dRe = reshape(inp2d(:,f),2,[]);, % inp2dRe = repmat(inp2dRe,1,size(knn3d,2)); %------------------------------------------------------------------% optimize with selective joints (opts.cJoints) est3dv = H_regularize(knn3dv,f); inp2dRev = reshape(inp2dv(:,f),2,[]); inp2dRev = repmat(inp2dRev,1,size(knn3d,2)); %------------------------------------------------------------------% optimize and getting R,t parameters [X{f,1},rn(f,1)] = lsqnonlin(@(x) objfunLocal(x,inp2dRev,est3dv,cm),startValue,lb,ub,optimOpts); %------------------------------------------------------------------% starting options if(f == 1) rnFr = 0; while(rn>3e+05) [X{f,1},rn(f,1)] = lsqnonlin(@(x) objfunLocal(x,inp2dRev,est3dv,cm),X{f,1},lb,ub,optimOpts); if (rnFr == rn) break; end rnFr = rn; cnt = cnt + 1; end end %------------------------------------------------------------------ %R = makehgtform('xrotate',X{f,1}(1),'yrotate',X{f,1}(2),'zrotate',X{f,1}(3)); R = makehgtform('xrotate',deg2rad(X{f,1}(1)),'yrotate',deg2rad(X{f,1}(2)),'zrotate',deg2rad(X{f,1}(3))); R = R(1:3,1:3); T = [X{f,1}(4); X{f,1}(5); X{f,1}(6)]; R = [R T]; camMtx{f,1} = R; %------------------------------------------------------------------% getting 2D data j3d = R*est3d; est2d = project_points2Short(j3d,cm.omc_ext,cm.Tc_ext,cm.fc,cm.cc,cm.kc,cm.alpha_c); tm2d = reshape(est2d,2*nJoints,[]); est2dRt(:,f) = tm2d(:); %------------------------------------------------------------------% getting 3D data j3d([2 3],:) = flipud(j3d([2 3],:)); % '123' ---> '132' here back fliping is done in opposite direction j3d([1 3],:) = flipud(j3d([1 3],:)); % '321' ---> '123' tm3d = reshape(j3d,3*nJoints,[]); est3dRt(:,f) = tm3d(:); %------------------------------------------------------------------% startValue with window size 5 sf = max(1,f-windowsize); [~,ind] = min(rn(sf:f)); ind = ind + sf - 1; startValue = X{ind,1}; fprintf('\b\b\b\b'); %% if(testIm) %%% H_writeImageTest2(opts,inp2d,est2dRt,vFile,f,bodyType) end %% est3d = []; est3dv = []; end end toc orName = [opts.subject '_' opts.actName '_' num2str(opts.knn) '_' opts.bodyType '_rn.mat']; save(fullfile(opts.saveResPath,orName),'rn','-v7.3'); rtName = [opts.subject '_' opts.actName '_' num2str(opts.knn) '_' opts.bodyType '_rtMtx.mat']; save(fullfile(opts.saveResPath,rtName),'X','-v7.3'); camName = [opts.subject '_' opts.actName '_' num2str(opts.knn) '_' opts.bodyType '_camMtxComb.mat']; save(fullfile(opts.saveResPath,camName),'camMtx','-v7.3'); end function f = objfunLocal(x,in2d,est3d,cm) %R = makehgtform('xrotate',x(1),'yrotate',x(2),'zrotate',x(3)); R = makehgtform('xrotate',deg2rad(x(1)),'yrotate',deg2rad(x(2)),'zrotate',deg2rad(x(3))); R = R(1:3,1:3); T = [x(4); x(5); x(6)]; R = [R T]; j3d = R*est3d; %%est2d = project_points2(j3d,cm.omc_ext,cm.Tc_ext,cm.fc,cm.cc,zeros(5,1),0); %%est2d = project_points2Short(j3d,cm.omc_ext,cm.Tc_ext,cm.fc,cm.cc,cm.kc,cm.alpha_c); est2d = project_points2ShortOptim(j3d,cm.omc_ext,cm.Tc_ext,cm.fc,cm.cc); % f = sqrt(sum((est2d - in2d).^2)); % f = repmat(sum(sqrt(sqrt(sum((est2d - in2d).^2)))),size(x)); end function est3d = H_regularize(knn3d,f) %% est3d = knn3d(:,:,f); est3d = squeeze(est3d); est3d = reshape(est3d,3,[]); est3d ([1 3],:) = flipud(est3d([1 3],:)); % '321' ---> '123' est3d ([2 3],:) = flipud(est3d([2 3],:)); % '123' ---> '132' est3d(4,:) = 1; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
errorHumanEva.m
.m
3D_Pose_Estimation_CVPR2016-master/code/errorHumanEva.m
3,107
utf_8
274fbb095679590e793911c138288956
function [errPrJnts, errPrFr, errPrAllFr] = errorHumanEva(data,mocapGT,cJoints) % data = data(1:3*length(cJoints),:); % mocapGT = mocapGT(1:3*length(cJoints),:); errPrFr = nan(size(data,2),1); % error nrOfFrames errPrJnts = nan(size(data,1)/3,1,size(data,2)); % error joints*knn*nrOfFrames for f = 1:size(data,2) % frames errPrJntsTmp = nan(size(data,1)/3,1); i = 1; for j = 1:size(data,1)/3 % joints errPrJntsTmp(j) = error_internal(data(i:i+2,f),mocapGT(i:i+2,f)); i = i + 3; end errPrJnts(:,1,f) = errPrJntsTmp; errPrFr(f) = mean(errPrJntsTmp); end errPrAllFr = mean(errPrFr); end function [err] = error_internal(point1, point2) err = sqrt(sum((point1(:) - point2(:)).^2)); end %% % % % % Thorax joint % % % e1 = error_internal(pose1.torsoProximal, pose2.torsoProximal); % % % e2 = error_internal(pose1.headProximal, pose2.headProximal); % % % if (any([e1, e2])) % % % err(end+1) = mean([e1, e2]); % % % end % % % % Pelvis joint % % % err(end+1) = error_internal(pose1.torsoDistal, pose2.torsoDistal); % % % % Left shoulder % % % err(end+1) = error_internal(pose1.upperLArmProximal, pose2.upperLArmProximal); % % % % Left elbow % % % e1 = error_internal(pose1.upperLArmDistal, pose2.upperLArmDistal); % % % e2 = error_internal(pose1.lowerLArmProximal, pose2.lowerLArmProximal); % % % if (any([e1, e2])) % % % err(end+1) = mean([e1, e2]); % % % end % % % % Left wrist % % % err(end+1) = error_internal(pose1.lowerLArmDistal, pose2.lowerLArmDistal); % % % % Right shoulder % % % err(end+1) = error_internal(pose1.upperRArmProximal, pose2.upperRArmProximal); % % % % Right elbow % % % e1 = error_internal(pose1.upperRArmDistal, pose2.upperRArmDistal); % % % e2 = error_internal(pose1.lowerRArmProximal, pose2.lowerRArmProximal); % % % if (any([e1, e2])) % % % err(end+1) = mean([e1, e2]); % % % end % % % % Right wrist % % % err(end+1) = error_internal(pose1.lowerRArmDistal, pose2.lowerRArmDistal); % % % % Left hip % % % err(end+1) = error_internal(pose1.upperLLegProximal, pose2.upperLLegProximal); % % % % Left knee % % % e1 = error_internal(pose1.upperLLegDistal, pose2.upperLLegDistal); % % % e2 = error_internal(pose1.lowerLLegProximal, pose2.lowerLLegProximal); % % % if (any([e1, e2])) % % % err(end+1) = mean([e1, e2]); % % % end % % % % Left ankle % % % err(end+1) = error_internal(pose1.lowerLLegDistal, pose2.lowerLLegDistal); % % % % Right hip % % % err(end+1) = error_internal(pose1.upperRLegProximal, pose2.upperRLegProximal); % % % % Right knee % % % e1 = error_internal(pose1.upperRLegDistal, pose2.upperRLegDistal); % % % e2 = error_internal(pose1.lowerRLegProximal, pose2.lowerRLegProximal); % % % if (any([e1, e2])) % % % err(end+1) = mean([e1, e2]); % % % end % % % % Right ankle % % % err(end+1) = error_internal(pose1.lowerRLegDistal, pose2.lowerRLegDistal); % % % % Head (top of the head) % % % err(end+1) = error_internal(pose1.headDistal, pose2.headDistal); % % % err = mean(err);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
emptyMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/code/emptyMotion.m
6,889
utf_8
6ecb50721bd9279da049272df1df4952
function mot = emptyMotion(varargin) switch nargin case 0 mot = struct('njoints',0,... % number of joints 'nframes',0,... % number of frames 'frameTime',nan,... % inverse sampling rate: time per frame (in seconds) 'samplingRate',nan,... % sampling rate (in Hertz) (120 Hertz is Carnegie-Mellon Mocap-DB standard) 'jointTrajectories',cell(1,1),... % 3D joint trajectories 'jointTrajectoriesN',cell(1,1),... % 3D joint trajectories (Normalized) 'jointTrajectories2D',cell(1,1),... % 2D joint trajectories 'rootTranslation',[],... % global translation data stream of the root 'rotationEuler',cell(1,1),... % rotational data streams for all joints, including absolute root rotation at pos. 1, Euler angles 'rotationQuat',cell(1,1),... % rotational data streams for all joints, including absolute root rotation at pos. 1, quaternions 'jointNames',cell(1,1),... % cell array of joint names: maps node ID to joint name 'boneNames',cell(1,1),... % cell array of bone names: maps bone ID to node name. ID 1 is the root. 'nameMap',cell(1,1),... % cell array mapping standard joint names to DOF IDs and trajectory IDs 'animated',[],... % vector of IDs for animated joints/bones 'unanimated',[],... % vector of IDs for unanimated joints/bones 'boundingBox',[],... % bounding box (given a specific skeleton) 'filename','',... % source filename 'documentation','',... % documentation from source file 'angleUnit','deg'); % angle unit, either deg or rad case 1 if ismot_local(varargin{1}) refmot = varargin{1}; mot = struct('njoints',refmot.njoints,... % number of joints 'nframes',0,... % number of frames 'frameTime',refmot.frameTime,... % inverse sampling rate: time per frame (in seconds) 'samplingRate',refmot.samplingRate,... % sampling rate (in Hertz) (120 Hertz is Carnegie-Mellon Mocap-DB standard) 'jointTrajectories',[],...cell(refmot.njoints,1),...% 3D joint trajectories 'rootTranslation',[],... % global translation data stream of the root 'rotationEuler',[],...{cell(refmot.njoints,1)},...% rotational data streams for all joints, including absolute root rotation at pos. 1, Euler angles 'rotationQuat',[],...{cell(refmot.njoints,1)},...% rotational data streams for all joints, including absolute root rotation at pos. 1, quaternions 'jointNames',{refmot.jointNames},... % cell array of joint names: maps node ID to joint name 'boneNames',{refmot.boneNames},... % cell array of bone names: maps bone ID to node name. ID 1 is the root. 'nameMap',{refmot.nameMap},... % cell array mapping standard joint names to DOF IDs and trajectory IDs 'animated',refmot.animated,... % vector of IDs for animated joints/bones 'unanimated',refmot.unanimated,... % vector of IDs for unanimated joints/bones 'boundingBox',[],... % bounding box (given a specific skeleton) 'filename','',... % source filename 'documentation','',... % documentation from source file 'angleUnit','deg'); % angle unit, either deg or rad elseif isskel_local(varargin{1}) skel = varargin{1}; mot = struct('njoints',skel.njoints,... % number of joints 'nframes',0,... % number of frames 'frameTime',nan,... % inverse sampling rate: time per frame (in seconds) 'samplingRate',nan,... % sampling rate (in Hertz) (120 Hertz is Carnegie-Mellon Mocap-DB standard) 'jointTrajectories',[],...{cell(skel.njoints,1)},...% 3D joint trajectories 'rootTranslation',[],... % global translation data stream of the root 'rotationEuler',[],...{cell(skel.njoints,1)},... % rotational data streams for all joints, including absolute root rotation at pos. 1, Euler angles 'rotationQuat',[],...{cell(skel.njoints,1)},... % rotational data streams for all joints, including absolute root rotation at pos. 1, quaternions 'jointNames',{skel.jointNames},... % cell array of joint names: maps node ID to joint name 'boneNames',{skel.boneNames},... % cell array of bone names: maps bone ID to node name. ID 1 is the root. 'nameMap',{skel.nameMap},... % cell array mapping standard joint names to DOF IDs and trajectory IDs 'animated',skel.animated,... % vector of IDs for animated joints/bones 'unanimated',skel.unanimated,... % vector of IDs for unanimated joints/bones 'boundingBox',[],... % bounding box (given a specific skeleton) 'filename','',... % source filename 'documentation','',... % documentation from source file 'angleUnit','deg'); % angle unit, either deg or rad end end end %% local functions function ismot_bool = ismot_local(arg) if isfield(arg,'nframes') && isfield(arg,'rotationQuat') ismot_bool = true; else ismot_bool = false; end end function isskel_bool = isskel_local(arg) if isfield(arg,'njoints') && isfield(arg,'nodes') isskel_bool = true; else isskel_bool = false; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
recOnWeightedKernel.m
.m
3D_Pose_Estimation_CVPR2016-master/code/recOnWeightedKernel.m
12,345
utf_8
e93849a49bae2f70b66d852857515f10
function [er, optim, opts] = recOnWeightedKernel(varargin) tic %% options updates close all; if(nargin == 0) [opts, ~] = initializeOpts; elseif(nargin == 1) [opts, ~] = initializeOpts(varargin{1}); elseif(nargin == 2) [opts, ~] = initializeOpts(varargin{1},varargin{2}); elseif(nargin == 3) [opts, ~] = initializeOpts(varargin{1},varargin{2},varargin{3}); elseif(nargin == 4) [opts, ~] = initializeOpts(varargin{1},varargin{2},varargin{3},varargin{4}); elseif(nargin == 5) [opts, ~] = initializeOpts(varargin{1},varargin{2},varargin{3},varargin{4},varargin{5}); else disp('error: wrong number of input arguments'); end %% Options to select opts.round = 1; opts.database = 'CMU_amc_regFit'; opts.loadPath = fullfile('../Data/'); opts.loadInPath = fullfile('../Data/'); opts.saveResPath = fullfile('../Data/'); if ~exist(opts.saveResPath,'dir') mkdir(opts.saveResPath); end %% Loading input anf GT [motIn,~, opts] = loadnPrepareQMot(opts); load(fullfile([opts.loadPath 'motGT_' opts.subject '_' opts.actName ])); %gt estP2D = cell2mat(motIn.jointTrajectories2DF); [cm.fc, cm.cc, cm.alpha_c, cm.kc, cm.Rc_ext, cm.omc_ext, cm.Tc_ext] = readSpicaCalib(opts.pathCalFile); %% Loading nn %shape = {'upper';'lower';'left';'right';'pose'}; try shape = motIn.bodyTypeOrder; catch disp('Please load right input'); end for h = 1:length(shape) loadPath = opts.loadPath; idName = [opts.subject '_' opts.actName '_' num2str(opts.knn) '_' shape{h} '_obj.mat']; load([loadPath idName]); objAll{h,1}.obj = obj; objAll{h,1}.knn = opts.knn; objAll{h,1}.knnJoints = opts.allJoints; objAll{h,1}.bodyType = shape{h}; idNameCM = [opts.subject '_' opts.actName '_' num2str(opts.knn) '_' shape{h} '_camMtx.mat']; fileCM = [loadPath idNameCM]; load(fileCM); camMtxAll{h,1} = camMtx; loadPath = opts.loadPath; opts.cJno = getShapeJointNum(shape{h},opts.inputDB); [opts.allJoints, opts.cJoints] = getJointsHE (opts.inputDB,opts.database,opts.cJno,shape{h}); opts = getJointsIdx(opts); jnts.cJidx{h,1} = opts.cJidx; jnts.cJidx2{h,1} = opts.cJidx2; jnts.cJidx3{h,1} = opts.cJidx3; end %% reconstruction options erJoints = 14; selknn = 256; nknn = 64; % 64 optim.nknn = nknn; optim.nrOfSVPosePriorP = 18; %18 % 25 %30 optim.nrOfPrinComps = 18; %18 % 25 %30 optim.w_pose = .35; %20 .60 optim.w_control = .55; %10 .45 optim.w_pose2D = .25; %10 0 optim.w_limb = .065; %10 .05 fprintf('%3d ', optim.w_pose ); fprintf('%3d ', optim.w_control); fprintf('%3d ', optim.w_pose2D ); fprintf('%3d ', optim.w_limb ); disp(' . . . done'); optim.expPPrior = 0.5; optim.expMPrior = 0.5; optim.expSmooth = 0.5; optim.expControl = 0.5; optim.jointWeights = 1; optim.jointWeights2D = 1; % optim.jointWeights = ones(3*length(opts.allJoints),selknn); % optim.jointWeights2D = ones(2*length(opts.allJoints),selknn); optLSQ = optimset( 'Display','none',... %'iter', 'MaxFunEvals',100000,... 'MaxIter',1000,... 'TolFun',0.001,... 'TolX',0.001,... 'LargeScale','on',... 'Algorithm','levenberg-marquardt'); lb = []; ub = []; %-------------------------------------------------------------------------- lbb = -0.5; ubb = 1.5; startValueMtx = [0;0;0;0;0;0]; windowsize = 4; % for 5 we have to select 4 optimOpts = optimset(... 'Display','off',... % 'Display','iter' 'MaxIter',10000,... 'MaxFunEvals',10000,... % 'PlotFcns', @optimplotx, ... 'Algorithm' , 'trust-region-reflective' , ...%'trust-region-reflective',... %'levenberg-marquardt' , ... 'TolX',0.001); %% Reconstruction optim.limlenIdx = H_calLimbLengthIdx(opts.allJoints); sknnObj = obj; obj.data = []; sknnObj.knn = nknn; sknnObj.data = nan(nknn*3*motIn.njoints, motIn.nframes); toc tic fprintf('Reconstruction: Frame no. ... '); for f = 1:motIn.nframes fprintf('%3d ', f); sObj = objAll{motIn.bodyType(f),1}; sknn = sObj.obj.data(:,f); sknn = reshape(sknn,3*length(opts.allJoints),[]); sknn = sknn(:,1:selknn); for j = 1:length(optim.limlenIdx) optim.limlen(j,:) = sqrt(sum((sknn(optim.limlenIdx(j,1:3),:) - sknn(optim.limlenIdx(j,4:6),:)).^2)); %optim.limlen(j,:) = sum(sqrt((sknn(optim.limlenIdx(j,1:3),:) - sknn(optim.limlenIdx(j,4:6),:)).^2)); end %====================================================================== weights regularization w = motIn.knnWts(1:selknn,f)'; ind = find(w>1); w(ind) = 0; w = regulateWeights(w); [~, wtidx] = sort(w,'descend'); w = w(wtidx(1:nknn)); sw = sum(w); optim.limlen = optim.limlen(:,wtidx(1:nknn)); sknn = sknn(:,wtidx(1:nknn)); sknnObj.data(:,f) = sknn(:); %====================================================================== opts.bodyType = sObj.bodyType; opts.cJno = getShapeJointNum(opts.bodyType,opts.inputDB); [opts.allJoints, opts.cJoints] = getJointsHE (opts.inputDB,opts.database,opts.cJno,opts.bodyType); opts = getJointsIdx(opts); optim.estP2D = estP2D(:,f); optim.camMtx = cell2mat(camMtxAll{motIn.bodyType(f),1}(f,1)); optim.cJidx2 = opts.cJidx2; optim.wtPose = w; %====================================================================== % knn repeats according to the weights for weighted pca wlm = ceil(w*10); for k = 1:length(wlm) nn = repmat(sknn(:,k),1,wlm(k)); nn2d = repmat(sknn(:,k),1,wlm(k)); wt = repmat(w(k),1,wlm(k)); if (k == 1) nnrep = nn; nnrep2d = nn2d; wrep = wt; else nnrep = [nnrep,nn]; nnrep2d = [nnrep2d,nn2d]; wrep = [wrep,wt]; end end optim.wtPoserep = wrep; optim.localModelPosePrior_Pos = nnrep'; %sknn'; [optim.coeffs_Pos,score_Pos] = princomp2(optim.localModelPosePrior_Pos); optim.meanVec_Pos = mean(optim.localModelPosePrior_Pos)';%rec(:,f);% covMatPosePrior_Pos = computeCovMat(optim.localModelPosePrior_Pos,optim.nrOfSVPosePriorP); optim.invCovMatPosePrior_Pos = inv(covMatPosePrior_Pos); startValue = score_Pos(1,1:optim.nrOfPrinComps); % lb = min([score_Pos(:,1:optim.nrOfPrinComps)*lbb; score_Pos(:,1:optim.nrOfPrinComps)*ubb]); % ub = max([score_Pos(:,1:optim.nrOfPrinComps)*lbb; score_Pos(:,1:optim.nrOfPrinComps)*ubb]); Xo = lsqnonlin(@(x) objfunLocal(x,optim,cm),startValue,lb,ub,optLSQ); recOpt(:,f) = optim.coeffs_Pos(:,1:optim.nrOfPrinComps) * Xo' + optim.meanVec_Pos; wtidx = []; w = []; sknn = []; optim.limlen = []; fprintf('\b\b\b\b'); end fprintf('\b done \n'); toc recOpt = H_rigidTransformKnn(recOpt,motGT); motrecOpt = H_mat2cellMot(recOpt,motGT); [er.er3DPoseOpt, er.er3DPoseOpt.std] = H_cal3DError(motrecOpt,motGT,erJoints); disp('3D pose error per every five frames : '); disp(er.er3DPoseOpt.errFr1_5(1,1)); end function f = objfunLocal(x,optim,cm) %% local Objective functions pos_curr = optim.coeffs_Pos(:,1:optim.nrOfPrinComps) * x' + optim.meanVec_Pos; %% Prior pose term e_pose = computePrior_local(optim.localModelPosePrior_Pos',pos_curr,optim.wtPoserep,optim.jointWeights,3,optim.expMPrior); e_pose = e_pose/sqrt(numel(e_pose)); %% control term est3d = H_regularize(pos_curr); est3d = optim.camMtx * est3d; est2d = project_points2Short(est3d,cm.omc_ext,cm.Tc_ext,cm.fc,cm.cc,cm.kc,cm.alpha_c); est2d = reshape(est2d,[],1); e_control = optim.estP2D(optim.cJidx2) - est2d(optim.cJidx2); e_control = reshape(e_control,2,numel(e_control)/2); e_control = sqrt(sum(e_control.^2)); e_control = reshape(e_control,[],1); e_control = e_control /sqrt( numel(e_control)); % for k = 1:length(optim.limlenIdx) limlen(k,1) = sqrt(sum((pos_curr(optim.limlenIdx(k,1:3)) - pos_curr(optim.limlenIdx(k,4:6))).^2)); end e_limb = optim.limlen - limlen(:,ones(1,numel(optim.wtPose))); e_limb = reshape(e_limb,[],1); e_limb = sqrt(e_limb.^2); e_limb = e_limb/sqrt(numel(e_limb)); %% Function return vales -------------------------------------------------- f = [optim.w_pose * e_pose;... optim.w_control * e_control;... optim.w_limb * e_limb... ]; end function est3d = H_regularize(est3d) %% est3d = reshape(est3d,3,[]); est3d ([1 3],:) = flipud(est3d([1 3],:)); % '321' ---> '123' est3d ([2 3],:) = flipud(est3d([2 3],:)); % '123' ---> '132' est3d(4,:) = 1; end function e = computePrior_local(data,query,poseWeights,jointWeights,dofs,exponent) %% % Note: Both poseWeights and jointWeights are already normalized!! diff = data - query(:,ones(1,numel(poseWeights))); diff = reshape(diff,dofs,numel(diff)/dofs); diff = sqrt(sum(diff.^2)); diff = reshape(diff,size(data,1)/dofs,numel(poseWeights)); %diff = reshape(diff,size(data,1),numel(poseWeights)); e = jointWeights .* diff; %e = e.^exponent; poseWeights = repmat(poseWeights,size(diff,1),[]); e = e.* poseWeights; e = reshape(e,[],1); end function covMat = computeCovMat(localModel,nrOfSVPosePrior) %% Compute Covariance Matrix [U,S,V] = svd(localModel,'econ'); singVal = diag(S); totalNrOfSV = numel(singVal); sigma = sum(singVal(nrOfSVPosePrior+1:end).^2)/(totalNrOfSV-nrOfSVPosePrior); S2 = diag([singVal(1:nrOfSVPosePrior)' sqrt(sigma)*ones(1,(totalNrOfSV-nrOfSVPosePrior))]); covMat = V*S2*V'/(totalNrOfSV-1); end %========================================================================== function [er, stdev] = H_cal3DError(motrec,motGT,erJoints) %% error with input er.errJnts = nan(length(erJoints),motrec.nframes); er.errFr = nan(motrec.nframes,1); er.errFrAll = 0; inMot = cell2mat(motrec.jointTrajectories); mocapGT = cell2mat(motGT.jointTrajectories); [er.errJnts, er.errFr, er.errFrAll] = errorHumanEva(inMot,mocapGT,erJoints); stdev = std(er.errFr,1); er.errJnts = squeeze(er.errJnts); er.errFr1_5(1,1) = mean(er.errFr(1:5:end)); er.errFr1_5(2,1) = mean(er.errFr(2:5:end)); er.errFr1_5(3,1) = mean(er.errFr(3:5:end)); er.errFr1_5(4,1) = mean(er.errFr(4:5:end)); er.errFr1_5(5,1) = mean(er.errFr(5:5:end)); er.errFr1_5(1,2) = std(er.errFr(1:5:end),1); % standard ddeviation er.errFr1_5(2,2) = std(er.errFr(2:5:end),1); er.errFr1_5(3,2) = std(er.errFr(3:5:end),1); er.errFr1_5(4,2) = std(er.errFr(4:5:end),1); er.errFr1_5(5,2) = std(er.errFr(5:5:end),1); end function weights = regulateWeights(w) weights = w-min(w); %weights = weights/max(weights); weights = weights/(max(w) - min(w)); end function limlenIdx = H_calLimbLengthIdx(allJoints) %% Limb Lengths ids limbs1 = {'Left Ankle'; 'Left Knee'; 'Left Hip'; 'Left Shoulder'; 'Left Elbow'; 'Right Ankle'; 'Right Knee'; 'Right Hip'; 'Right Shoulder'; 'Right Elbow'; 'Left Hip'; 'Head'; 'Neck';'Neck'}; limbs2 = {'Left Knee'; 'Left Hip'; 'Left Shoulder'; 'Left Elbow'; 'Left Wrist'; 'Right Knee'; 'Right Hip'; 'Right Shoulder'; 'Right Elbow'; 'Right Wrist'; 'Right Hip'; 'Neck'; 'Left Shoulder';'Right Shoulder'}; for n = 1: length(limbs1) idx1 = getSingleJntIdx(limbs1{n},allJoints,3); idx2 = getSingleJntIdx(limbs2{n},allJoints,3); limlenIdx(n,:) = [idx1; idx2]'; end end function recOr = H_Orient(rec,camMtxAllSel) for f = 1:size(rec,2) recTmp = reshape(rec(:,f),3,[]); recTmp(4,:) = 1; %[recOr,dYdom,dYdT] = rigid_motion(recTmp,om,T) tmp = camMtxAllSel{f} * recTmp; recOr(:,f) = tmp(:); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
recOnWeightedKernelH36Mbm.m
.m
3D_Pose_Estimation_CVPR2016-master/code/recOnWeightedKernelH36Mbm.m
12,075
utf_8
ffb099efa7b685200da7d38736999ad3
function [er, optim, opts, motrecOpt] = recOnWeightedKernelH36Mbm(opts) %% options updates close all; % opts_bak = opts; % if(nargin == 0) % [opts, skel] = initializeOpts; % elseif(nargin == 1) % [opts, skel] = initializeOpts(varargin{1}); % elseif(nargin == 2) % [opts, skel] = initializeOpts(varargin{1},varargin{2}); % elseif(nargin == 3) % [opts, skel] = initializeOpts(varargin{1},varargin{2},varargin{3}); % elseif(nargin == 4) % [opts, skel] = initializeOpts(varargin{1},varargin{2},varargin{3},varargin{4}); % elseif(nargin == 5) % [opts, skel] = initializeOpts(varargin{1},varargin{2},varargin{3},varargin{4},varargin{5}); % else % disp('H_error: H_retMain... wring number of input arguments'); % end % round = 1; % opts.round = round; % % opts.database = 'Human36Mbm'; %'Human36Mbm'\'CMU_H36M'; % opts.exp = 'nogt'; % nogt/gt2D/gt3D % opts.loadPath = fullfile('../Data/'); % opts.loadIdxPath = fullfile('../Data/'); % opts.loadInPath = fullfile('../Data/'); % opts.saveResPath = fullfile('../Data/'); if ~exist(opts.saveResPath,'dir') mkdir(opts.saveResPath); end %% Loading input anf GT [motIn, motInN, opts] = loadnPrepareQMot(opts); load(fullfile([opts.loadPath 'motGT_' opts.subject '_' opts.actName ])); %gt if(isfield(opts, 'extractFrameNum') == 1) motGT = extractSingleGT(motGT, opts.extractFrameNum); end estP2D = cell2mat(motIn.jointTrajectories2DF); cm = motIn.camera; %% Loading nn %shape = {'upper';'lower';'left';'right';'pose'}; try shape = motIn.bodyTypeOrder; catch disp('Please load right input which has weighted knn ...'); end for h = 1:length(shape) loadIdxPath = opts.loadIdxPath; idName = [opts.subject '_Activity_All_C2_256_' shape{h} '_obj.mat']; load([loadIdxPath idName]); objAll{h,1}.obj = obj; objAll{h,1}.knn = opts.knn; objAll{h,1}.knnJoints = opts.allJoints; objAll{h,1}.bodyType = shape{h}; idNameCM = [opts.subject '_Activity_All_C2_256_' shape{h} '_camMtx.mat']; load([loadIdxPath idNameCM]); camMtxAll{h,1} = camMtx; loadIdxPath = opts.loadIdxPath; opts.cJno = getShapeJointNum(shape{h},opts.inputDB); [opts.allJoints, opts.cJoints] = getJointsHE (opts.inputDB,opts.database,opts.cJno,shape{h}); opts = getJointsIdx(opts); jnts.cJidx{h,1} = opts.cJidx; jnts.cJidx2{h,1} = opts.cJidx2; jnts.cJidx3{h,1} = opts.cJidx3; end %% reconstruction options erJoints = 14; selknn = 256; nknn = 64; optim.nknn = nknn; optim.nrOfSVPosePriorP = 18; %25 %30 % number of singular values used for pose term optim.nrOfPrinComps = 18; %25 %30 optim.w_pose = .35; %20 .60 optim.w_control = .55; %10 .45 optim.w_limb = .065; %10 .05 fprintf('%3d ', optim.w_pose ); fprintf('%3d ', optim.w_control); fprintf('%3d ', optim.w_limb ); disp(' . . . done'); optim.expPPrior = 0.5; optim.expMPrior = 0.5; optim.expSmooth = 0.5; optim.expControl = 0.5; optim.jointWeights = 1; optim.jointWeights2D = 1; optLSQ = optimset( 'Display','none',... %'iter', 'MaxFunEvals',100000,... 'MaxIter',1000,... 'TolFun',0.001,... 'TolX',0.001,... 'LargeScale','on',... 'Algorithm','levenberg-marquardt'); lb = []; ub = []; %% Reconstruction bt = 'all'; % all/pose optim.limlenIdx = H_calLimbLengthIdx(opts.allJoints); tic fprintf('Reconstruction: Frame no. ... '); for f = 1:motIn.nframes fprintf('%3d ', f); if(strcmp(bt,'all')) sObj = objAll{motIn.bodyType(f),1}; else sObj = objAll{1,1}; end sknn = sObj.obj.data(:,f); sknn = reshape(sknn,3*length(opts.allJoints),[]); sknn = sknn(:,1:selknn); for j = 1:length(optim.limlenIdx) optim.limlen(j,:) = sqrt(sum((sknn(optim.limlenIdx(j,1:3),:) - sknn(optim.limlenIdx(j,4:6),:)).^2)); end w = motIn.knnWts(1:selknn,f)'; ind = find(w>1); w(ind) = 0; w = regulateWeights(w); [~, wtidx] = sort(w,'descend'); w = w(wtidx(1:nknn)); optim.limlen = optim.limlen(:,wtidx(1:nknn)); sknn = sknn(:,wtidx(1:nknn)); opts.bodyType = sObj.bodyType; opts.cJno = getShapeJointNum(opts.bodyType,opts.inputDB); [opts.allJoints, opts.cJoints] = getJointsHE (opts.inputDB,opts.database,opts.cJno,opts.bodyType); opts = getJointsIdx(opts); optim.estP2D = estP2D(:,f); if(strcmp(bt,'all')) optim.camMtx = cell2mat(camMtxAll{motIn.bodyType(f),1}(f,1)); else optim.camMtx = cell2mat(camMtxAll{1,1}(f,1)); end optim.cJidx2 = opts.cJidx2; optim.wtPose = w; wlm = ceil(w*10); for k = 1:length(wlm) nn = repmat(sknn(:,k),1,wlm(k)); nn2d = repmat(sknn(:,k),1,wlm(k)); wt = repmat(w(k),1,wlm(k)); if (k == 1) nnrep = nn; nnrep2d = nn2d; wrep = wt; else nnrep = [nnrep,nn]; nnrep2d = [nnrep2d,nn2d]; wrep = [wrep,wt]; end end optim.wtPoserep = wrep; optim.localModelPosePrior_Pos = nnrep'; %sknn'; % [optim.coeffs_Pos,score_Pos] = princomp2(optim.localModelPosePrior_Pos); optim.meanVec_Pos = mean(optim.localModelPosePrior_Pos)';%rec(:,f);% covMatPosePrior_Pos = computeCovMat(optim.localModelPosePrior_Pos,optim.nrOfSVPosePriorP); optim.invCovMatPosePrior_Pos = inv(covMatPosePrior_Pos); if f > 1 startValue = (optim.coeffs_Pos(:,1:optim.nrOfPrinComps) \ (recOpt(:,f - 1) - optim.meanVec_Pos))'; else startValue = score_Pos(1,1:optim.nrOfPrinComps); end startValue = score_Pos(1,1:optim.nrOfPrinComps); Xo = lsqnonlin(@(x) objfunLocal(x,optim,cm),startValue,lb,ub,optLSQ); recOpt(:,f) = optim.coeffs_Pos(:,1:optim.nrOfPrinComps) * Xo' + optim.meanVec_Pos; wtidx = []; w = []; sknn = []; optim.limlen = []; fprintf('\b\b\b\b'); end fprintf('\b done \n'); toc %% Reconstruct with kernal approach recOpt = H_rigidTransformKnn(recOpt,motGT); motrecOpt = H_mat2cellMot(recOpt,motGT); [er.er3DPoseOpt, er.er3DPoseOpt.std] = H_cal3DError(motrecOpt,motGT,erJoints); disp(er.er3DPoseOpt.errFrAll); %motPlay3D('Human36Mbm',motrecOpt); end function f = objfunLocal(x,optim,cm) pos_curr = optim.coeffs_Pos(:,1:optim.nrOfPrinComps) * x' + optim.meanVec_Pos; e_pose = computePrior_local(optim.localModelPosePrior_Pos',pos_curr,optim.wtPoserep,optim.jointWeights,3,optim.expMPrior); e_pose = e_pose/sqrt(numel(e_pose)); est3d = H_regularize(pos_curr); [est2d,~] = H_proj(optim.camMtx,est3d,cm); est2d = reshape(est2d,[],1); e_control = optim.estP2D(optim.cJidx2) - est2d(optim.cJidx2); e_control = reshape(e_control,2,numel(e_control)/2); e_control = sqrt(sum(e_control.^2)); e_control = reshape(e_control,[],1); e_control = e_control /sqrt( numel(e_control)); % for k = 1:length(optim.limlenIdx) limlen(k,1) = sqrt(sum((pos_curr(optim.limlenIdx(k,1:3)) - pos_curr(optim.limlenIdx(k,4:6))).^2)); end e_limb = optim.limlen - limlen(:,ones(1,numel(optim.wtPose))); e_limb = reshape(e_limb,[],1); e_limb = sqrt(e_limb.^2); e_limb = e_limb/sqrt(numel(e_limb)); f = [optim.w_pose * e_pose;... optim.w_control * e_control;... optim.w_limb * e_limb... ]; end function est3d = H_regularize(est3d) %% est3d = reshape(est3d,3,[]); est3d([2 3],:) = flipud(est3d([2 3],:)); est3d(4,:) = 1; end function e = computePrior_local(data,query,poseWeights,jointWeights,dofs,exponent) %% % Note: Both poseWeights and jointWeights are already normalized!! diff = data - query(:,ones(1,numel(poseWeights))); diff = reshape(diff,dofs,numel(diff)/dofs); diff = sqrt(sum(diff.^2)); diff = reshape(diff,size(data,1)/dofs,numel(poseWeights)); %diff = reshape(diff,size(data,1),numel(poseWeights)); e = jointWeights .* diff; %e = e.^exponent; poseWeights = repmat(poseWeights,size(diff,1),[]); e = e.* poseWeights; e = reshape(e,[],1); end function covMat = computeCovMat(localModel,nrOfSVPosePrior) %% Compute Covariance Matrix [U,S,V] = svd(localModel,'econ'); singVal = diag(S); totalNrOfSV = numel(singVal); sigma = sum(singVal(nrOfSVPosePrior+1:end).^2)/(totalNrOfSV-nrOfSVPosePrior); S2 = diag([singVal(1:nrOfSVPosePrior)' sqrt(sigma)*ones(1,(totalNrOfSV-nrOfSVPosePrior))]); covMat = V*S2*V'/(totalNrOfSV-1); end %========================================================================== function [er, stdev] = H_cal3DError(motrec,motGT,erJoints) %% error with input er.errJnts = nan(length(erJoints),motrec.nframes); er.errFr = nan(motrec.nframes,1); er.errFrAll = 0; inMot = cell2mat(motrec.jointTrajectories); mocapGT = cell2mat(motGT.jointTrajectories); [er.errJnts, er.errFr, er.errFrAll] = errorHumanEva(inMot,mocapGT,erJoints); stdev = std(er.errFr,1); % er.errJnts = squeeze(er.errJnts); er.errFr1_5(1,1) = mean(er.errFr(1:5:end)); er.errFr1_5(2,1) = mean(er.errFr(2:5:end)); er.errFr1_5(3,1) = mean(er.errFr(3:5:end)); er.errFr1_5(4,1) = mean(er.errFr(4:5:end)); er.errFr1_5(5,1) = mean(er.errFr(5:5:end)); er.errFr1_5(1,2) = std(er.errFr(1:5:end),1); % standard ddeviation er.errFr1_5(2,2) = std(er.errFr(2:5:end),1); er.errFr1_5(3,2) = std(er.errFr(3:5:end),1); er.errFr1_5(4,2) = std(er.errFr(4:5:end),1); er.errFr1_5(5,2) = std(er.errFr(5:5:end),1); end function weights = regulateWeights(w) %% Normalize weights between 0 - 1 weights = w-min(w); %weights = weights/max(weights); weights = weights/(max(w) - min(w)); end function limlenIdx =H_calLimbLengthIdx(allJoints) %% Limb Lengths ids limbs1 = {'Left Ankle'; 'Left Knee'; 'Left Hip'; 'Left Shoulder'; 'Left Elbow'; 'Right Ankle'; 'Right Knee'; 'Right Hip'; 'Right Shoulder'; 'Right Elbow'; 'Left Hip'; 'Head'; 'Neck';'Neck'}; limbs2 = {'Left Knee'; 'Left Hip'; 'Left Shoulder'; 'Left Elbow'; 'Left Wrist'; 'Right Knee'; 'Right Hip'; 'Right Shoulder'; 'Right Elbow'; 'Right Wrist'; 'Right Hip'; 'Neck'; 'Left Shoulder';'Right Shoulder'}; for n = 1: length(limbs1) idx1 = getSingleJntIdx(limbs1{n},allJoints,3); idx2 = getSingleJntIdx(limbs2{n},allJoints,3); limlenIdx(n,:) = [idx1; idx2]'; end end function H_motionPlayer(skel,mot1,mot2) scalingFactor = 10; for i = 1:mot1.njoints mot1.jointTrajectories{i,1}(1,:) = mot1.jointTrajectories{i,1}(1,:)/scalingFactor ; mot1.jointTrajectories{i,1}(2,:) = mot1.jointTrajectories{i,1}(2,:)/scalingFactor ; mot1.jointTrajectories{i,1}(3,:) = mot1.jointTrajectories{i,1}(3,:)/scalingFactor ; mot2.jointTrajectories{i,1}(1,:) = mot2.jointTrajectories{i,1}(1,:)/scalingFactor ; mot2.jointTrajectories{i,1}(2,:) = mot2.jointTrajectories{i,1}(2,:)/scalingFactor ; mot2.jointTrajectories{i,1}(3,:) = mot2.jointTrajectories{i,1}(3,:)/scalingFactor ; end mot1.boundingBox = computeBoundingBox(mot1); mot2.boundingBox = computeBoundingBox(mot2); motionplayerPro('skel',skel,'mot',{mot1,mot2}); end function [est2d,j3d] = H_proj(x,est3d,cm) R = makehgtform('xrotate',deg2rad(x(1)),'yrotate',deg2rad(x(2)),'zrotate',deg2rad(x(3))); R = R(1:3,1:3); T = [x(4); x(5); x(6)]; R = [R T]; j3d = R*est3d; % T = T'; % j3d = est3d(1:3,:); [est2d, ~] = ProjectPointRadial(j3d', cm.R, cm.T, cm.f, cm.c, cm.k, cm.p); est2d = est2d'; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
recMotNG.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/ChaiHodgins/recMotNG.m
7,550
utf_8
5c5a145cfee329a3ba212b265ee261a1
function res = recMotNG(skel,mot,priorKnowledge) % setting variables ---------------------------------------------- dataRep = 'euler'; % quat is bad for prior controlJoints = [4,9,17,18,20,25,27]; % joints for simulated control signal selectedJoints = [4,9,19,20,26,27];%[3,4,8,9,12:17,19,20,26,27];%[4,9,20,27,3,8,19,26]; % joints for prior term k = 25; % number of nearest neighbours nrOfPrinComps = []; % number of principal components startFrame = 1; endFrame = 10;%mot.nframes; % ---------------------------------------------------------------- % preprocessing data --------------------------------------------- selectedJointsIndices = jointIDsToMatrixIndices(skel,selectedJoints); posData = priorKnowledge.mat_pos; nGraph = priorKnowledge.nGraph; mot.rootTranslation = zeros(3,mot.nframes); % mot.rotationQuat{1} = [ones(1,mot.nframes);zeros(3,mot.nframes)]; % mot = convert2euler(skel,mot); % mot.jointTrajectories = forwardKinematicsQuat(skel,mot); % mot.boundingBox = computeBoundingBox(mot); mot = fitRootOrientationsFrameWise(skel,mot); mot = cutMotion(mot,startFrame,endFrame); skel = addDOFIDsToSkel(skel); res.origmot = mot; optimStruct.origmot = mot; posData = mat2cell(posData,3*ones(1,size(posData,1)/3),size(posData,2)); posData = cell2mat(posData(controlJoints)); switch dataRep case 'quat' rotData = priorKnowledge.mat_quat; optimStruct.selectedJointsIndices = selectedJointsIndices.quats; rotations = zeros(size(cell2mat(mot.rotationQuat(mot.animated)))); case 'euler' rotData = priorKnowledge.mat_euler; optimStruct.selectedJointsIndices = selectedJointsIndices.euler; rotations = zeros(size(cell2mat(mot.rotationEuler(mot.animated)))); end controlSignal = cell2mat(mot.jointTrajectories(controlJoints)); optimStruct.skel = skel; if isempty(nrOfPrinComps) nrOfPrinComps = size(rotData,1); end optimStruct.nrOfPrinComps = nrOfPrinComps; optimStruct.qlastlast = []; optimStruct.qlast = []; optimStruct.controlJoints = controlJoints; % quats = cell2mat(mot.rotationQuat(mot.animated)); % optimStruct.qlastlast = quats(:,1); % optimStruct.qlast = quats(:,2); % ---------------------------------------------------------------- % setting options for optimization ------------------------------- options = optimset( 'Display','iter',... 'MaxFunEvals',100000,... 'MaxIter',100,... 'TolFun',0.001,... 'PlotFcns', @optimplotx); % 'LargeScale','off',...%);%,... lb = []; ub = []; % --------------------------------------------------------------- % estimating nearest neighbours of 0th frame -------------------- distances = sum(abs(posData-repmat(controlSignal(:,1),1,size(posData,2)))); [distancesSorted,indicesSorted] = sort(distances); NNlast = indicesSorted(1:k); % indices of NN of last synthesized pose % --------------------------------------------------------------- for i=startFrame:endFrame counter = i-startFrame+1; fprintf('\nReconstructing frame %i (%i/%i)...\n',i,counter,endFrame-startFrame+1); optimStruct.controlSignal = controlSignal(:,counter); NNcandidates = getNeighboursNGraph(nGraph,NNlast); fprintf('Number of NN-candidates: %i\n',length(NNcandidates)); rotData_tmp = rotData(:,NNcandidates); posData_tmp = posData(:,NNcandidates); indicesSorted = sortByQueryMetric(rotData_tmp,posData_tmp,optimStruct.qlast,optimStruct.qlastlast,optimStruct.controlSignal); NNlast = NNcandidates(indicesSorted(1:k)); optimStruct.localModel_rot = rotData(:,NNlast)'; % optimStruct.localModel_pos = posData(:,NNlast)'; [optimStruct.coeffs,optimStruct.score] = princomp(optimStruct.localModel_rot); optimStruct.meanVec = mean(optimStruct.localModel_rot,1)'; optimStruct.Delta = optimStruct.localModel_rot(:,optimStruct.selectedJointsIndices); optimStruct.priorFactor = inv(cov(optimStruct.Delta)); % ----------------------------------------------------------- % Es gilt (modulo Rechenungenauigkeit): % optimStruct.localModel_rot == ... % optimStruct.score(:,1:nrOfPrinComps) * optimStruct.coeffs(:,1:nrOfPrinComps)' ... % + repmat(optimStruct.meanVec,nrOfPrinComps,1); % ----------------------------------------------------------- % optimization for frame i ---------------------------------- startValue = (optimStruct.localModel_rot(1,:)-optimStruct.meanVec') / optimStruct.coeffs(:,1:nrOfPrinComps)'; % startValue = ones(size(optimStruct.meanVec'))/length(optimStruct.meanVec); X = lsqnonlin(@(x) objfunLocal(x,optimStruct),startValue,lb,ub,options); % ----------------------------------------------------------- if ~isempty(optimStruct.qlast) optimStruct.qlastlast = optimStruct.qlast; end optimStruct.qlast = optimStruct.coeffs(:,1:nrOfPrinComps) * X'... + optimStruct.meanVec; if ~isempty(optimStruct.qlastlast) optimStruct.smoothSummand = - 2*optimStruct.qlast + optimStruct.qlastlast; end rotations(:,counter) = optimStruct.qlast; end res.recmot = buildMotFromRotData(rotations,skel); end %% local functions function f = objfunLocal(x,optimStruct) rotData_curr = optimStruct.coeffs(:,1:optimStruct.nrOfPrinComps) * x'... + optimStruct.meanVec; q_curr = buildMotFromRotData(rotData_curr,optimStruct.skel); % ------- control term ------------ e_control = cell2mat(q_curr.jointTrajectories(optimStruct.controlJoints))... - optimStruct.controlSignal; e_control = e_control / sqrt(numel(e_control)); % e_control = sum(e_control.^2); % ------- smoothness term --------- if ~isempty(optimStruct.qlastlast) e_smooth = rotData_curr + optimStruct.smoothSummand; else e_smooth = zeros(size(rotData_curr)); end e_smooth = e_smooth / sqrt(numel(e_smooth)); % e_smooth = sum(e_smooth.^2); % ------- prior term ------------ diffVec = (rotData_curr(optimStruct.selectedJointsIndices)-optimStruct.meanVec(optimStruct.selectedJointsIndices)); e_prior = diffVec'... * optimStruct.priorFactor... * diffVec; e_prior = e_prior / numel(diffVec); % ------- overall error -------- % f = e_prior; w_control = 1;%0.8; w_smooth = 1;%0.2; w_prior = 1;%0.5; f = [w_control * e_control;... w_smooth * e_smooth;... w_prior * e_prior]; % b = [sum((w_control*e_control).^2) sum((w_smooth *e_smooth ).^2)]; % b = [sum((w_control*e_control).^2) sum((w_smooth *e_smooth ).^2) (w_prior*e_prior).^2]; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
sortByQueryMetric.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/ChaiHodgins/sortByQueryMetric.m
872
utf_8
9ff925af44a4bbf7078f3e093ca8e830
% Input: % - rotData: rotation data of all candidates (for Euler angles of size 59 x #candidates) % - posData: position data of selected joints of all candidates % - qlast: rotation data of last synthesized pose % - qlastlast: rotation data of second last synthesized pose % - controlSignal: current position data of control markers function [candidatesSorted,distancesSorted] = sortByQueryMetric(rotData,posData,qlast,qlastlast,controlSignal) nPoints = size(posData,2); alpha = 0.8; beta = 0.2; control_term = sum((posData-repmat(controlSignal,1,nPoints)).^2); if ~isempty(qlastlast) smoothness_term = sum((rotData+repmat(-2*qlast+qlastlast,1,nPoints)).^2); else smoothness_term = 0; end distances = alpha * control_term + beta * smoothness_term; [distancesSorted,candidatesSorted] = sort(distances);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
recMotNG_new.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/ChaiHodgins/recMotNG_new.m
8,130
utf_8
3e337954f724eaeb097671cfcfcbaf66
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function recMotNG (REConstruct MOTion using Neighbour Graph) % % res = recMotNG(skel,mot,data) % % input: % - skel: skeleton struct % - mot: mot struct % - data: struct containing fields 'nGraph', 'quat' and 'pos', % obtained by data = buildNeighbourGraphC; % output: % - res: struct containing fields 'origmot' and 'recmot' % % author: Jochen Tautges ([email protected]) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = recMotNG_new(skel,mot,data) % options for reconstruction ------------- % optimStruct.joints = [4,9,17,18,21,25,28]; % joints simulating control data optimStruct.joints = [4,28]; % joints simulating control data optimStruct.priorJoints = [3,4,5,8,9,10,12:17,19,20,21,26,27,28]; % joints used for pose prior optimStruct.nrOfPrinComps = 64; % number of principal components used to represent poses k = 256; % number of nearest neighbours used to build local model optimStruct.r = 32; % number of singular values used for prior term startFrame = 1; endFrame = mot.nframes; res.w_control = 1; res.w_smoothness = 1; res.w_prior = 10; % ---------------------------------------- optimStruct.w_control = res.w_control; optimStruct.w_smoothness = res.w_smoothness; optimStruct.w_prior = res.w_prior; % options for optimization --------------- lb = []; ub = []; options = optimset( 'Display','iter',... 'MaxFunEvals',100000,... 'MaxIter',50,... 'TolFun',0.01);%,... % 'LargeScale','off');%,... % use Levenberg Marquard % 'PlotFcns', @optimplotx); % ---------------------------------------- res.skel = skel; mot = cutMotion(mot,startFrame,endFrame); res.origmot = mot; mot.rootTranslation = zeros(3,mot.nframes); mot.rotationQuat{1}(1,:) = 1; mot.rotationQuat{1}(2:4,:) = 0; mot.jointTrajectories = forwardKinematicsQuat(skel,mot); % mot = fitRootOrientationsFrameWise(skel,mot); mot.boundingBox = computeBoundingBox(mot); res.recmot = emptyMotion(mot); quatrec = zeros(size(data.quat,1),mot.nframes); optimStruct.jointIDX = jointIDsToMatrixIndices(skel,optimStruct.joints); optimStruct.priorIDX = jointIDsToMatrixIndices(skel,optimStruct.priorJoints); dofs = getDOFsFromSkel(skel); optimStruct.skel = skel; optimStruct.posLast = []; optimStruct.posLastLast = []; controlSignal = cell2mat(mot.jointTrajectories(optimStruct.joints)); % estimating nearest neighbours of 0th frame -------------------- distances = sum(abs(data.pos(optimStruct.jointIDX.pos,:)-repmat(controlSignal(:,1),1,size(data.pos,2)))); [distancesSorted,indicesSorted] = sort(distances); NNlast = indicesSorted(1:k); % indices of NN of last synthesized pose % --------------------------------------------------------------- if isempty(optimStruct.nrOfPrinComps) optimStruct.nrOfPrinComps = size(data.quat,1); end % optimStruct.localModel = data.quat'; % [optimStruct.coeffs,score] = princomp2(optimStruct.localModel); % optimStruct.meanVec = mean(optimStruct.localModel)'; for i=startFrame:endFrame counter = i-startFrame+1; fprintf('\nReconstructing frame %i (%i/%i)...\n',i,counter,endFrame-startFrame+1); optimStruct.controlSignal = controlSignal(:,counter); NNcandidates = getNeighboursNGraph(data.nGraph,NNlast); fprintf('Number of NN-candidates: %i\n',length(NNcandidates)); rotData_tmp = data.quat(optimStruct.jointIDX.quats,NNcandidates); posData_tmp = data.pos(optimStruct.jointIDX.pos,NNcandidates); indicesSorted = sortByQueryMetric(rotData_tmp,posData_tmp,optimStruct.posLast,optimStruct.posLastLast,optimStruct.controlSignal); NNlast = NNcandidates(indicesSorted(1:k)); optimStruct.localModel = data.quat(:,NNlast)'; [optimStruct.coeffs,score] = princomp2(optimStruct.localModel); optimStruct.meanVec = mean(optimStruct.localModel)'; [U,S,V] = svd(optimStruct.localModel(:,optimStruct.priorIDX.quats)); singVal = diag(S); sigma = sum(singVal(optimStruct.r+1:end).^2)/(numel(singVal)-optimStruct.r); S2 = diag([singVal(1:optimStruct.r)' sqrt(sigma)*ones(1,(numel(singVal)-optimStruct.r))]); C = V*S2*V'/(numel(singVal)-1); optimStruct.meanVecPrior = mean(optimStruct.localModel(:,optimStruct.priorIDX.quats))'; optimStruct.priorFactor = inv(C); if counter==1 % choose x of nearest neighbour as startvalue startValue = score(1,1:optimStruct.nrOfPrinComps); else % choose x of last reconstructed pose as startvalue startValue = (optimStruct.coeffs(:,1:optimStruct.nrOfPrinComps) \ (quatrec(:,counter-1) - optimStruct.meanVec))'; end % optimization ------------------------------------- X = lsqnonlin(@(x) objfunLocal(x,optimStruct),startValue,lb,ub,options); % -------------------------------------------------- quatrec(:,counter) = optimStruct.coeffs(:,1:optimStruct.nrOfPrinComps) * X' + optimStruct.meanVec; if ~isempty(optimStruct.posLast) optimStruct.qLastLast = optimStruct.qLast; optimStruct.qLast = quatrec(:,counter); optimStruct.summand = - 2*optimStruct.qLast + optimStruct.qLastLast; else optimStruct.qLast = quatrec(:,counter); end end res.recmot.rootTranslation = res.origmot.rootTranslation; res.recmot.rotationQuat = mat2cell(quatrec,dofs.quat,i); res.recmot.rotationQuat{1} = res.origmot.rotationQuat{1}; res.recmot.jointTrajectories = C_forwardKinematicsQuat(skel,res.recmot); res.recmot.boundingBox = computeBoundingBox(res.recmot); res.recmot = convert2euler(skel,res.recmot); res.dist = compareMotions08(skel,res.origmot,res.recmot); end %% local functions function f = objfunLocal(x,optimStruct) quat_curr = optimStruct.coeffs(:,1:optimStruct.nrOfPrinComps) * x' + optimStruct.meanVec; mot_curr = buildMotFromRotData(quat_curr,optimStruct.skel); pos_curr = cell2mat(mot_curr.jointTrajectories); % control term -------------------------------------------------------- e_control = optimStruct.controlSignal - pos_curr(optimStruct.jointIDX.pos); e_control = e_control / sqrt(numel(e_control)); % --------------------------------------------------------------------- % smoothness term ----------------------------------------------------- if ~isempty(optimStruct.posLastLast) e_smoothness = pos_curr + optimStruct.summand; else e_smoothness = zeros(size(pos_curr)); end e_smoothness = e_smoothness / sqrt(numel(e_smoothness)); % --------------------------------------------------------------------- % prior term ---------------------------------------------------------- diffVec = quat_curr(optimStruct.priorIDX.quats) - optimStruct.meanVecPrior; e_prior = diffVec'... * optimStruct.priorFactor... * diffVec; e_prior = e_prior / numel(diffVec); % --------------------------------------------------------------------- f = [optimStruct.w_control * e_control;... optimStruct.w_smoothness * e_smoothness;... optimStruct.w_prior * e_prior]; % b = [sum((w_control * e_control).^2),... % sum((w_smoothness * e_smoothness).^2),... % sum((w_prior * e_prior).^2)]; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
readKinectData.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/kinectRecordings/readKinectData.m
2,220
utf_8
0d752a6e31d824a416f68c48b6eae6b6
function [skels,mots] = readKinectData(file) rawdata = importdata(file); if ~isempty(rawdata) timestamps = rawdata(:,1); skelids = rawdata(:,2); skeldata = rawdata(:,3:end); diffskelids = unique(skelids); numskels = numel(diffskelids); mots = cell(numskels,1); skels = cell(numskels,1); nframes = zeros(numskels,1); for cs = 1:numskels mots{cs} = emptyMotion(); skels{cs} = emptySkeleton(); mots{cs}.nframes = sum(skelids==diffskelids(cs)); mots{cs}.filename = [file '_skel_' num2str(diffskelids(cs))]; mots{cs}.timestamps = timestamps(skelids==diffskelids(cs)); mots{cs}.jointTrajectories = skeldata(skelids==diffskelids(cs),:)'*100; mots{cs}.jointTrajectories = mat2cell(mots{cs}.jointTrajectories, ... 3*ones(20,1),mots{cs}.nframes); [skels{cs},mots{cs}] = setKinectDefaultValues(skels{cs},mots{cs}); end else skels=[]; mots=[]; end end function [skel,mot] = setKinectDefaultValues(skel,mot) % Hardcoded properties of kinect skeleton ... mot.njoints = 20; mot.jointNames = {'HIP_CENTER', ... 'SPINE', ... 'SHOULDER_CENTER', ... 'HEAD', ... 'SHOULDER_LEFT', ... 'ELBOW_LEFT', ... 'WRIST_LEFT', ... 'HAND_LEFT', ... 'SHOULDER_RIGHT', ... 'ELBOW_RIGHT', ... 'WRIST_RIGHT', ... 'HAND_RIGHT', ... 'HIP_LEFT', ... 'KNEE_LEFT', ... 'ANKLE_LEFT',... 'FOOT_LEFT',... 'HIP_RIGHT',... 'KNEE_RIGHT',... 'ANKLE_RIGHT',... 'FOOT_RIGHT'}'; mot.boneNames = mot.jointNames; mot.animated = 1:20; skel.njoints = mot.njoints; skel.animated = mot.animated; skel.boneNames = mot.boneNames; skel.filename = mot.filename; skel.nameMap = mot.boneNames; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
buildTensorActRepStyle.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/buildTensorActRepStyle.m
7,136
utf_8
d6e3ee0b48a4b327d2d03755869165c9
function [Tensor]=buildTensorActRepStyle(p,varargin) % Creates a motion tensor from a given Directories of our % MocapDB. Each directory corresponds to one style. % All motions in a given directories are warped and put into the tensor. % The reference motion is allways the first motion in the first dir. % author: Bjoern Krueger ([email protected]) % R:\HDM05_3style_example\cut_amc % If there is a maximum of Reps definied us it, otherwise use all % motions. ! Can result in a lot of NaN's. switch nargin case 2 maxRep =varargin{1}; dataRep='Quat'; Styles ={'walk4StepsRstart', ... 'walkLeftCircle4StepsRstart', ... 'walkRightCircle4StepsRstart'}; case 3 maxRep =varargin{1}; dataRep=varargin{2}; Styles ={'walk4StepsRstart', ... 'walkLeftCircle4StepsRstart', ... 'walkRightCircle4StepsRstart'}; case 4 maxRep =varargin{1}; dataRep=varargin{2}; Styles =varargin{3}; otherwise error('Wrong number of Args'); end % Define size of Representation switch dataRep case 'Quat' dimDataRep=4; case 'Position' dimDataRep=3; case 'ExpMap' dimDataRep=3; otherwise error('buildTensorActRepStyle: Wrong Date specified in var: dataRep'); end % Check if Backslash is included in path and append extension. dim=size(p); if(p(dim(2))~='\') p=[p '\']; end ext='*.amc'; % Check if there is a Directory for every Style: numStyles=size(Styles,2); for s=1:numStyles if(~exist([p Styles{1,s}],'dir')) error(['buildTensorActRepStyle: ' ... 'Dir for Style ' ... Styles{1,s} ' does not exist!']); end end % Get Lists of files: for s=1:numStyles listofFiles{s}=dir([p Styles{1,s} '\' ext]); numMotions{s} =size(listofFiles{s},1); end dimStyleMode =numStyles; dimActorsMode=5; dimRepMode =maxRep; %% Collect Information about the given %% Files/Styles/Classes % We need the number of actors, minimum of repetitions % This are information about the dimension of the % resulting tensor. % Known Actors: bd,bk,mm,dg,tr actors{1}='HDM_bd'; actors{2}='HDM_bk'; actors{3}='HDM_dg'; actors{4}='HDM_mm'; actors{5}='HDM_tr'; numActors=size(actors,2); reps=zeros(numActors,numStyles); for s=1:numStyles %Count repetitions of each actor for a=1:numActors reps(a,s)=countActor(listofFiles{s},actors{a}); end end % Motions to fit by DTW skelfile=fullfile(p, Styles{1,1}, [actors{1} '.asf']); motfile =fullfile(p, Styles{1,1}, listofFiles{1}(1).name); [fitskel,fitmot]=readMocap(skelfile,motfile); fprintf('fitmot: '); fprintf([listofFiles{s}(1).name '\n']) fitmot=reduceFrameRate(fitskel,fitmot); Tensor.DataRep=dataRep; Tensor.numNaturalModes = 3; Tensor.dimNaturalModes = [dimStyleMode dimActorsMode dimRepMode]; Tensor.numTechnicalModes= 3; Tensor.dimTechnicalModes= [dimDataRep fitmot.nframes fitmot.njoints]; Tensor.styles=Styles; % Allocate memory for Tensor Tensor.data=NaN([Tensor.dimTechnicalModes Tensor.dimNaturalModes]); for s=1:numStyles rep=1; actor=1; fprintf(' '); file=1; % Run throgh list of files while (file<numMotions{s}) % for file=1:dim(1) if(actor<=size(actors,2)) if(rep<=reps(actor,s)&&rep<=maxRep) %Load motion fprintf('\b\b\b\bRead '); skelfile=fullfile(p, Styles{1,s}, [actors{actor} '.asf']); motfile =fullfile(p, Styles{1,s}, listofFiles{s}(file).name); fprintf(listofFiles{s}(file).name); [skel,mot]=readMocap(skelfile,motfile); % Reduce frame rate mot=reduceFrameRate(skel,mot); % fit motion mot=fitMotion(skel,mot); % Timewarp motion for c=1:size(listofFiles{s}(file).name,2) fprintf('\b'); end fprintf('\b\b\b\b\bWarp'); [mot]=SimpleDTW(fitmot,skel,mot); % Fill warped motion into tensor Tensor.rootdata(:,:,s,actor,rep)=mot.rootTranslation; Tensor.motions{s,actor,rep}=motfile; Tensor.skeletons{s,actor,rep}=skelfile; for joint=1:mot.njoints Tensor.joints{joint,s,actor,rep}=mot.jointNames{joint}; switch dataRep case 'Quat' if(~isempty(mot.rotationQuat{joint})) Tensor.data(:,:,joint,s,actor,rep)=mot.rotationQuat{joint}; else Tensor.data(1,:,joint,s,actor,rep) =ones (1,mot.nframes); Tensor.data(2:4,:,joint,s,actor,rep)=zeros(3,mot.nframes); end case 'Position' if(~isempty(mot.jointTrajectories{joint})) Tensor.data(:,:,joint,s,actor,rep)=mot.jointTrajectories{joint}; else Tensor.data(1:3,:,joint,s,actor,rep)=zeros(3,mot.nframes); end case 'ExpMap' if(~isempty(mot.rotationQuat{joint})) Tensor.data(:,:,joint,s,actor,rep)=quatlog(mot.rotationQuat{joint}); else Tensor.data(1:3,:,joint,s,actor,rep)=zeros(3,mot.nframes); end otherwise error('buildTensorActRepStyle: Wrong Type specified in var: dataRep\n'); end end rep=rep+1; file=file+1; else actor=actor+1; rep=1; % file=file-1; end else file=file+1; end end fprintf('\b\b\b\b'); end Tensor=HOSVDv2(Tensor); end function num=countActor(files,actor) LoFN=[files(:).name]; tmp=size(strfind(LoFN,actor)); num=tmp(2); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
findCoefficientsColumn.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/findCoefficientsColumn.m
3,362
utf_8
a033daf8edd44b1c910f685662a2d570
% FUNCTION findCoefficients searches for optimal coefficients to % reconstruct a given motion out of a given tensor. It uses the Matlab % Optimization Toolbox. % INPUT: % Tensor: struct: containing data, core, matrices. % newMot: struct: the motion that should be reconstructed. % varargin{1}: string: Type of data Representation 'Quat' or 'Position' % varargin{2}: cell of arrays: Start values for optimization values % have to correspond to the number of natural and % technical modes. % % OUTPUT: % X: cell array: coefficients found for best solution % Y: cell array: X normalized to length 1 % mot: struct: motion reconstructed with X % d: float: distance, correponding to the used distance % measure between mot and newMot. function [X] = findCoefficientsColumn(Tensor,newMot,varargin) % Align first new Motion like all others! % [skel,fitmot]=reconstructMotionT(Tensor,[1 1 1]); % skel = readASF(Tensor.skeletons{1,1}); % newMot=fitMotion(skel,newMot); % Timewarp motion %[newMot]=SimpleDTW(fitmot,skel,newMot); nrOfTechnicalModes=Tensor.numTechnicalModes; nrOfNaturalModes =Tensor.numNaturalModes; % Compute mode-n-product of core tensor and all matrices related to % technical modes core_tmp=Tensor.core; for i=1:nrOfTechnicalModes core_tmp=modeNproduct(core_tmp,Tensor.factors{i},i); end root_tmp=Tensor.rootcore; for i=1:nrOfTechnicalModes-1 root_tmp=modeNproduct(root_tmp,Tensor.rootfactors{i},i); end iter=500; % Set options for optimization options = optimset('Display','iter','MaxFunEvals',iter*12,'MaxIter',iter,'TolFun',1e-1); % Set lower and upper bounds for optimization variable x dimvec=size(core_tmp); n=sum(dimvec(nrOfTechnicalModes+1:end)); % lb=-0.5*ones(1,n); % ub= 1.5*ones(1,n); % Define used representation of motion data within the Tensor and % define starting guess x0 if not set by user (through varargin) x0=0; for i=1:nrOfNaturalModes for j=1:dimvec(nrOfTechnicalModes+i) x0=[x0 1/dimvec(nrOfTechnicalModes+i)]; end end x0=x0(2:end); setx0=false; readSkel=true; switch nargin case 2 DataRep='Quat'; case 3 DataRep=varargin{1}; case 4 x0=varargin{2}; setx0=true; DataRep=varargin{1}; case 5 x0=varargin{2}; setx0=true; DataRep=varargin{1}; skel=varargin{3}; readSkel=false; otherwise disp('Wrong number of arguments'); end if readSkel skel = readASF(Tensor.skeletons{1,1}); end % if(setx0) % lb= min(x0)*ones(1,n); % ub= max(x0)*ones(1,n); % else lb=-inf(1,n); ub= inf(1,n); % end % % fprintf('\nlower bound x0 upper bound\n'); % disp([lb' x0' ub']); tmpTensor=Tensor; tmpTensor.core=core_tmp; tmpTensor.rootcore=root_tmp; [X,RESNORM,RESIDUAL] = ... lsqnonlin(@(x) ... objfunCol( x,tmpTensor,newMot, ... nrOfNaturalModes,nrOfTechnicalModes,... dimvec,skel,DataRep) ... ,x0,lb,ub,options); % dim=size(Tensor.core); % dim= dim(Tensor.numTechnicalModes+1:size(dim,2)); % Y=getRowCoefficients(Tensor,vectorToCellArray(X,dim));
github
umariqb/3D_Pose_Estimation_CVPR2016-master
modeNproduct.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/modeNproduct.m
868
utf_8
16282f02ba80f7e0494e84e44239a479
% modeNproduct % computes the mode-n-product T x_n M % i.e. T x_n M replaces every mode-n-vector v of T by the product Mv % example: result = modeNproduct(tensor,matrix,3); % with tensor (n1 x n2 x n3 x ... x n) and matrix (m x n3) % author: Jochen Tautges ([email protected]) function result = modeNproduct(Tensor,Matrix,n) if size(Matrix)==1 result=Tensor*Matrix; else nd=ndims(Tensor); dim=size(Tensor); if nd<n nd=nd+1; dim=[dim 1]; end order=n:n+nd-1; order=order-(order>nd)*nd; dim2=dim; dim2(n)=size(Matrix,1); Tensor = permute(Tensor,order); dim = dim(order); dim(1) = size(Matrix,1); result = Matrix*Tensor(:,:); result = reshape(result,dim); result = ipermute(result,order); result = reshape(result,dim2); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
findCoefficients.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/findCoefficients.m
3,421
utf_8
7854c4bfa177d799469f1223ef221752
% FUNCTION findCoefficients searches for optimal coefficients to % reconstruct a given motion out of a given tensor. It uses the Matlab % Optimization Toolbox. % INPUT: % Tensor: struct: containing data, core, matrices. % newMot: struct: the motion that should be reconstructed. % varargin{1}: string: Type of data Representation 'Quat' or 'Position' % varargin{2}: cell of arrays: Start values for optimization values % have to correspond to the number of natural and % technical modes. % % OUTPUT: % X: cell array: coefficients found for best solution % Y: cell array: X normalized to length 1 % mot: struct: motion reconstructed with X % d: float: distance, correponding to the used distance % measure between mot and newMot. function [X] = findCoefficients(Tensor,newMot,varargin) % Align first new Motion like all others! [skel,fitmot]=reconstructMotionT(Tensor,[1 1]); skel = readASF(Tensor.skeletons{1,1}); newMot=fitMotion(skel,newMot); % Timewarp motion [newMot]=SimpleDTW(fitmot,skel,newMot); nrOfTechnicalModes=3; nrOfNaturalModes=ndims(Tensor.core)-nrOfTechnicalModes; % Compute mode-n-product of core tensor and all matrices related to % technical modes core_tmp=Tensor.core; for i=1:nrOfTechnicalModes core_tmp=modeNproduct(core_tmp,Tensor.factors{i},i); end root_tmp=Tensor.rootcore; for i=1:nrOfTechnicalModes-1 root_tmp=modeNproduct(root_tmp,Tensor.rootfactors{i},i); end % Set options for optimization options = optimset('Display','iter','MaxFunEvals',2500,'MaxIter',500); % Set lower and upper bounds for optimization variable x dimvec=size(core_tmp); n=sum(dimvec(nrOfTechnicalModes+1:end)); lb=-0.5*ones(1,n); ub= 1.5*ones(1,n); % Define used representation of motion data within the Tensor and % define starting guess x0 if not set by user (through varargin) x0=0; for i=1:nrOfNaturalModes for j=1:dimvec(nrOfTechnicalModes+i) x0=[x0 1/dimvec(nrOfTechnicalModes+i)]; end end x0=x0(2:end); switch nargin case 2 DataRep='Quat'; case 3 DataRep=varargin{1}; case 4 x0=varargin{2}; DataRep=varargin{1}; otherwise disp('Wrong number of arguments'); end fprintf('\nlower bound x0 upper bound\n'); disp([lb' x0' ub']); tmpTensor=Tensor; tmpTensor.core=core_tmp; tmpTensor.rootcore=root_tmp; [Y,RESNORM,RESIDUAL] = ... lsqnonlin(@(x) ... objfun( x,tmpTensor,newMot, ... nrOfNaturalModes,nrOfTechnicalModes,... dimvec,skel,DataRep) ... ,x0,lb,ub,options); % Show computed coefficients for i=1:nrOfNaturalModes X{i}=Y(1:dimvec(i+nrOfTechnicalModes)); % X2{i}=round(X{i}); Y=Y(dimvec(i+nrOfTechnicalModes)+1:size(Y,2)); end % Construct motion with computed coefficients and compute mean error % [skel ,mot] =constructMotion(Tensor,X,skel,DataRep); % [skel2,mot2]=constructMotion(Tensor,X2); % d =compareMotions(mot, newMot,DataRep); % d2=compareMotions(mot2,newMot); % if d2<d % X=X2; % d=d2; % mot=mot2; % end for i=1:nrOfNaturalModes fprintf('\n X{%i}\n',i); disp(X{i}'); end % fprintf('Mean error of joint orientations: E = %.3f degrees.\n',d);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
findCoefficientsBruteForce.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/findCoefficientsBruteForce.m
5,270
utf_8
b1834d9e2999fbb6b2eb8182380f1cfb
% FUNCTION findCoefficients searches for optimal coefficients to % reconstruct a given motion out of a given tensor. It uses the Matlab % Optimization Toolbox. % INPUT: % Tensor: struct: containing data, core, matrices. % newMot: struct: the motion that should be reconstructed. % varargin{1}: string: Type of data Representation 'Quat' or 'Position' % varargin{2}: cell of arrays: Start values for optimization values % have to correspond to the number of natural and % technical modes. % % OUTPUT: % X: cell array: coefficients found for best solution % Y: cell array: X normalized to length 1 % mot: struct: motion reconstructed with X % d: float: distance, correponding to the used distance % measure between mot and newMot. function [X,dist] = findCoefficientsBruteForce(Tensor,newMot,varargin) % Align first new Motion like all others! [skel,fitmot]=reconstructMotionT(Tensor,[1 1]); skel = readASF(Tensor.skeletons{1,1}); newMot=fitMotion(skel,newMot); % Timewarp motion [newMot]=SimpleDTW(fitmot,skel,newMot); nrOfTechnicalModes=3; nrOfNaturalModes=ndims(Tensor.core)-nrOfTechnicalModes; % Compute mode-n-product of core tensor and all matrices related to % technical modes core_tmp=Tensor.core; for i=1:nrOfTechnicalModes core_tmp=modeNproduct(core_tmp,Tensor.factors{i},i); end root_tmp=Tensor.rootcore; for i=1:nrOfTechnicalModes-1 root_tmp=modeNproduct(root_tmp,Tensor.rootfactors{i},i); end % Set options for optimization % options = optimset('Display','iter','MaxFunEvals',10000); % Set lower and upper bounds for optimization variable x dimvec=size(core_tmp); % n=sum(dimvec(nrOfTechnicalModes+1:end)); % lb=-2*ones(1,n); % ub=2*ones(1,n); % Define used representation of motion data within the Tensor and % define starting guess x0 if not set by user (through varargin) % x0=0; % for i=1:nrOfNaturalModes % for j=1:dimvec(nrOfTechnicalModes+i) % x0=[x0 1/dimvec(nrOfTechnicalModes+i)]; % end % end % x0=x0(2:end); switch nargin case 2 DataRep='Quat'; case 3 DataRep=varargin{1}; case 4 x0=varargin{2}; DataRep=varargin{1}; otherwise disp('Wrong number of arguments'); end % fprintf('\nlower bound x0 upper bound\n'); % disp([lb' x0' ub']); tmpTensor=Tensor; tmpTensor.core=core_tmp; tmpTensor.rootcore=root_tmp; X=zeros(1,8); dist=inf(1,1); tmp2=inf(1,1); fprintf('\n'); for c=1:35 fprintf(' '); end for x1=1:11 for x2=1:11 % for x3=1:11 % for x4=1:11 % for x5=1:11 for x6=1:11 for x7=1:11 % for x8=1:11 x0(1)=x1/10-0.1; x0(2)=x2/10-0.1; x0(3)=0;%x3/10-0.1; x0(4)=0;%x4/10-0.1; x0(5)=0;%x5/10-0.1; x0(6)=x6/10-0.1; x0(7)=x7/10-0.1; x0(8)=0;%x8/10-0.1; for c=1:35 fprintf('\b'); end fprintf('x0= %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f %1.1f', ... x0(1),x0(2),x0(3),x0(4),x0(5),x0(6),x0(7),x0(8)) tmp= objfun(x0,tmpTensor,newMot, ... nrOfNaturalModes, ... nrOfTechnicalModes,... dimvec,skel,DataRep); tmp2=sum(tmp(:).*tmp(:)); if(tmp2<dist) dist=tmp2 X=x0 fprintf('\n'); for c=1:35 fprintf(' '); end end % end end end % end % end % end end end % Show computed coefficients % for i=1:nrOfNaturalModes % X{i}=Y(1:dimvec(i+nrOfTechnicalModes)); % % X2{i}=round(X{i}); % Y=Y(dimvec(i+nrOfTechnicalModes)+1:size(Y,2)); % end % Construct motion with computed coefficients and compute mean error % [skel ,mot] =constructMotion(Tensor,X,skel,DataRep); % [skel2,mot2]=constructMotion(Tensor,X2); % d =compareMotions(mot, newMot,DataRep); % d2=compareMotions(mot2,newMot); % if d2<d % X=X2; % d=d2; % mot=mot2; % end % % for i=1:nrOfNaturalModes % Y{i}=X{i}/(sqrt(sum(X{i}.*X{i}))); % fprintf('\n Y{%i}\n',i); % disp(Y{i}'); % end % fprintf('Mean error of joint orientations: E = %.3f degrees.\n',d);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
findCoefficientsColumnRoot.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/findCoefficientsColumnRoot.m
3,148
utf_8
911d39058f655f579d6f39d1d8de486e
% FUNCTION findCoefficients searches for optimal coefficients to % reconstruct a given motion out of a given tensor. It uses the Matlab % Optimization Toolbox. % INPUT: % Tensor: struct: containing data, core, matrices. % newMot: struct: the motion that should be reconstructed. % varargin{1}: string: Type of data Representation 'Quat' or 'Position' % varargin{2}: cell of arrays: Start values for optimization values % have to correspond to the number of natural and % technical modes. % % OUTPUT: % X: cell array: coefficients found for best solution % Y: cell array: X normalized to length 1 % mot: struct: motion reconstructed with X % d: float: distance, correponding to the used distance % measure between mot and newMot. function [X,Y] = findCoefficientsColumnRoot(Tensor,newMot,varargin) % Align first new Motion like all others! % [skel,fitmot]=reconstructMotionT(Tensor,[1 1 1]); skel = readASF(Tensor.skeletons{1,1}); newMot=fitMotion(skel,newMot); % Timewarp motion %[newMot]=SimpleDTW(fitmot,skel,newMot); nrOfTechnicalModes=Tensor.numTechnicalModes-1; nrOfNaturalModes =Tensor.numNaturalModes; for i=1:5%nrOfTechnicalModes-1 Tensor.rootcore=modeNproduct(Tensor.rootcore,Tensor.rootfactors{i},i); end iter=20000; % Set options for optimization options = optimset('Display','iter','MaxFunEvals',iter*5,'MaxIter',iter,'TolFun',1e-3); % Set lower and upper bounds for optimization variable x dimvec=Tensor.dimNaturalModes; n=sum(dimvec(nrOfTechnicalModes:end)); % lb=-0.5*ones(1,n); % ub= 1.5*ones(1,n); % Define used representation of motion data within the Tensor and % define starting guess x0 if not set by user (through varargin) x0=0; for i=1:nrOfNaturalModes for j=1:dimvec(i) x0=[x0 1/dimvec(i)]; end end x0=x0(2:end); % x0=[]; % for i=1:nrOfNaturalModes % y0=[]; % for j=1:dimvec(i) % y0=[y0 1/dimvec(i)]; % end % x0=[x0 (Tensor.factors{nrOfTechnicalModes+i}'*y0')']; % end setx0=false; switch nargin case 2 DataRep='Quat'; case 3 DataRep=varargin{1}; case 4 x0=varargin{2}; setx0=true; DataRep=varargin{1}; otherwise disp('Wrong number of arguments'); end % if(setx0) % lb= min(x0)*ones(1,n); % ub= max(x0)*ones(1,n); % else lb=-inf(1,n); ub= inf(1,n); % end % % fprintf('\nlower bound x0 upper bound\n'); % disp([lb' x0' ub']); %tmpTensor=Tensor; %tmpTensor.rootcore=root_tmp; [X,RESNORM,RESIDUAL] = ... lsqnonlin(@(x) ... objfunColRoot( x,Tensor,newMot, ... nrOfNaturalModes, ... nrOfTechnicalModes,... dimvec,skel,DataRep), ... x0,lb,ub,options); dim= size(Tensor.rootcore); dim= dim (Tensor.numTechnicalModes+1:size(dim,2)); Y=getRowCoefficients(Tensor,X);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
reconstructMotionCut.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/reconstructMotionCut.m
3,317
utf_8
6be9dfe9d14bb5f985dc1e5f70d1332a
function resultX=reconstructMotionCut(skel,mot,tensors) mot=changeFrameRate(skel,mot,30); info=filename2info(mot.filename); styles{1}=info.motionCategory; % styles{2}=info.motionCategory; TensorID=findTensorForStyles(styles,tensors); % for subClassInd=1:tensors{TensorID}.dimNaturalModes(1) tensors{TensorID}.addSkel=skel; [fitSkel, fitMot] = extractMotion(tensors{TensorID}, ... tensors{TensorID}.DTW.refMotID); [gdm, warpPath, ldm] = pointCloudDTW_pos(fitMot, mot, 2); segMot=warpMotion(warpPath,skel,mot); % % % ldm = ldm/max(ldm(:)); % % % % % % parameter.vis = 0; % % % % % % % Anpassen!!! % % % % % % parameter.match_thresh = 0.5*fitMot.nframes; % % % % % % parameter.match_endExclusionForward = 1; % % % parameter.match_startExclusionBackward = 1; % % % % % % hits = retrieveSubsequenceDTWHits(ldm, parameter); % fprintf('\n\n\nSubsequence DTW found %i Hits!\n\n\n', size(hits,2)); recCount=0; % for hitInd=1:size(hits,2) % plotDTWpathNice(ldm,flipud(hits(1, hitInd).match')); % drawnow(); % warpPath = convertWarpingPath(flipud(hits(1, hitInd).match')); % segMot = warpMotion(warpPath,skel,mot); segMot = fitMotion(skel, segMot); set = defaultSet_eg08; set.windowLength = segMot.nframes; set.warping = 0; recCount = recCount + 1; resultX{recCount} = emptyResultStruct(); resultX{recCount}.amc = fullfile(info.amcpath,info.amcname); resultX{recCount}.asf = info.asfname; resultX{recCount}.startFrame = 1;%hits(1, hitInd).frame_first_matched; resultX{recCount}.endFrame = mot.nframes;%hits(1, hitInd).frame_last_matched; resultX{recCount}.motionClass = styles; resultX{recCount}.styles = tensors{TensorID}.styles; resultX{recCount}.orgMot = mot;% warpMotion(convertWarpingPath(fliplr(flipud(hits(1, hitInd).match'))),skel,segMot); fprintf('\nReconstruction { %i } :\n\n',recCount); resultX{recCount}.res = recMot_eg08(tensors{TensorID},skel,segMot,set); resultX{recCount}.distUnWarp = compareMotions_eg08(resultX{recCount}.res.origMot,resultX{recCount}.res.recMot); resultX{recCount}.recMotUnWarp = warpMotion(fliplr(warpPath),skel,resultX{recCount}.res.recMot); resultX{recCount}.distUnWarp = compareMotions_eg08(resultX{recCount}.orgMot,resultX{recCount}.recMotUnWarp); end % end % end function listOfTensors = findTensorForStyles(styles, tensors) listOfTensors=[]; for tensorID=1:size(tensors,2) positions=0; for styleID=1:size(tensors{tensorID}.styles,2) findres=cell2mat(strfind(styles,tensors{tensorID}.styles{styleID})); if ~isempty(findres) positions=positions+findres; end end if positions>0 listOfTensors=[listOfTensors tensorID]; end end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
buildTensorFromDir.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/buildTensorFromDir.m
3,528
utf_8
904870213c131d96a7c4f53dffa8f61e
function [Tensor]=buildTensorFromDir(p) % Creates a motion tensor from a given Directory of our MocapDB % All motions in a given directory are warped and put into the tensor. % The reference motion is allways the first motion in dir. % author: Bjoern Krueger ([email protected]) %% Check if Backslash is included in path and append extension. dim=size(p); if(p(dim(2))~='\') p=[p '\']; end ext='*.amc'; %% Get List of files files=dir([p ext]); dim=size(files); %% Collect Information about the given Files % We need the number of actors, minimum of repetitions % This are information about the dimension of the % resulting tensor. % Known Actors: bd,bk,mm,dg,tr actors{1}='HDM_bd'; actors{2}='HDM_bk'; actors{3}='HDM_dg'; actors{4}='HDM_mm'; actors{5}='HDM_tr'; %Count repetitions of each actor reps(1)=countActor(files,actors{1}); reps(2)=countActor(files,actors{2}); reps(3)=countActor(files,actors{3}); reps(4)=countActor(files,actors{4}); reps(5)=countActor(files,actors{5}); if (min(reps)==0) [numReps,I]=min(reps); reps(I)=max(reps); numReps=min(reps); else numReps=min(reps); end %% Start reading information rep=1; actor=1; % Motions to fit by DTW skelfile=[p actors{1} '.asf']; motfile =[p files(1).name]; [fitskel,fitmot]=readMocap(skelfile,motfile); fprintf('fitmot: '); fprintf([files(1).name '\n']) fitmot=reduceFrameRate(fitskel,fitmot); Tensor.data=NaN(4,fitmot.nframes,fitmot.njoints,size(actors,2),numReps); fprintf('Motion '); % Go through all files for file=1:dim(1) fprintf('\b\b\b'); fprintf('%2i ',file); % Check if motion has to be read if(actor<=size(actors,2)) correctActor=strfind(files(file).name,actors{actor}); else correctActor=0; end if(isempty(correctActor)) correctActor=0; end if ((rep<=numReps)&&correctActor==1) % read motion fprintf('Read '); skelfile=[p actors{actor} '.asf']; motfile=[p files(file).name]; fprintf(files(file).name); [skel,mot]=readMocap(skelfile,motfile); mot=reduceFrameRate(skel,mot); % Timewarp motion for c=1:size(files(file).name,2) fprintf('\b'); end fprintf('\b\b\b\b\bWarp'); [mot]=SimpleDTW(fitmot,skel,mot); % Fill warped motion into tensor Tensor.motions{actor,rep}=motfile; for joint=1:mot.njoints Tensor.joints{joint,actor,rep}=mot.jointNames{joint}; if(~isempty(mot.rotationQuat{joint})) Tensor.data(:,:,joint,actor,rep)=mot.rotationQuat{joint}; else Tensor.data(1,:,joint,actor,rep) =ones (1,mot.nframes); Tensor.data(2:4,:,joint,actor,rep)=zeros(3,mot.nframes); end end rep=rep+1; fprintf('\b\b\b\b'); else actor=actor+1; rep=1; end end fprintf('\n'); end function num=countActor(files,actor) LoFN=[files(:).name]; tmp=size(strfind(LoFN,actor)); num=tmp(2); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
buildTensorFromDir2.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/buildTensorFromDir2.m
5,307
utf_8
9e9cd9ad5ec40658a7c6a9c508f9cc8c
function [Tensor]=buildTensorFromDir2(p,varargin) % Creates a motion tensor from a given Directory of our MocapDB % All motions in a given directory are warped and put into the tensor. % The reference motion is allways the first motion in dir. % author: Bjoern Krueger ([email protected]) %% Check if Backslash is included in path and append extension. dim=size(p); if(p(dim(2))~='\') p=[p '\']; end ext='*.amc'; %% Get List of files files=dir([p ext]); dim=size(files); %% Collect Information about the given Files % We need the number of actors, minimum of repetitions % This are information about the dimension of the % resulting tensor. % Known Actors: bd,bk,mm,dg,tr actors{1}='HDM_bd'; actors{2}='HDM_bk'; actors{3}='HDM_dg'; actors{4}='HDM_mm'; actors{5}='HDM_tr'; %Count repetitions of each actor reps(1)=countActor(files,actors{1}); reps(2)=countActor(files,actors{2}); reps(3)=countActor(files,actors{3}); reps(4)=countActor(files,actors{4}); reps(5)=countActor(files,actors{5}); % If there is a maximum of Reps definied us it, otherwise use all % motions. ! Can result in a lot of NaN's. switch nargin case 1 maxRep =max(reps); dataRep='Quat'; case 2 maxRep=varargin{1}; dataRep='Quat'; case 3 maxRep=varargin{1}; dataRep=varargin{2}; otherwise error('Wrong number of Args'); end switch dataRep case 'Quat' dimDataRep=4; case 'Position' dimDataRep=3; case 'ExpMap' dimDataRep=3; otherwise error('buildTensorFromDir2: Wrong Date specified in var: dataRep'); end % Motions to fit by DTW skelfile=[p actors{1} '.asf']; motfile =[p files(1).name]; [fitskel,fitmot]=readMocap(skelfile,motfile); fprintf('fitmot: '); fprintf([files(1).name '\n']) fitmot=reduceFrameRate(fitskel,fitmot); % Allocate memory for Tensor Tensor.data=NaN(dimDataRep,fitmot.nframes,fitmot.njoints,size(actors,2),maxRep); rep=1; actor=1; fprintf(' '); file=1; % Run throgh list of files while (file<dim(1)) % for file=1:dim(1) if(actor<=size(actors,2)) if(rep<=reps(actor)&&rep<=maxRep) %Load motion fprintf('\b\b\b\bRead '); skelfile=[p actors{actor} '.asf']; motfile=[p files(file).name]; fprintf(files(file).name); [skel,mot]=readMocap(skelfile,motfile); % Reduce frame rate mot=reduceFrameRate(skel,mot); % fit motion mot=fitMotion(skel,mot); % Timewarp motion for c=1:size(files(file).name,2) fprintf('\b'); end fprintf('\b\b\b\b\bWarp'); [mot]=SimpleDTW(fitmot,skel,mot); % Fill warped motion into tensor Tensor.motions{actor,rep}=motfile; Tensor.skeletons{actor,rep}=skelfile; Tensor.rootdata(:,:,actor,rep)=mot.rootTranslation; for joint=1:mot.njoints Tensor.joints{joint,actor,rep}=mot.jointNames{joint}; switch dataRep case 'Quat' if(~isempty(mot.rotationQuat{joint})) Tensor.data(:,:,joint,actor,rep)=mot.rotationQuat{joint}; else Tensor.data(1,:,joint,actor,rep) =ones (1,mot.nframes); Tensor.data(2:4,:,joint,actor,rep)=zeros(3,mot.nframes); end case 'Position' if(~isempty(mot.jointTrajectories{joint})) Tensor.data(:,:,joint,actor,rep)=mot.jointTrajectories{joint}; else Tensor.data(1:3,:,joint,actor,rep)=zeros(3,mot.nframes); end case 'ExpMap' if(~isempty(mot.rotationQuat{joint})) Tensor.data(:,:,joint,actor,rep)=quatlog(mot.rotationQuat{joint}); else Tensor.data(1:3,:,joint,actor,rep)=zeros(3,mot.nframes); end otherwise error('buildTensorFromDir2: Wrong Date specified in var: dataRep'); end end rep=rep+1; file=file+1; else actor=actor+1; rep=1; % file=file-1; end else file=file+1; end end fprintf('\b\b\b\b'); end function num=countActor(files,actor) LoFN=[files(:).name]; tmp=size(strfind(LoFN,actor)); num=tmp(2); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
reconstructMotionT.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/reconstructMotionT.m
1,907
utf_8
9b107df5e11c2c5d4f447ca3b818680a
% function reconstructMotion % reconstructs/approximates an original motion from a given core tensor of % arbitrary order and related matrices (obtained by HOSVD) % recMotion = reconstructMotion(core,factors,rows,varargin) % % example: reconstructMotion(Tensor,[2,2,1]) for 3 natural modes % % Remark: Use the tucker function from the n-way toolbox to perform HOSVD % and to obtain core and factors: % [factors,core] = tucker(Tensor, [n1 n2 n3 ... n_m]), % with Tensor being of m-th order % type "help tucker" for more information function [skel,mot] = reconstructMotionT(Tensor,rows,varargin) DataRep=Tensor.DataRep; skel = readASF(Tensor.skeletons{rows(1),rows(2),1}); nrOfDim = size(Tensor.factors,2); nrOfNaturalModes = size(rows,2); nrOfTechnicalModes = nrOfDim-nrOfNaturalModes; nrOfDimRoot = size(Tensor.rootfactors,2); nrOfTechnicalModesRoot = nrOfDimRoot-nrOfNaturalModes; for i=1:nrOfTechnicalModes Tensor.core = modeNproduct(Tensor.core,Tensor.factors{i},i); end for i=1:nrOfTechnicalModesRoot Tensor.rootcore = modeNproduct(Tensor.rootcore,Tensor.rootfactors{i},i); end for i=nrOfDim:-1:nrOfTechnicalModes+1 Tensor.data = modeNproduct(Tensor.core,Tensor.factors{i}(rows(i-nrOfTechnicalModes),:),i); end for i=nrOfDimRoot:-1:nrOfTechnicalModesRoot+1 Tensor.rootcore = modeNproduct(Tensor.rootcore,Tensor.rootfactors{i}(rows(i-nrOfTechnicalModesRoot),:),i); end mot=createMotionFromCoreTensor(Tensor,skel,true,true,DataRep); % dims=size(Tensor.core); % mot = emptyMotion; % % mot.njoints=dims(3); % mot.nframes=dims(2); % % mot.rootTranslation=Tensor.rootcore(:,:); % % for joint=1:mot.njoints % mot.rotationQuat{1,joint}=Tensor.core(:,:,joint); % end % % mot.samplingRate=30; % mot.frameTime=1/30; % mot.jointTrajectories = forwardKinematicsQuat(skel,mot); % mot.boundingBox = computeBoundingBox(mot);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
reconstructMotion6D.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/reconstructMotion6D.m
1,499
utf_8
802c28399e1376e0256b07775247fcf8
% function reconstructMotion % reconstructs/approximates an original motion from a given core tensor of % arbitrary order and related matrices (obtained by HOSVD) % recMotion = reconstructMotion(core,factors,rows,varargin) % % example: reconstructMotion(Tensor,[2,2,1]) for 3 natural modes % % Remark: Use the tucker function from the n-way toolbox to perform HOSVD % and to obtain core and factors: % [factors,core] = tucker(Tensor, [n1 n2 n3 ... n_m]), % with Tensor being of m-th order % type "help tucker" for more information function [skel,mot] = reconstructMotion6D(Tensor,rows,varargin) skel = readASF(Tensor.skeletons{rows(1),rows(2),1}); nrOfDim = Tensor.numNaturalModes+Tensor.numTechnicalModes; nrOfNaturalModes = Tensor.numNaturalModes; nrOfTechnicalModes = Tensor.numTechnicalModes; nrOfDimRoot = size(Tensor.rootfactors,2); nrOfTechnicalModesRoot = nrOfDimRoot-nrOfNaturalModes; for i=1:nrOfTechnicalModes Tensor.core = modeNproduct(Tensor.core,Tensor.factors{i},i); end for i=1:nrOfTechnicalModesRoot Tensor.rootcore = modeNproduct(Tensor.rootcore,Tensor.rootfactors{i},i); end for i=nrOfTechnicalModes+1:nrOfDim Tensor.core = modeNproduct(Tensor.core,Tensor.factors{i}(rows(i-nrOfTechnicalModes),:),i); end for i=nrOfTechnicalModes:nrOfDim-1 Tensor.rootcore = modeNproduct(Tensor.rootcore,Tensor.rootfactors{i}(rows(i-nrOfTechnicalModesRoot),:),i); end mot=createMotionFromCoreTensor(Tensor,skel,true,true,'ExpMap');
github
umariqb/3D_Pose_Estimation_CVPR2016-master
compareMotions.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/compareMotions.m
9,628
utf_8
2f1c2b1282b0d03b31ea9c4922351fbd
% FUNCTION compareMotions compares to given motions. It returns a matrix of % distances for joints(rows) and frames(columns). % INPUT: % mot: struct: motion % mot1: struct: motion that shold be compared to mot % varargin{1}: string: Defines which distance measurement should % be used. % % OUTPUT: % result: matrix: containig distances for every joint for every % frame. Most optimization tools from Matlabs % Optimization Toolbox can use this and make summation % and calculating squares implicit. function result=compareMotions(mot,mot1,varargin) existSkel=false; plotSteps=true; switch nargin case 2 dataRep='Quat'; case 3 dataRep=varargin{1}; case 4 dataRep=varargin{1}; skel =varargin{2}; existSkel=true; case 5 dataRep=varargin{1}; skel =varargin{2}; existSkel=true; plotSteps=varargin{3}; otherwise error('compareMotions: Wrong number of arguments!\n'); end % result=zeros(mot.nframes,mot.njoints); switch dataRep case 'Quat' for i=2:mot.njoints % result(:,i)=QuatDistRot(i,mot,mot1); % result(:,i)=QuatDistAxisJoint(i,mot,mot1); result(:,i)=QuatDist(i,mot,mot1); % result(:,i)=QuatDistAbs(i,mot,mot1); % resultP(:,i)=PosDist(i,mot,mot1); end case 'Position' for i=2:mot.njoints result(:,i)=PosDist(i,mot,mot1); end if plotSteps plot3(mot1.jointTrajectorie{5}','.'); hold on; plot3( mot.jointTrajectorie{5}'); hold off; drawnow(); end case 'ExpMap' for i=[3 8 19 26]%[2:4 7:9 12:14 18:21 25:28] result(:,i)=QuatDistRot(i,mot,mot1); end if plotSteps subplot(2,1,1) plot(mot1.rotationQuat{4}','.'); hold on; plot( mot.rotationQuat{4}'); hold off; axis([0 mot.nframes -0.5 1.2]) subplot(2,1,2) plot(mot1.rotationQuat{20}','.'); hold on; plot( mot.rotationQuat{20}'); hold off; axis([0 mot.nframes -0.5 1.2]) drawnow(); % I = getframe(gcf); % imwrite(I.cdata, ['c:\opt_vid\opt_' datestr(now, 30) '.png']); end case 'jointAngle' if existSkel JointAngles1 = dataAcquisition(skel, mot, selectFeatures('jointAngle'),false); JointAngles2 = dataAcquisition(skel, mot1, selectFeatures('jointAngle'),false); tmp = abs(JointAngles1-JointAngles2); if plotSteps plot(JointAngles2','.'); hold on; plot( JointAngles1'); hold off; axis([0 mot.nframes 0 pi]) drawnow(); end result = tmp.*tmp; else error(['compareMotions: if jointAngles are compared a '... 'skeleton should be given!\n']); end case 'Acce' mot =addAccToMot(mot); mot1=addAccToMot(mot1); counter=0; % for j=1:dimTechnicalModes(3) % for j=[5,10,15,22,29] for j=1:30 for i=1:size(mot.jointAccelerations{j},2) counter=counter+1; m {counter,1}=mot .jointAccelerations{j}(:,i); mRec{counter,1}=mot1.jointAccelerations{j}(:,i); end end result=distVector_pointCloudDistance(m,mRec,0); if plotSteps subplot(2,1,1); joint=5; plot( mot.jointAccelerations{joint}'); hold on; plot( mot1.jointAccelerations{joint}','.'); boxsize=2000; axis([0 mot.nframes -boxsize boxsize]); hold off; subplot(2,1,2); joint=20; plot( mot.jointAccelerations{joint}'); hold on; plot( mot1.jointAccelerations{joint}','.'); boxsize=2000; axis([0 mot.nframes -boxsize boxsize]); hold off; drawnow; end otherwise error('compareMotions: Wrong type of Data specified in var: dataRep\n'); end end function res=QuatDistRot(i,mot,mot1) res=zeros(mot.nframes,1); if(~isempty(mot.rotationQuat{i})&&~isempty(mot1.rotationQuat{i})) res=distS3(mot.rotationQuat{i},mot1.rotationQuat{i},0.001); end end function res=QuatDistAxisJoint(i,mot,mot1) res=zeros(mot.nframes,1); if(~isempty(mot.rotationQuat{i})&&~isempty(mot1.rotationQuat{i})) smo=size(mot.rotationQuat{i},2); sm1=size(mot1.rotationQuat{i},2); if(sm1<smo) smo=sm1; end rot=acosd(mot.rotationQuat{i}(1,1:smo))-real(acos(mot1.rotationQuat{i}(1,1:smo))); rotR=abs(real(rot)); % rotI=abs(imag(rot)); % rot=abs(acos(mot.rotationQuat{i}(1,1:smo))*2-acos(mot1.rotationQuat{i}(1,1:smo))*2); x1=mot.rotationQuat{i}(2:4,1:smo); x2=mot1.rotationQuat{i}(2:4,1:smo); for i=1:size(x1,2) if(norm(x1(:,i))>0) x1(:,i)=x1(:,i)/norm(x1(:,i)); end if(norm(x2(:,i))>0) x2(:,i)=x2(:,i)/norm(x2(:,i)); end end angR=(1-dot(x1,x2))*180/pi; % angI=1-dot(imag(x1),imag(x2)); % ang=1-dot(mot.rotationQuat{i}(2:4,1:smo),mot1.rotationQuat{i}(2:4,1:smo)); res=rotR+angR;%+rotI+angI; end end function res=PosDist(i,mot,mot1) res=zeros(mot.nframes,1); if(~isempty(mot.jointTrajectories{i})&&~isempty(mot1.jointTrajectories{i})) smo=size(mot.jointTrajectories{i},2); sm1=size(mot1.jointTrajectories{i},2); if(sm1<smo) smo=sm1; end res=abs(mot.jointTrajectories{i}(1,1:smo)-mot1.jointTrajectories{i}(1,1:smo))'; end end function res=QuatDist(i,mot,mot1) res=zeros(mot.nframes,1); if(~isempty(mot.rotationQuat{i})&&~isempty(mot1.rotationQuat{i})) smo=size(mot.rotationQuat{i},2); sm1=size(mot1.rotationQuat{i},2); if(sm1<smo) smo=sm1; end res=1-dot(mot.rotationQuat{i}(:,1:smo),mot1.rotationQuat{i}(:,1:smo)); end end function res=QuatDistAbs(i,mot,mot1) res=zeros(mot.nframes,1); if(~isempty(mot.rotationQuat{i})&&~isempty(mot1.rotationQuat{i})) smo=size(mot.rotationQuat{i},2); sm1=size(mot1.rotationQuat{i},2); if(sm1<smo) smo=sm1; end res=sum(abs(mot.rotationQuat{i}(:,1:smo)-mot1.rotationQuat{i}(:,1:smo)),1); end end function res=QuatDistJochen(mot1,mot2) % = compareMotions_jt for i=1:mot1.njoints if (~(isempty(mot1.rotationQuat{i})) && ~(isempty(mot2.rotationQuat{i}))) res(i,1) = mean(real(acosd(dot(mot1.rotationQuat{i},mot2.rotationQuat{i}))*2)); end end end % result=sum(result,2)/mot.njoints; %fprintf('r= %3.3f\n',result); %Code-Halde: % for i=2:mot.njoints % if(~isempty(mot.rotationQuat{i})&&~isempty(mot1.rotationQuat{i})) % smo=size(mot.rotationQuat{i},2); % sm1=size(mot1.rotationQuat{i},2); % if(sm1<smo) % smo=sm1; % end % % tmp=dot(mot.rotationQuat{i}(:,1:smo),mot1.rotationQuat{i}(:,1:smo)); % j=i*4-3; % motion1(:,j:j+3)= mot.rotationQuat{i}(:,1:smo)'; % motion2(:,j:j+3)=mot1.rotationQuat{i}(:,1:smo)'; % % result(i)=sum(tmp)/mot.nframes;%real(acosd(sum(tmp,2)/mot.nframes)); % % result(i)=real(acosd(sum(tmp,2)/mot.nframes)); % end % end % % frames=smo; % dofs=mot.njoints; % m=motion1.*motion2; % colsum=0; % for i=4:4:size(m,2)-3 % colsum=colsum+real(acosd(sum(m(:,i:i+3)')')*2); % end % result=sum(colsum)/(frames*dofs); % result(i)=sum(tmp)/mot.nframes; % tmp=dot(mot.rotationQuat{i}(:,1:smo),mot1.rotationQuat{i}(:,1:smo)); % tmp=(ones(size(tmp))-tmp); % % a=sqrt(sum(mot.rotationQuat{i}(:,1:smo).*mot.rotationQuat{i}(:,1:smo))); % % b=sqrt(sum(mot1.rotationQuat{i}(:,1:smo).*mot1.rotationQuat{i}(:,1:smo))); % % c=a.*b; % % tmp=tmp./c; % % tmp=real(acosd(tmp)); % result(i)=sum(tmp)/mot.nframes;%real(acosd(sum(tmp,2)/mot.nframes)); % % % tmp=abs(mot.rootTranslation-mot1.rootTranslation); % result=sum(tmp,2); % result = sum(dist)/(mot.nframes+mot.njoints); % result = result*result; %tmp=sum(tmp)/mot.nframes; %tmp=sum(tmp,1)/mot.njoints; % tmp=(ones(size(tmp))-tmp)*2; % result(i)=tmp/mot.nframes;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
findCoefficients6D.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/findCoefficients6D.m
3,799
utf_8
d1304249fe489a02f37a81ff7f9de89b
% FUNCTION findCoefficients searches for optimal coefficients to % reconstruct a given motion out of a given tensor. It uses the Matlab % Optimization Toolbox. % INPUT: % Tensor: struct: containing data, core, matrices. % newMot: struct: the motion that should be reconstructed. % varargin{1}: string: Type of data Representation 'Quat' or 'Position' % varargin{2}: cell of arrays: Start values for optimization values % have to correspond to the number of natural and % technical modes. % % OUTPUT: % X: cell array: coefficients found for best solution % Y: cell array: X normalized to length 1 % mot: struct: motion reconstructed with X % d: float: distance, correponding to the used distance % measure between mot and newMot. function [X] = findCoefficients6D(Tensor,newMot,varargin) % Align first new Motion like all others! % % [skel,fitmot]=reconstructMotionT(Tensor,[1 1 1]); % % skel = readASF(Tensor.skeletons{1,1}); % % newMot=fitMotion(skel,newMot); % % % Timewarp motion % % [newMot]=SimpleDTW(fitmot,skel,newMot); nrOfTechnicalModes=Tensor.numTechnicalModes; nrOfNaturalModes =Tensor.numNaturalModes; % Compute mode-n-product of core tensor and all matrices related to % technical modes core_tmp=Tensor.core; for i=1:nrOfTechnicalModes core_tmp=modeNproduct(core_tmp,Tensor.factors{i},i); end root_tmp=Tensor.rootcore; for i=1:nrOfTechnicalModes-1 root_tmp=modeNproduct(root_tmp,Tensor.rootfactors{i},i); end iter=500; % Set options for optimization options = optimset('Display','iter','MaxFunEvals',iter*12,'MaxIter',iter,'TolFun',1e-1); % Set lower and upper bounds for optimization variable x dimvec=size(core_tmp); n=sum(dimvec(nrOfTechnicalModes+1:end)); lb=-0.5*ones(1,n); ub= 1.5*ones(1,n); % Define used representation of motion data within the Tensor and % define starting guess x0 if not set by user (through varargin) x0=0; for i=1:nrOfNaturalModes for j=1:dimvec(nrOfTechnicalModes+i) x0=[x0 1/dimvec(nrOfTechnicalModes+i)]; end end x0=x0(2:end); setx0=false; switch nargin case 2 DataRep='Quat'; case 3 DataRep=varargin{1}; case 4 x0=varargin{2}; setx0=true; DataRep=varargin{1}; case 5 x0=varargin{2}; setx0=true; DataRep=varargin{1}; skel=varargin{3}; otherwise disp('Wrong number of arguments'); end % if(setx0) lb= -ones(1,n); ub= 2*ones(1,n); % else % lb=zeros(1,n); % ub= inf(1,n); % end fprintf('\nlower bound x0 upper bound\n'); disp([lb' x0' ub']); tmpTensor=Tensor; tmpTensor.core=core_tmp; tmpTensor.rootcore=root_tmp; [X,RESNORM,RESIDUAL] = ... lsqnonlin(@(x) ... objfun( x,tmpTensor,newMot, ... nrOfNaturalModes,nrOfTechnicalModes,... dimvec,skel,DataRep) ... ,x0,lb,ub,options); % Show computed coefficients % for i=1:nrOfNaturalModes % X{i}=Y(1:dimvec(i+nrOfTechnicalModes)); % % X2{i}=round(X{i}); % Y=Y(dimvec(i+nrOfTechnicalModes)+1:size(Y,2)); % end % % % Construct motion with computed coefficients and compute mean error % % [skel ,mot] =constructMotion(Tensor,X,skel,DataRep); % % [skel2,mot2]=constructMotion(Tensor,X2); % % % d =compareMotions(mot, newMot,DataRep); % % d2=compareMotions(mot2,newMot); % % % if d2<d % % X=X2; % % d=d2; % % mot=mot2; % % end % % for i=1:nrOfNaturalModes % fprintf('\n X{%i}\n',i); % disp(X{i}'); % end % fprintf('Mean error of joint orientations: E = %.3f degrees.\n',d);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
findCoefficientsModeSA.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/MMM/findCoefficientsModeSA.m
1,499
utf_8
d2e2bcde84272837a3364e6539d0ab3c
function [X]=findCoefficientsModeSA(Tensor,newMot) % Prepare Data for optimization: % Align first new Motion like all others! [skel,fitmot]=reconstructMotionT(Tensor,[1 1 1]); skel = readASF(Tensor.skeletons{1,1}); newMot=fitMotion(skel,newMot); % Timewarp motion [newMot]=SimpleDTW(fitmot,skel,newMot); nrOfTechnicalModes=Tensor.numTechnicalModes; nrOfNaturalModes=Tensor.numNaturalModes; % Compute mode-n-product of core tensor and all matrices related to % technical modes core_tmp=Tensor.core; for i=1:nrOfTechnicalModes core_tmp=modeNproduct(core_tmp,Tensor.factors{i},i); end root_tmp=Tensor.rootcore; for i=1:nrOfTechnicalModes-1 root_tmp=modeNproduct(root_tmp,Tensor.rootfactors{i},i); end dimvec=size(core_tmp); % Define used representation of motion data within the Tensor and % define starting guess x0 if not set by user (through varargin) x0=0; for i=1:nrOfNaturalModes for j=1:dimvec(nrOfTechnicalModes+i) x0=[x0 1/dimvec(nrOfTechnicalModes+i)]; end end x0=x0(2:end) X=Array2Cell(x0,nrOfNaturalModes,nrOfTechnicalModes); D=inf; time=0; tic; while((D>0.1)&&(time<30)) D=rand(1,1); time=toc; end end function [X]=Array2Cell(x0,nat,tec) for i=1:nat X{i}=x0(1:dimvec(i+tec)); x0=x0(dimvec(i+tec)+1:size(x0,2)); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
buildPCAMatrixFromDir.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/PCA/buildPCAMatrixFromDir.m
4,770
utf_8
297a15d203d30c5ca76eba4a932f4f77
function [Matrix] = buildPCAMatrixFromDir(p,varargin) switch nargin case 1 maxRep =3; dataRep='Quat'; Styles ={'walk4StepsRstart', ... 'walkLeftCircle4StepsRstart', ... 'walkRightCircle4StepsRstart'}; case 2 maxRep =varargin{1}; dataRep='Quat'; Styles ={'walk4StepsRstart', ... 'walkLeftCircle4StepsRstart', ... 'walkRightCircle4StepsRstart'}; case 3 maxRep =varargin{1}; dataRep=varargin{2}; Styles ={'walk4StepsRstart', ... 'walkLeftCircle4StepsRstart', ... 'walkRightCircle4StepsRstart'}; case 4 maxRep =varargin{1}; dataRep=varargin{2}; Styles =varargin{3}; otherwise error('Wrong number of Args'); end Matrix.DataRep=dataRep; % define size of representation: switch dataRep case 'Quat' dimDataRep=4; case 'Position' dimDataRep=3; case 'ExpMap' dimDataRep=3; case 'Acc' dimDataRep=3; otherwise error('buildPCAMatrixFromDir: Wrong Date specified in var: dataRep'); end % Check if Backslash is included in path and append extension: if(p(end)~=filesep) p=[p filesep]; end ext='*.amc'; % Check if there is a directory for every style: numStyles=size(Styles,2); for s=1:numStyles if(~exist([p Styles{1,s}],'dir')) error(['buildTensorStyleActRep_jt: Dir for Style ' Styles{1,s} ' does not exist!']); end end % Get Lists of files: for s=1:numStyles listofFiles{s}=dir([p Styles{1,s} filesep ext]); end % Known Actors: bd,bk,mm,dg,tr actors{1}='HDM_bd'; actors{2}='HDM_bk'; actors{3}='HDM_dg'; actors{4}='HDM_mm'; actors{5}='HDM_tr'; numActors=size(actors,2); for s=1:numStyles %Count repetitions of each actor for a=1:numActors reps(a,s)=countActor(listofFiles{s},actors{a}); end end Matrix.data =[]; Matrix.rootdata =[]; for s=1:numStyles file=1; for a=1:numActors for r=1:max(maxRep,reps(a,s)) if (r<=maxRep) fprintf('Loading motion %i%i%i - ',s,a,r); skelfile = fullfile(p, Styles{1,s}, [actors{a} '.asf']); motfile = fullfile(p, Styles{1,s}, listofFiles{s}(file).name); [skel,mot] = readMocap(skelfile,motfile); mot = changeFrameRate(skel,mot,30); mot = fitMotion(skel,mot); Matrix.rootdata = [Matrix.rootdata mot.rootTranslation]; mot=addAccToMot(mot); tmpMatrix=zeros(mot.njoints*dimDataRep,mot.nframes); for joint=1:mot.njoints % Tensor.joints{joint,s,a,r}=mot.jointNames{joint}; switch dataRep case 'Quat' if(~isempty(mot.rotationQuat{joint})) tmpMatrix(joint*4-3:joint*4,:)=mot.rotationQuat{joint}; else tmpMatrix(joint*4-3,:) = ones(1,mot.nframes); tmpMatrix(joint*4-2:joint*4,:)=zeros(3,mot.nframes); end case 'Position' error('Not implemented'); case 'ExpMap' if(~isempty(mot.rotationQuat{joint})) tmpMatrix(joint*3-2:joint*3,:)=quatlog(mot.rotationQuat{joint}); else tmpMatrix(joint*3-2:joint*3,:)=zeros(3,mot.nframes); end case 'Acc' tmpMatrix(joint*3-2:joint*3,:)=mot.jointAccelerations{joint}; otherwise error('buildTensorStyleActRep_jt: Wrong Type specified in var: dataRep\n'); end end Matrix.data=[Matrix.data tmpMatrix]; end if (r<reps(a,s)||r==max(maxRep,reps(a,s))) file=file+1; end end end end [Matrix.rootcoefs,Matrix.rootscores,Matrix.rootvariances,Matrix.roott2] = princomp(Matrix.rootdata'); [Matrix.coefs,Matrix.scores,Matrix.variances,Matrix.t2] = princomp(Matrix.data'); Matrix.mean =mean(Matrix.data,2); Matrix.rootmean=mean(Matrix.rootdata,2); Matrix.cov =cov(Matrix.data'); Matrix.rootCov =cov(Matrix.rootdata); Matrix.inv =pinv(Matrix.cov'); end function num=countActor(files,actor) LoFN=[files(:).name]; tmp=size(strfind(LoFN,actor)); num=tmp(2); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
precision_recall_diagram2.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/analytics/Retrieval/precision_recall_diagram2.m
4,877
utf_8
0707860911207e2bde51c2b2b4f364d4
function [ output_args ] = precision_recall_diagram2( DB_info, mClasses, results1, results2, recompute, m, n, tau1, tau2 ) dbs = dbstack; fullPath = dbs(1).name(1:max(strfind(dbs(1).name, '\'))); saveFileName = 'precision_recall_diagram_cache'; if ~iscell(mClasses) motionClasses{1} = mClasses; else motionClasses = mClasses; end if nargin > 3 if strfind(lower(inputname(3)), 'c3d') labelTxt1 = 'LCS'; elseif strfind(lower(inputname(3)), 'amc') labelTxt1 = 'ASF/AMC'; end if strfind(lower(inputname(4)), 'c3d') labelTxt2 = 'LCS'; elseif strfind(lower(inputname(4)), 'amc') labelTxt2 = 'ASF/AMC'; end end if nargin < 5 recompute = false; end if nargin < 6 b = length(motionClasses); m = floor(sqrt(b)); if m*m ~= b m = m + 1; end n = double(int32(b/m)); if mod(b,m)~=0 n = n + 1; end end if nargin < 8 tau1 = 0.02; tau2 = 1; end if recompute for i=1:length(motionClasses) motionClass = motionClasses{i}; disp(motionClass); % % if i < 120 % continue; % end idx1 = strmatch(motionClass, {results1.category}', 'exact'); idx2 = strmatch(motionClass, {results2.category}', 'exact'); if isempty(idx1) || isempty(idx2) error('Motion class not contained in results!'); end hits1 = results1(idx1).hits; hits2 = results2(idx2).hits; % hitIdx11 = find([hits1.cost] <= tau1); % hitIdx21 = find([hits2.cost] <= tau1); % hits11 = hits1(hitIdx11); % hits21 = hits2(hitIdx21); hits11 = hits1(1:min(20, length(hits1))); hits21 = hits2(1:min(20, length(hits2))); if (~isempty(hits1) && ~isempty(hits2)) hitIdx12 = find([hits1.cost] <= tau2); hitIdx22 = find([hits2.cost] <= tau2); hits12 = hits1(hitIdx12); hits22 = hits2(hitIdx22); else hits12 = []; hits22 = []; end [precision1{1,i}, recall1{1,i}, n_relevant1{1,i}] = precision_recall2(motionClass, hits11, false, DB_info); [precision1{2,i}, recall1{2,i}, n_relevant1{2,i}] = precision_recall2(motionClass, hits21, false, DB_info); [precision2{1,i}, recall2{1,i}, n_relevant2{1,i}] = precision_recall2(motionClass, hits12, false, DB_info); [precision2{2,i}, recall2{2,i}, n_relevant2{2,i}] = precision_recall2(motionClass, hits22, false, DB_info); end save(fullfile(fullPath, 'Cache', saveFileName), 'precision1', 'recall1', 'n_relevant1', 'precision2', 'recall2', 'n_relevant2'); else load(fullfile(fullPath, 'Cache', saveFileName)); end figure; lineColors = {[0 0 1], [1 0 0], [0 0 1], [1 0 0], [0.6 0.6 1], [1 0.6 0.6]}; for i=1:length(motionClasses) motionClass = motionClasses{i}; h=subplot(m,n,i); set(h, 'ButtonDownFcn', {@onClick, motionClass, i }); hold on; plot(recall2{1,i}, precision2{1,i}, 'g'); plot(recall2{2,i}, precision2{2,i}, 'y'); plot(recall1{1,i}, precision1{1,i}, 'g'); plot(recall1{2,i}, precision1{2,i}, 'y'); % delimiters of two tau-curves plot(recall1{1,i}(end), precision1{1,i}(end), 'gx'); plot(recall1{2,i}(end), precision1{2,i}(end), 'yx'); plotLines = get(gca, 'Children'); for j=1:length(plotLines) set(plotLines(j), 'Color', lineColors{j}); end % % delimiters of Top20 % top = min(20, min(length(recall1{1,i}), length(recall1{2,i}))); % topX = recall1{1,i}(top) / max(recall1{1,i}(top), precision1{1,i}(top)); % topY = precision1{1,i}(top) / max(recall1{1,i}(top), precision1{1,i}(top)); % l = line([0 topX], [0 topY]); % set(l, 'color', [0.6*ones(3,1)]); % if length(motionClasses)==1 % plot(recall{1,i}, precision{1,i}, 'rx'); % plot(recall{2,i}, precision{2,i}, 'bx'); % xlabel('recall'); % ylabel('precision'); % end set(gca, 'XLim', [0 1.05]); set(gca, 'YLim', [0 1.05]); if length(motionClasses) < 5 legend({labelTxt1, labelTxt2}); else set(gca, 'XTickLabel', []); set(gca, 'YTickLabel', []); t = text(0.5, -0.1, motionClass); set(t, 'horizontalalignment', 'center'); set(t, 'FontSize', 6); % t=title(motionClass); % set(t, 'FontSize', 6); % set(t, 'Position', [0.55 1.2 1]) end end % --------------------------------------------------- function onClick( src, eventdata, motionClass, number) set(gcf, 'Name', [motionClass ' (Nr. ' num2str(number) ')']); disp(motionClass);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
HitsYesNoDifferencePano.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/analytics/Retrieval/HitsYesNoDifferencePano.m
4,141
utf_8
b08d69ae3c4bc0effd091b0beb5e558c
function HitsYesNoDifferencePano( DB1, DB2, recompute, tau ) % HitsYesNoDifferencePano( DB1, DB2, recompute, tau ) global VARS_GLOBAL saveFileName = 'hitsYesNoDifference_cache'; if nargin < 2 DB1 = 'HDM05_cut_c3d_dipl'; DB2 = 'HDM05_cut_amc_dipl'; end if nargin < 3 recompute = false; end if nargin < 4 % tau = 0.01; tau = 1; end dbs = dbstack; fullPath = dbs(1).name(1:max(strfind(dbs(1).name, '\'))); load he_motion_classes; load HE_DB_info; keyframesThreshLo = 0.1; par.thresh_lo = keyframesThreshLo; par.thresh_hi = 1-par.thresh_lo; load(['retrieval_results_' DB1 '_' DB1 '_' num2str(1000*par.thresh_lo)]); VARS_GLOBAL.HitsYesNoDifferenceResults1 = results; load(['retrieval_results_' DB2 '_' DB2 '_' num2str(1000*par.thresh_lo)]); VARS_GLOBAL.HitsYesNoDifferenceResults2 = results; clear results; if recompute for i=1:length(motion_classes) motionClass = motion_classes{i}; disp(motionClass); idx1 = strmatch(motionClass, {VARS_GLOBAL.HitsYesNoDifferenceResults1.category}', 'exact'); idx2 = strmatch(motionClass, {VARS_GLOBAL.HitsYesNoDifferenceResults2.category}', 'exact'); hitIdx1 = find([VARS_GLOBAL.HitsYesNoDifferenceResults1(idx1).hits.cost] < tau); hitIdx2 = find([VARS_GLOBAL.HitsYesNoDifferenceResults2(idx2).hits.cost] < tau); if isempty(hitIdx1) || isempty(hitIdx2) error('Motion class not contained in results!'); end hits1 = VARS_GLOBAL.HitsYesNoDifferenceResults1(idx1).hits(hitIdx1); hits2 = VARS_GLOBAL.HitsYesNoDifferenceResults2(idx2).hits(hitIdx2); [precision{1,i}, recall{1,i}, n_relevant{1,i}] = precision_recall(motionClass, hits1, false, DB_info); [precision{2,i}, recall{2,i}, n_relevant{2,i}] = precision_recall(motionClass, hits2, false, DB_info); end save(fullfile(fullPath, 'Cache', saveFileName), 'recall', 'precision', 'n_relevant'); else load(fullfile(fullPath, 'Cache', saveFileName)); end for i=1:length(motion_classes) hitYesNo1(i,1:length(recall{1,i})) = diff([0 recall{1,i}*n_relevant{1,i}]); hitYesNo2(i,1:length(recall{2,i})) = diff([0 recall{2,i}*n_relevant{2,i}]); % hitYesNo1(i,1:length(recall2{1,i})) = diff([0 recall2{1,i}*n_relevant2{1,i}]); % hitYesNo2(i,1:length(recall2{2,i})) = diff([0 recall2{2,i}*n_relevant2{2,i}]); end range = [1:min(min(size(hitYesNo1,2), size(hitYesNo2,2)), 50)]; % figure; % imagesc(hitYesNo1(:, range)); % title(DB1, 'Interpreter', 'none'); % colormap(hot); % % figure; % imagesc(hitYesNo2(:, range)); % title(DB2, 'Interpreter', 'none'); % colormap(hot); figure; imagesc(hitYesNo1(:, range)' - hitYesNo2(:, range)'); colormap([0 0 1; 1 1 1; 1 0 0]); h=ylabel('Position'); set(h, 'fontsize', 7); for i=1:length(motion_classes) h = text(i, length(range)*1.05, motion_classes{i}); set(h, 'HorizontalAlignment', 'Right'); set(h, 'Rotation', 55); set(h, 'FontSize', 6); set(h, 'ButtonDownFcn', @motionClassTextOnClick); % set(h, 'ButtonDownFcn', {@motionClassTextOnClick, results1, results2}); end set(gca, 'Position', [0.1 0.3 0.85 0.65]); set(gcf, 'Position', [236 417 712 413]); set(gca, 'xticklabel', []) set(gca, 'fontsize', 7); % ----------------------------------------------------------- function motionClassTextOnClick(src, eventdata) global VARS_GLOBAL t = get(gcf,'selectionType'); motionClass = get(src, 'string'); resultIdx1 = strmatch(motionClass, {VARS_GLOBAL.HitsYesNoDifferenceResults1.category}, 'exact'); resultIdx2 = strmatch(motionClass, {VARS_GLOBAL.HitsYesNoDifferenceResults2.category}, 'exact'); resultBrowser(motionClass); set(gcf, 'position', [ 5 231 560 650]); showDeltaDiff2( VARS_GLOBAL.HitsYesNoDifferenceResults2(resultIdx2).hits, VARS_GLOBAL.HitsYesNoDifferenceResults1(resultIdx1).hits, motionClass); set(gcf, 'position', [ 572 8 560 446]); showDeltaDiff2( VARS_GLOBAL.HitsYesNoDifferenceResults1(resultIdx1).hits, VARS_GLOBAL.HitsYesNoDifferenceResults2(resultIdx2).hits, motionClass); set(gcf, 'position', [ 572 462 560 420]);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
compareJoint.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/analytics/3DTraj/compareJoint.m
2,254
utf_8
63044f3afb107cbf239a154b0b9d5ef4
function compareJoint( skel1, mot1, skel2, mot2, jointName ) % compareJoint( skel1, mot1, skel2, mot2, jointName ) % % creates a clickable figure showing the l2-distance of the joint % given by "jointName". if nargin < 5 help compareJoint return end if length(mot1.jointTrajectories{1}) ~= length(mot2.jointTrajectories{1}) error('Files have different number of frames and cannot be compared!'); end idx1 = trajectoryID(mot1, jointName); idx2 = trajectoryID(mot2, jointName); diff = mot1.jointTrajectories{idx1} - mot2.jointTrajectories{idx2}; diff = sqrt(dot(diff, diff)); h=figure; set(h, 'Name', mot1.filename); plot(diff); set(gca, 'ButtonDownFcn', {@animateOnClick, skel1, mot1, skel2, mot2}); hold on; meanDiff = mean(diff); textXPos = mot1.nframes / 20; plot(meanDiff * ones(1, length(diff)), ':'); plot( (meanDiff-std(diff)) * ones(1, length(diff)), 'r:'); plot( (meanDiff+std(diff)) * ones(1, length(diff)), 'r:'); text( textXPos, meanDiff, 'mean', 'BackgroundColor',[.9 .9 .9]); text( textXPos, meanDiff-std(diff), 'mean - std', 'BackgroundColor',[.9 .9 .9]); t=text( textXPos, meanDiff+std(diff), 'mean + std', 'BackgroundColor',[.9 .9 .9]); xlabel('frames'); ylabel('deviation'); title(['distance between ' upper(jointName) ' trajectories ( std.dev.=' num2str(std(diff)) ')' ], 'Interpreter', 'none'); axis tight; xlims = get(gca, 'xlim'); axis auto; set(gca, 'xlim', xlims); return; % ------------------------------------------------------------------------- function animateOnClick(varargin) skel1 = varargin{3}; mot1 = varargin{4}; skel2 = varargin{5}; mot2 = varargin{6}; t = get(gcf,'selectionType'); % try to find animation window titleText = 'compareJoint animation figure'; children = get(0, 'Children'); animationWindow = []; for i=1:length(children) if strcmpi( titleText, get(children(i), 'Name') ) animationWindow = children(i); end end if isempty(animationWindow) h=figure; set(h, 'Name', titleText); else set(0, 'CurrentFigure', animationWindow); end if strcmpi(t, 'alt') % right click animate(skel2, mot2, 1, 0.5); elseif strcmpi(t, 'extend') % middle click animate([skel1, skel2], [mot1, mot2], 1, 0.5); else animate(skel1, mot1, 1, 0.5); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
matrix_comparison_similarity.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/analytics/FM_MT/matrix_comparison_similarity.m
2,704
utf_8
24f1aa0b2da611ae524fe0e4e05b3b15
function similarity = matrix_comparison_similarity( compFunction, aggrFunction, showDetailsCategory, recomputeMatrix ) % matrix = matrix_comparison_similarity( compFunction, aggrFunction, showDetailsCategory, constBoneLengths, recomputeMatrix ) % % Shoes similarity of motion classes referring to the given compFunction. % % compFunction: 'adv' - advanced bitwise difference (not taking differences in run lengths into account) % 'bitDiff' - bitwise difference % 'featureCurves' - std. dev. of difference of feature curves % 'MTdiff' - difference between Motion-Templates % aggrFunction: 'mean' - aggregates by calculating the mean value of each category % 'max' - aggregates by taking the maximum value of each category % showDetailsCategory : determines right-click behaviour % constBoneLengths : Enforce constant bonelengths after joint position estimation. Default = true. % recomputeMatrix : Enforces recomputation of matrix if nargin < 1 help matrix_comparison return; else if nargin < 2 aggrFunction = 'mean'; end if nargin < 3 showDetailsCategory = true; end if nargin < 4 constBoneLengths = true; end if nargin < 5 recomputeMatrix = false; end end load HE_motion_classes; matrix = matrix_comparison(compFunction, aggrFunction, 0, showDetailsCategory, recomputeMatrix ); for i=1:61 for j=1:61 similarity(i,j) = sum(abs(matrix(:,i) - matrix(:,j))); end end figure; imagesc(similarity, 'buttondownfcn', {@matrixOnClick, similarity, motion_classes}); axis off; colormap('hot'); set(colorbar, 'Position', [0.935 0.251 0.02 0.7]); set(colorbar, 'Fontsize', 7); for i=1:length(motion_classes) h = text(-1, i, motion_classes{i}); set(h, 'HorizontalAlignment', 'Right'); set(h, 'Interpreter', 'None'); set(h, 'FontSize', 5); end for i=1:length(motion_classes) h = text(i, length(motion_classes)+1.5, motion_classes{i}); set(h, 'HorizontalAlignment', 'Right'); set(h, 'Rotation', 55); set(h, 'FontSize', 5); end set(gca, 'Position', [0.22 0.25 0.7 0.7]); % ------------------------------ function matrixOnClick(src, eventdata, similarity, motion_classes) pointClicked = get(get(src, 'Parent'), 'CurrentPoint'); x = round(pointClicked(1,1)); y = round(pointClicked(1,2)); title([motion_classes{x} ' - ' motion_classes{y} ' ( ' num2str(similarity(x,y)) ' )']);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
matrix_comparison_showFeature.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/analytics/FM_MT/matrix_comparison_showFeature.m
3,408
utf_8
f4f93990c3e2efac29ba05d8100f7575
function matrix = matrix_comparison_showFeature( src, eventdata, compFunction, diffPerFeature, featureNames, motionClasses, dbName1, dbName2, constBoneLengths, CLIM ) pointClicked = get(get(src, 'Parent'), 'CurrentPoint'); x = round(pointClicked(1,1)); y = round(pointClicked(1,2)); % cmap = hot; % cmap(1,:) = [0.4 0.4 0.4]; % for not used entries if x <= length(motionClasses) motionClass = motionClasses{ x }; % left click and right click: Change title to display information if y <= length(featureNames) featureName = featureNames{ y }; set(get(get(src, 'Parent'), 'Title'), 'String', [featureName ' (Nr. ' num2str(y) ') - ' motionClass]); set(get(get(src, 'Parent'), 'Title'), 'Interpreter', 'none'); end disp(get(get(gca, 'title'), 'string')); % right click: Open up comparison for selected motion class t = get(gcf,'selectionType'); if strcmpi(t, 'alt') % right click % matrix = zeros(length(featureNames), length(motionClasses)); for i=1:length(motionClasses) matrix(1:length(diffPerFeature{i}(y,:)),i) = diffPerFeature{i}(y,:)'; end figure; % imagesc(matrix, 'buttondownfcn',{@matrix_comparison_showMatrixEntryFeature, y, motionClasses, dbName1, dbName2, constBoneLengths }); if nargin < 10 || isempty(CLIM) imagesc(matrix); else imagesc(matrix, CLIM); end set(get(gca, 'Children'), 'buttondownfcn',{@matrix_comparison_showMatrixEntryFeature, y, motionClasses, dbName1, dbName2, constBoneLengths }); axis off; colormap('hot'); for i=1:length(motionClasses) rectY = length(diffPerFeature{i}(y,:)); rectHeight = size(matrix, 2) - rectY; % if rectHeight > 0 h=rectangle('Position', [i-0.5 rectY+0.5 1.02 rectHeight]); set(h, 'EdgeColor', 'none'); set(h, 'FaceColor', [0.5 0.5 0.5]); for j=1:rectHeight h=line([i-0.5 i+0.5], [rectY-0.5+j rectY+0.505+j]); set(h, 'Color', [0 0 0]); set(h, 'LineWidth', 0.2); end end set(gcf, 'Name', [featureName ' (Nr. ' num2str(y) ')']); h = text(-1, floor(size(matrix,1)/2), 'files in motion class'); set(h, 'HorizontalAlignment', 'Center'); set(h, 'Rotation', 90); set(h, 'FontSize', 8); for i=1:length(motionClasses) h = text(i, size(matrix, 1)+1.5, motionClasses{i}); set(h, 'HorizontalAlignment', 'Right'); set(h, 'Rotation', 55); set(h, 'FontSize', 5); end set(gca, 'Position', [0.07 0.155 0.92 0.8]); set(gcf, 'Position', [4 57 831 646]); end else if y <= length(featureNames) featureName = featureNames{ y }; set(get(get(src, 'Parent'), 'Title'), 'String', featureName); else set(get(get(src, 'Parent'), 'Title'), 'String', 'CLICK IMAGE FOR DETAILS!'); end end % ----------------------------------------------------------- function featureTextOnClick(src, eventdata) fullFeatureName = ['feature_AK_bool_' get(src, 'String') '_robust']; open(fullFeatureName);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
matrix_comparison.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/analytics/FM_MT/matrix_comparison.m
5,576
utf_8
8921b05996863ad882e7c58a6260dab9
function [matrix, diffPerFeature] = matrix_comparison( compFunction, aggrFunction, thresh, showDetailsCategory, recomputeMatrix, fontSize ) % [matrix, diffPerFeature] = matrix_comparison( compFunction, aggrFunction, thresh, showDetailsCategory, recomputeMatrix, fontSize ) % % compFunction: 'adv' - advanced bitwise difference (not taking differences in run lengths into account) % 'bitDiff' - bitwise difference % 'featureCurves' - std. dev. of difference of feature curves % 'MTdiff' - difference between Motion-Templates % aggrFunction: 'mean' - aggregates by calculating the mean value of each category % 'max' - aggregates by taking the maximum value of each category % thresh : cuts matrix values below thresh to zero. Used as multiple of max(max(matrix)). % showDetailsCategory : determines right-click behaviour % recomputeMatrix : Enforces recomputation of matrix % fontSize : xLabel and yLabel font size if nargin < 1 help matrix_comparison return; else switch lower(compFunction) case {'adv', 'bitdiff', 'featurecurves', 'featurecurvesadv', 'mtdiff'} otherwise error('Unknown compFunction!'); end if nargin < 2 aggrFunction = 'mean'; end switch lower(aggrFunction) case {'mean', 'max'} otherwise error('Unknown aggrFunction!'); end if nargin < 3 thresh = 0; end if nargin < 4 showDetailsCategory = true; end if nargin < 5 recomputeMatrix = false; end if nargin < 6 fontSize = 6; end end dbs = dbstack; fullPath = dbs(1).name(1:max(strfind(dbs(1).name, '\'))); load all_motion_classes; categories = motion_classes; feature_names = getFeatureNames; global VARS_GLOBAL dbPath = VARS_GLOBAL.dir_root; dbName1 = 'HDM05_cut_amc'; dbName2 = 'HDM05_cut_c3d'; % filenames for load + save matrixFilename = 'matrix'; diffFilename = 'diff'; if ( strcmpi(compFunction, 'mtdiff') || strcmpi(compFunction, 'mtDTW') ) [diff, matrix] = motionTemplateComparison( compFunction, dbName1, dbName2, motion_classes ); diffPerFeature = []; else if recomputeMatrix for i=1:length(categories) [diff{i}, diffPerFeature{i}] = feature_comparison_category( compFunction, categories{i}, dbName1, dbName2 ); % matrix(:,i) = mean(diffPerFeature{i}, 2); switch lower(aggrFunction) case 'mean' matrix(:,i) = mean(diffPerFeature{i}, 2); case 'max' matrix(:,i) = max(diffPerFeature{i}, [], 2); end end save( fullfile(fullPath, 'Cache', [matrixFilename '_' aggrFunction '_' compFunction]), 'matrix'); save( fullfile(fullPath, 'Cache', [diffFilename '_' aggrFunction '_' compFunction]), 'diffPerFeature'); else load( fullfile(fullPath, 'Cache', [matrixFilename '_' aggrFunction '_' compFunction]) ); load( fullfile(fullPath, 'Cache', [diffFilename '_' aggrFunction '_' compFunction]) ); end end if thresh > 0 matrix(find(matrix < thresh*max(max(matrix)))) = 0; end h=figure; set(h, 'Name', [aggrFunction ' of ' compFunction]); if strcmpi(compFunction, 'mtdiff') imagesc(matrix, 'buttondownfcn',{@mtDiffOnClick, categories, dbName1, dbName2}) else if showDetailsCategory imagesc(matrix, 'buttondownfcn',{@matrix_comparison_showCategory, ... compFunction, diffPerFeature, feature_names, categories, fullfile(dbPath, dbName1), fullfile(dbPath, dbName2), [0 max(max(cell2mat(diffPerFeature)))] }) else imagesc(matrix, 'buttondownfcn',{@matrix_comparison_showFeature, ... compFunction, diffPerFeature, feature_names, categories, fullfile(dbPath, dbName1), fullfile(dbPath, dbName2), [0 max(max(cell2mat(diffPerFeature)))] }) end end axis off; colormap('hot'); for i=1:length(feature_names) h = text(-1, i, feature_names{i}(17:end-7)); set(h, 'HorizontalAlignment', 'Right'); set(h, 'Interpreter', 'None'); set(h, 'FontSize', fontSize); set(h, 'ButtonDownFcn', @featureTextOnClick); end for i=1:length(categories) h = text(i, length(feature_names)+1.5, categories{i}); set(h, 'HorizontalAlignment', 'Right'); set(h, 'Rotation', 55); set(h, 'FontSize', fontSize-1); end % set(gcf, 'Position', [620 280 650 580]) children = get(gcf, 'Children'); set(children(1), 'YLim', [0 length(feature_names)+3.7]); h = colorbar; % pos = get(h,'Position'); % pos(3)=pos(3)/3; % pos(1)=0.9; set(h,'Position',[0.93 0.24 0.02 0.72]); set(h, 'Fontsize', 7); set(gca, 'Position', [0.2 0.18 0.72 0.79]); % ----------------------------------------------------------- function featureTextOnClick(src, eventdata) fullFeatureName = ['feature_AK_bool_' get(src, 'String') '_robust']; open(fullFeatureName); function mtDiffOnClick(src, eventdata, categories, dbName1, dbName2) pointClicked = get(get(src, 'Parent'), 'CurrentPoint'); x = round(pointClicked(1,1)); y = round(pointClicked(1,2)); t = get(gcf,'selectionType'); if strcmpi(t, 'alt') % right click % showTemplateComparison( categories{x}, dbName1, dbName2, true, false); showTemplateComparison( categories{x}, dbName1, dbName2, true, true); else title(categories{x}); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
matrix_comparison_showCategory.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/analytics/FM_MT/matrix_comparison_showCategory.m
3,289
utf_8
77817382a114de20eea286d077a390ad
function [ output_args ] = matrix_comparison_showCategory( src, eventdata, compFunction, diffPerFeature, featureNames, motionClasses, dbName1, dbName2, CLIM ) pointClicked = get(get(src, 'Parent'), 'CurrentPoint'); x = round(pointClicked(1,1)); y = round(pointClicked(1,2)); if x <= length(motionClasses) motionClass = motionClasses{ x }; % left click and right click: Change title to display information if y <= length(featureNames) featureName = featureNames{ y }; t = title([featureName ' - ' motionClass]); set(t, 'Interpreter', 'none'); else t = title(motionClass); set(t, 'Interpreter', 'none'); end disp(get(get(gca, 'title'), 'string')); % right click: Open up comparison for selected motion class t = get(gcf,'selectionType'); if strcmpi(t, 'alt') % right click motionClass = motionClasses{x}; % showTemplateComparison(motionClass); dir1 = fullfile(dbName1, motionClass, filesep); files1 = dir(fullfile(dir1, '*.c3d')); dir2 = fullfile(dbName2, motionClass, filesep); files2 = dir(fullfile(dir2, '*.c3d')); if isempty(files1) % db1 is AMC, db2 is C3D files1 = dir(fullfile(dir1, '*.amc')); else % db1 is C3D, db2 is AMC files2 = dir(fullfile(dir2, '*.amc')); end maxFiles = min([length(files1) length(files2)]); files1 = strcat(mat2cell(repmat(dir1,maxFiles,1), ones(maxFiles,1)), {files1(1:maxFiles).name}'); files2 = strcat(mat2cell(repmat(dir2,maxFiles,1), ones(maxFiles,1)), {files2(1:maxFiles).name}'); figure; if nargin < 10 || isempty(CLIM) imagesc(diffPerFeature{x}); else imagesc(diffPerFeature{x}, CLIM); end set(get(gca, 'Children'), 'buttondownfcn',{@matrix_comparison_showMatrixEntry, featureNames, motionClass, files1, files2 }); axis off; colormap('hot'); set(gca, 'Position', [0.25 0.11 0.72 0.85]); h = text(floor(length(files1)/2), length(featureNames)+2, ['files in motion class ' motionClass]); set(h, 'HorizontalAlignment', 'Center'); for i=1:length(featureNames) h = text(0, i, featureNames{i}(17:end-7)); set(h, 'HorizontalAlignment', 'Right'); set(h, 'Interpreter', 'None'); set(h, 'FontSize', 8); set(h, 'ButtonDownFcn', @featureTextOnClick); end set(gcf, 'Position', [373 58 650 631]); end else if y <= length(featureNames) featureName = featureNames{ y }; set(get(get(src, 'Parent'), 'Title'), 'String', featureName); else set(get(get(src, 'Parent'), 'Title'), 'String', 'CLICK IMAGE FOR DETAILS!'); end end % ----------------------------------------------------------- function featureTextOnClick(src, eventdata) t = get(gcf,'selectionType'); if strcmpi(t, 'alt') % right click fullFeatureName = ['feature_AK_bool_' get(src, 'String') '_robust']; open(fullFeatureName); else disp(get(src, 'String')); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
new_motionTemplateGenerateReal_realInputWeighted.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/motion_templates/new_motionTemplateGenerateReal_realInputWeighted.m
7,916
utf_8
a136948ee28935380adc7ee969f800ac
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Generation of motion template %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Utemplate,UtemplateWeights,Vcost] = new_motionTemplateGenerateReal_realInputWeighted(U,Uweights,parameter) % function [Utemplate,UtemplateWeights,Vcost] = new_motionTemplateGenerateReal_realInputWeighted(U,parameter,Uweights_in) numU = size(U,1); dimU = size(U{1},1); lenV = size(U{1},2); if (parameter.VrepWoverlapFactor<=0) parameter.VrepWoverlapFactor = 1/(numU-1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % DTW computatation: U{1} with U{2},...,U{numU} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VrepW = cell(numU,1); Vmatch = cell(numU,1); Vcost = zeros(numU,1); UwarpWeights = zeros(numU,lenV); UwarpWeights(1,:) = Uweights{1}; Uwarp = cell(numU,1); Uwarp{1}=U{1}; for k=2:numU [Uwarp{k},UwarpWeights(k,:),VrepW{k},Vmatch{k},Vcost(k)] = new_motionTemplateDTWReal_realInputWeighted(U{1},Uweights{1},U{k},Uweights{k},parameter); end if (parameter.templateComputationStrategy == 6) || (parameter.templateComputationStrategy == 8) % only idendical values are kept. Everythind else is set to 0.5 UtemplateHelp = Uwarp{1}; for k=2:numU differences = find(UtemplateHelp ~= Uwarp{k}); UtemplateHelp(differences) = 0.5*ones(size(differences)); end %finally average all weights. UtemplateHelpWeights = sum(UwarpWeights,1); UtemplateHelpWeights = UtemplateHelpWeights/numU; else %use real averaging %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Utemplate % Compute the weighted average over all templates that were generated in the % preceding step. Note that all templates have the length of the reference % stream V==U{1}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% UtemplateHelp = zeros(size(U{1})); UtemplateHelpWeights = sum(UwarpWeights,1); for k=1:numU X = repmat(UwarpWeights(k,:),dimU,1); UtemplateHelp = UtemplateHelp + X.*Uwarp{k}; end X = repmat(UtemplateHelpWeights,dimU,1); UtemplateHelp = UtemplateHelp./X; UtemplateHelpWeights = UtemplateHelpWeights/numU; end if (parameter.conjoin == 0) Utemplate = UtemplateHelp; UtemplateWeights = UtemplateHelpWeights; else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % VrepWConjoin % All data streams U_i for i=2:numU have been aligned with the reference stream % V==U_1. Multiple matching frames from a U_i to a frame in V have been % recorded in the VrepW{i}, each entry of which represents a segment in V. % Now find the "connected components" of these segments within V. % That is, find longest contiguous segments within V such that there is a % covering with overlapping segments from the VrepW{i}, where two % segments A and B are "overlapping" if there is a sequence of segments that % connects A and B through simple overlap relations. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VrepWconcat = VrepW{2}; for k=3:numU VrepWconcat = [VrepWconcat VrepW{k}]; end num = size(VrepWconcat,2); VrepWconjoin = zeros(2,num); [a,b] = sort(VrepWconcat(1,:)); VrepWconcat = VrepWconcat(:,b); X = VrepWconcat; B = zeros(size(X,2),max(max(VrepWconcat))); s = (numU-1)*ones(size(B,2),1); s(1) = 0; p = X(1,1); for k=1:size(X,2) B(k,X(1,k):X(2,k)) = 1; if (X(1,k)~=p) % this code will execute each time a new block of start indices begins p = X(1,k); s(p) = sum(B(1:k-1,p)); end end % visualization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if parameter.visVrepW == 1 %X = VrepWconcat(:,(VrepWconcat(1,:)~=VrepWconcat(2,:))); figure; subplot(2,2,1); xlabel('VrepWconcat'); imagesc(B,[0 1]); colormap hot; subplot(2,2,2); xlabel('Column sums over VrepWconcat'); b = sum(B); plot(b); set(gca,'xlim',[1 length(b)]); subplot(2,2,3); xlabel('Upward column sums at lower contour'); plot(s); line([1 length(b)],[parameter.VrepWoverlapFactor*(numU-1) parameter.VrepWoverlapFactor*(numU-1)],'color','r'); set(gca,'xlim',[1 length(b)],'ylim',[0 numU]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % counter = 0; % k = 0; % while k<num % k = k+1; % pos1 = VrepWconcat(1,k); % pos2 = VrepWconcat(2,k); % while k<num && VrepWconcat(1,k+1)<=pos2 % k = k+1; % pos2 = max(pos2,VrepWconcat(2,k)); % end % counter = counter+1; % VrepWconjoin(1,counter)=pos1; % VrepWconjoin(2,counter)=pos2; % end % VrepWconjoin = VrepWconjoin(:,1:counter); v = find(s<parameter.VrepWoverlapFactor*(numU-1))'; w = [v(2:end)-1 size(B,2)]; VrepWconjoin = [v; w]; % visualization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if parameter.visVrepW == 1 B = zeros(size(VrepWconjoin,2),max(max(VrepWconjoin))); for k=1:size(VrepWconjoin,2) B(k,VrepWconjoin(1,k):VrepWconjoin(2,k)) = 1; end subplot(2,2,4); xlabel('VrepWconjoin'); imagesc(B,[0 1]); colormap hot; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % UtemplateConjoin % Now that a segmentation of V has been determined (VrepWconjoin), % compute the weighted average of the columns within Utemplate corresponding to each % of these segments, resulting in UtemplateConjoin. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% UtemplateWeights = zeros(1,size(VrepWconjoin,2)); Utemplate = zeros(dimU,size(VrepWconjoin,2)); for k=1:size(VrepWconjoin,2) X = repmat(UtemplateHelpWeights(VrepWconjoin(1,k):VrepWconjoin(2,k)),dimU,1); pattern = sum(X.*UtemplateHelp(:,VrepWconjoin(1,k):VrepWconjoin(2,k)),2); UtemplateWeights(k) = UtemplateWeights(k) + sum(UtemplateHelpWeights(VrepWconjoin(1,k):VrepWconjoin(2,k))); pattern = pattern/UtemplateWeights(k); Utemplate(:,k) = pattern; end % for k=1:size(VrepWconjoin,2) % pattern = sum(UtemplateHelp(:,VrepWconjoin(1,k):VrepWconjoin(2,k)),2); % UtemplateWeights(k) = UtemplateWeights(k) + sum(UtemplateHelpWeights(VrepWconjoin(1,k):VrepWconjoin(2,k))); % pattern = pattern/(VrepWconjoin(2,k)-VrepWconjoin(1,k)+1); % Utemplate(:,k) = pattern; % end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Visualization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if parameter.visTemplate == 1 figure; set(gcf,'Position',[55 70 560 861]); subplot(6,1,1); plot(UtemplateHelpWeights); title('UtemplateHelp'); colorbar; subplot(6,1,2); colormap(hot); imagesc(UtemplateHelp,[0 1]); colorbar; subplot(6,1,3); plot(UtemplateWeights); title('Utemplate'); colorbar; subplot(6,1,4); colormap(hot); imagesc(Utemplate,[0 1]); colorbar; drawnow; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
new_motionTemplateDTWReal_realInputWeighted.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/motion_templates/new_motionTemplateDTWReal_realInputWeighted.m
5,156
utf_8
9d7cbd47ace8c08991cdf6d226654402
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Cost of features % by Meinard Mueller, 03.06.2005 % % V n times p matrix, data stream of length n with p dimensional feature vectors % W m times p matrix, data stream of length n with p dimensional feature vectors % match num x 2 array encoding the matched indices % costF 1 x p array containing the costs per feature % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Wwarp,WwarpWeights,VrepW,match,cost,C,D]=motionTemplateDTW_realInputWeighted(V,Vweights,W,Wweights,parameter) V = V'; W = W'; n = size(V,1); p = size(V,2); m = size(W,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Global cost matrix for matching i-th feature with j-th feature %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % C = zeros(n,m); % for i=1:n % for j=1:m % C(i,j) = norm(V(i,:)-W(j,:),1) / p; % end % end % computes pairwise L_1 distance between feature vectors %%%%%%%% equivalent C code, improves efficiency by roughly a factor of 10 C = C_DTW_compute_Creal(V,W); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% C = C.*((repmat(Vweights',1,m)+repmat(Wweights,n,1))/2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Computing optimal match by dynamic programming %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %Attention: MATLAB indexing always begins with index 1 % D = zeros(n,m); % E = zeros(n,m); % % D(1,1) = C(1,1); % for i=2:n % D(i,1)=D(i-1,1)+C(i,1); % end % for j=2:m % D(1,j)=D(1,j-1)+C(1,j); % end % % for i=2:n % for j=2:m % [val,E(i,j)] = min([D(i-1,j-1), D(i,j-1), D(i-1,j)]); %diag, horz, vert % D(i,j) = val+C(i,j); % end % end %%%%%%%% equivalent C code, improves efficiency [D,E] = C_DTW_compute_D(C); i = n; j = m; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% match = zeros(n+m-1,2); k=0; while ((i>1) & (j>1)) k=k+1; match(k,:)=[i j]; if E(i,j)==1 j=j-1; i=i-1; elseif E(i,j)==2 j=j-1; else i=i-1; end end k = k+1; match(k,:)=[i j]; while (i>1) i = i-1; k=k+1; match(k,:)=[i j]; end while (j>1) j = j-1; k=k+1; match(k,:)=[i j]; end match = match([1:k],:); match = flipud(match); cost = D(n,m); match = match'; match_v = match(1,:); match_w = match(2,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % De-warp VwarpTemplate into Vtemplate, yielding a sequence % of the same length as V, while averaging columns that are % replicated in the match of V to W using Wweights. % Normalize each resulting column by the sum of Wweights used % in the averaging process. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% WwarpMatch = W(match_w,:)'; WwarpMatchWeights = Wweights(match_w); match_len = length(match_v); Wwarp = zeros(p,n); WwarpWeights = zeros(1,n); [Vruns, Vruns_start, Vrep] = runs_find_constant(match_v); for k=1:length(Vruns) b = Vruns(k); range = Vruns_start(k):Vruns_start(k)+Vrep(k)-1; X = repmat(WwarpMatchWeights(range),p,1); Wwarp(:,b) = Wwarp(:,Vruns(k))+sum(X.*WwarpMatch(:,range),2); WwarpWeights(b) = WwarpWeights(b)+sum(WwarpMatchWeights(range)); end Wwarp = Wwarp./repmat(WwarpWeights,p,1); % for k=1:match_len % b = match_v(k); % Wwarp(:,b) = Wwarp(:,b)+WwarpMatch(:,k)/Vrep(b); % WwarpWeights(b) = WwarpWeights(b)+WwarpMatchWeights(k); % end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Compute a 2 x m matrix VrepW, column j of which % encodes a pair (start_j,end_j). These entries are indices % into V, and denote segments within V that match to the same % frame j in W. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [Wruns, Wruns_start, Wrep] = runs_find_constant(match_w); VrepW = [match_v(Wruns_start); match_v(Wruns_start+Wrep-1)]; for k=1:m % normalize each Wweight(j) by the number of elements in V matching to W(j) WwarpWeights(VrepW(1,k):VrepW(2,k)) = WwarpWeights(VrepW(1,k):VrepW(2,k))/Wrep(k); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Visualizations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if parameter.visCost == 1 figure; imagesc(C,[0 p]); axis xy; colormap(hot); colorbar; title(['Local cost matrix C, D(n,m)=',num2str(D(n,m)),', #(match)=',num2str(size(match,2))]); hold on; plot(match(2,:),match(1,:),'.c'); end if parameter.visWarp == 1 figure; subplot(2,1,1); plot(WwarpWeights); title('WwarpWeights'); colorbar; subplot(2,1,2); imagesc(Wwarp,[0 1]); title('Wwarp'); colormap(hot); colorbar; drawnow; % subplot(2,2,3); % imagesc(VwarpEqual,[0 1]); title('VwarpEqual'); % subplot(2,2,4); % imagesc(Vequal,[0 1]); title('Vequal'); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
motionTemplateDTWRetrievalWeighted.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/motion_templates/motionTemplateDTWRetrievalWeighted.m
6,504
utf_8
220ef1c3e5d7c102dce1db2c81257ac5
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Motion Retrieval via substring DTW based on motion templates % by Meinard Mueller, 10.11.2005 % % V n times p matrix, data stream of length n with p dimensional feature vectors % W m times p matrix, data stream of length n with p dimensional feature vectors % hits struct array, see below % costF 1 x p array containing the costs per feature % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hits,C,D,Delta]=motionTemplateDTWRetrievalWeighted(V,Vweights,W,Wweights,parameter,varargin) di = [1 0 1]; dj = [1 1 0]; if (nargin>6) dj = varargin{2}; end if (nargin>5) di = varargin{1}; end if (nargin>7) dWeights = varargin{3}; else dWeights = ones(1,length(di)); end if (parameter.expandV==1) [V,Vweights] = expandWeightedVectorSequence(V,Vweights); end V = V'; W = W'; n = size(V,1); p = size(V,2); m = size(W,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Global cost matrix for matching i-th feature with j-th feature %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% V_0 = double(V==0)+double(V==0.5); V_1 = double(V==1)+double(V==0.5); C = V_1*W' + V_0*(1-W'); % #(concurrences) C = p-C; % #(disagreements) C = C/n; % disagreements per frame in V %C = C/(p*n); % disagreements per feature and frame in V %C = C_DTW_compute_C(V,W); % slower num_V_nonfuzzy = max(1,sum(V~=0.5,2)); C = C.*((repmat(Vweights',1,m)+repmat(Wweights,n,1))./(2*repmat(num_V_nonfuzzy,1,m))); %C = C.*((repmat(Vweights',1,m)+repmat(Wweights,n,1))/2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Computing optimal match by dynamic programming %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % tic; % D = zeros(n,m); % E = zeros(n,m); % % D(1,1) = C(1,1); % for i=2:n % D(i,1)=D(i-1,1)+C(i,1); % end % for j=2:m % D(1,j)=C(1,j); % end % % for i=2:n % for j=2:m % indices = sub2ind(size(D),max(i-di,1),max(j-dj,1)); % [val,E(i,j)] = min(D(indices)); % % D(i,j) = val + dWeights(E(i,j))*C(i,j); % end % end %%%%%%%% equivalent C code, improves efficiency by roughly a factor of 150 [D,E] = C_DTWpartial_compute_D_variablePathSteps(C,int32(di),int32(dj),dWeights); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %t=toc; fprintf('%f',t) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Matches %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Delta = D(n,:); match_numMax = parameter.match_numMax; match_thresh = parameter.match_thresh; hits = struct('file_id',0,... % file ID, index into idx.files 'file_name','',... 'cost',0,... 'match',0,... % num x 2 array encoding the matched indices 'frame_first_matched_all',0,... % the first frame of this hit (using a continuous frame count for the entire database) 'frame_last_matched_all',0,... % the last frame of this hit (using a continuous frame count for the entire database) 'frame_first_matched',0,... % the first frame of this hit 'frame_last_matched',0,... % the last frame of this hit 'frame_length',0); % the length of this hit measured in frames hits = repmat(hits,match_numMax,1); matches_length = zeros(1,length(Delta)); % this array will indicate the length (in frames) of the match starting at a specific point Delta_help = Delta; counter = 0; [cost,pos] = min(Delta_help); while counter<match_numMax && cost <= match_thresh i=n; j=pos; match_temp = zeros(max(n,m),2); k=0; while ((i>1) & (j>1)) k=k+1; match_temp(k,:)=[i j]; i2 = i - di(E(i,j)); j2 = j - dj(E(i,j)); i = i2; j = j2; end k = k+1; match_temp(k,:)=[i j]; while (i>1) i = i-1; k=k+1; match_temp(k,:)=[i j]; end match_temp = match_temp([1:k],:); match_temp = flipud(match_temp)'; if (matches_length(match_temp(2,1))>0) % has the starting point of this path been recorded previously? current_match_length = matches_length(match_temp(2,1)); else % new starting point of a match path; record match. counter = counter+1; hits(counter).match = match_temp; hits(counter).frame_first_matched_all = match_temp(2,1); hits(counter).frame_last_matched_all = match_temp(2,end); hits(counter).cost = cost; current_match_length = match_temp(2,end)-match_temp(2,1)+1; pufferBackward = ceil(parameter.match_startExclusionBackward*current_match_length); pufferForward = ceil(parameter.match_startExclusionForward*current_match_length); ind_start = max(match_temp(2,1)-pufferBackward,1); ind_end = min(match_temp(2,1)+pufferForward,m); matches_length(ind_start:ind_end) = repmat(current_match_length,1,ind_end-ind_start+1); end pufferBackward = ceil(parameter.match_endExclusionBackward*current_match_length); pufferForward = ceil(parameter.match_endExclusionForward*current_match_length); ind_start = max(match_temp(2,end)-pufferBackward,1); ind_end = min(match_temp(2,end)+pufferForward,m); Delta_help(ind_start:ind_end)=Inf; [cost,pos] = min(Delta_help); end hits = hits(1:counter); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Visualizations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if parameter.visCost == 1 figure; set(gcf,'Position',[30 551 1210 398]); subplot(2,1,1) C_vis = C; C_vis(isnan(C_vis))=max(max(C_vis)); imagesc(C_vis); axis xy; colormap(hot); colorbar; D_vis = D; D_vis(isnan(D_vis))=max(max(D_vis)); subplot(2,1,2) imagesc(D_vis); axis xy; colormap(hot); colorbar; hold on; for k=1:length(hits) plot(hits(k).match(2,:),hits(k).match(1,:),'.c'); end % h=figure; % plot(Delta); % set(h,'position',[0 161 1275 229]); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
MT_DisplayRealtimeData.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/XSensMatlab/MT_DisplayRealtimeData.m
22,793
utf_8
a722757e17506c523bd2757224064a50
function MT_DisplayRealtimeData(varargin) %% MT_DisplayRealtimeData(varargin); % % Real-time display of calibrated data or 3D orientation data from an MTi % or MTx % % varargin: Input arguments % 1. COM-port [integer] to which MT is connected (default = 1 , i.e. COM1) % 2. Display mode [string], choose to view: % 'caldata' Calibrated inertial and magnetic data (default) % 'euler' Orientation output in Euler-angles (see Tech Doc for definition) % 'quat' Orientation output in Quaternions % 'matrix' Orientation output in rotation Matrix format % 3. zoom-level, [1=12 s chart, 2=8 s chart (default), 3=4 s chart] % 4. update rate, [1=slow, 2=medium (default), 3=fast] % % example function call: % "MT_DisplayRealtimeData(1,'euler',2,3)" % % Press key on keyboard while running: % % Calibrated Inertial and magnetic data MODE: % "Q" = Quit % "P" = Pause/Start real-time plot % "Z" = Toggle Zoom in/out % "A" = View only accelerometer data % "G" = View only rate gyro data % "M" = View only magnetometer data % "D" = View all MTi / MTx data (default) % % Orientation data output MODE: % "Q" = Quit % "P" = Pause/Start real-time plot % "R" = Reset reference orientation (refer to Tech Doc for details) % "Z" = Zoom in/out (not applicable for Matrix output mode) % (it is not possible to switch orientation output mode during run-time) % % Xsens Technologies B.V., 2002-2007 % v.2.8.4 % tested to be compatible with MATLAB 2006b. % The display code in this demo code has been changed due to a bug in MATLAB 7.x % please refer to: % http://www.mathworks.com/support/bugreports/details.html?rp=207276 % Check to see if number of input arguments is correct if nargin>4, error('too many input arguments') end % set default values if needed defaultValues={1,'caldata',2,1.0,1,1.0}; nonemptyIdx=~cellfun('isempty',varargin); defaultValues(nonemptyIdx)=varargin(nonemptyIdx); [COMport,DisplayMode,zoom_level_setting,filterSettings_gain,filterSettings_corr,filterSettings_weight]... =deal(defaultValues{:}); % set up MTObj h=actxserver('MotionTracker.FilterComponent'); try % use try-catch to avoid the need to shutdown MATLAB if m-function fails (e.g. during debugging) % This is needed because MATLAB does not properly release COM-objects when % the m-function fails/crasehes and the object is not explicitly released with "delete(h)" % call MT_SetCOMPort is required, unless using COM 1 h.MT_SetCOMPort(COMport); % request the Sample Frequency (update rate) of the MTi or MTx SF = h.MT_GetMotionTrackerSampleFrequency; % call MT_SetFilterSettings is optional h.MT_SetFilterSettings(filterSettings_gain,filterSettings_corr,filterSettings_weight); % init figure plotting variables % set time scale zoom level zoom_levels=[12*SF,8*SF,4*SF]; % in seconds zoom_level=zoom_levels(zoom_level_setting); OldFigureUserData = [0 0 0]; status = 0; last_t=0; % default vertical zoom YLims = [-22 22; -1200 1200; -1.8 1.8; -1 1]; ResetFigure =1; first_time=1; % create figure % NOTE, the releasing of MTObj is done in the Figure Close Request function % "mt_figure_close" [f_handle, p_handle] = mt_create_figure(OldFigureUserData(3), -1 ,h, YLims, SF,... zoom_level, OldFigureUserData); % choose what data to ask from MTObj if strcmp(DisplayMode,'caldata') Channels = 10; % request calibrated inertial and magnetic data h.MT_SetCalibratedOutput(1); % set figure UserData to appropriate values (format: % [MT_being_plotted, Zoom, PlotType]) set(f_handle,'UserData', [0 0 0]) elseif strcmp(DisplayMode,'euler') Channels = 3; % request orientation data in Euler-angles h.MT_SetOutputMode(1); % set figure UserData to appropriate values (format: % [MT_being_plotted, Zoom, PlotType]) set(f_handle,'UserData', [0 0 4]) elseif strcmp(DisplayMode,'quat') Channels = 4; % request orientation data in quaternions h.MT_SetOutputMode(0); % set figure UserData to appropriate values (format: % [MT_being_plotted, Zoom, PlotType]) set(f_handle,'UserData', [0 0 5]) elseif strcmp(DisplayMode,'matrix') Channels = 9; % request orientation data in DCM rotation matrix h.MT_SetOutputMode(2); % set figure UserData to appropriate values (format: % [MT_being_plotted, Zoom, PlotType]) set(f_handle,'UserData', [0 0 6]) else disp('unkown mode....stopping, check variable "Channels"!!') % clean up, release MTObj delete(h); clear h; end % That's it! % MTObj is ready to start processing the data stream from the MTi or MTx h.MT_StartProcess; % start processing data % init data variable d=zeros(1,Channels); last_d = d; while ishandle(f_handle) && ishandle(h), % check if all objects are alive if status ~= 0, last_d=d(end,:); end % retreive data from MTObj object [d,status,N]=MT_get_data(h, Channels); % Now the data is available! The rest of the code is only to % display the data and to make it look nice and smooth on display.... if status==1, % default mode... % retrieve values from figure CurrentFigureUserData = get(f_handle,'UserData'); if ResetFigure ==1, % check if figure should be reset last_t=0; % wrap plot around figureUserData = get(f_handle,'UserData'); % call local function to (re)setup figure [f_handle, p_handle] = mt_create_figure(CurrentFigureUserData(3), f_handle,h, YLims, SF, zoom_level, figureUserData); ResetFigure = 0; end % create timebase t=[last_t:last_t+N]./SF; last_t=last_t+N; % check if figures should be reset if any(CurrentFigureUserData ~= OldFigureUserData), % check if figure UserData changed by KeyPress ResetFigure =1; % make sure plot is reset first_time =1; % re-initialize zoom levels too elseif last_t>zoom_level || first_time==1 ResetFigure =1; % make sure plot is reset first_time =0; YLims = mt_plot_data(d, last_d, t, CurrentFigureUserData, p_handle); else % other wise --> plot % plot the data using a local funtion YLims = mt_plot_data(d, last_d, t, CurrentFigureUserData, p_handle); end OldFigureUserData = CurrentFigureUserData; elseif status>1, % MTObj not correctly configured, stopping [str_out]=MT_return_error(status); disp(str_out); disp('MTObj not correctly configured, stopping.....'); break end % if end % while % release MTObj is done on figure close...not here if ishandle(f_handle), % check to make sure figure is not already gone close(f_handle) end catch % try catch for debugging % make sure MTObj is released even on error h.MT_StopProcess; delete(h); clear h; % display some information for tracing errors disp('Error was catched by try-catch.....MTobj released') crashInfo = lasterror; % retrieve last error message from MATLAB disp('Line:') crashInfo.stack.line disp('Name:') crashInfo.stack.name disp('File:') crashInfo.stack.file rethrow(lasterror) end % ------------------------------------------------------------------------- % end of function MT_DisplayRealtimeData(varargin); %% ------------------------------------------------------------------------- % LOCAL FUNCTIONS % ------------------------------------------------------------------------- function [f_handle, p_handle] = mt_create_figure(type, f_handle, h, YLims,SF, zoom_level, figureUserData) % local function to create the figure for real time plotting of data. % accepts plot type information for custom plots % % if figure does not yet exist enter -1 in figure_handle input if ~ishandle(f_handle), % create figure f_handle = figure('Name','Real-time display of MTi or MTx data','NumberTitle','off'); end fontSizeUsed = 12; axisName = {'X' 'Y' 'Z'}; eulerName = {'Roll' 'Pitch' 'Yaw'}; quatName = {'img w q_0' 'x q_1' 'y q_2' 'z q_3'}; % init p_handle = zeros(9); a_handle = zeros(9); switch type case 0% calibrated inertial and magnetic data(default) for i=1:9, subplot(3,3,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(mod(i-1,3)+1,:)]); grid on; end tlh = title(a_handle(1),['Acceleration [m/s^2] (press A)']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel(a_handle(7),'time [s]'); ylh = ylabel(a_handle(1),'X_S'); tlh = title(a_handle(2),['Gyro [deg/s] (press G)']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel(a_handle(8),'time [s]'); ylh = ylabel(a_handle(4),'Y_S'); tlh = title(a_handle(3),['Magnetometer [a.u.] (press M)']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel(a_handle(9),'time [s]'); ylh = ylabel(a_handle(7),'Z_S'); case 1 %'acc' (only accelerometer) for i=1:3, subplot(3,1,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(i,:)]); grid on; ylh = ylabel(a_handle(i),[axisName{i} '_S acceleration [m/s^2]']); set(ylh,'FontSize',fontSizeUsed-1); end tlh = title(a_handle(1),['Accelerometer data']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel('time [s]'); set(xlh,'FontSize',fontSizeUsed); case 2 % 'gyr' (only gyroscopes) for i=1:3, subplot(3,1,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(i,:)]); grid on; ylh = ylabel(a_handle(i),[axisName(i) '_S angular rate [deg/s]']); set(ylh,'FontSize',fontSizeUsed-1); end tlh = title(a_handle(1),['Rate gyroscope data']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel('time [s]'); set(xlh,'FontSize',fontSizeUsed); case 3 % 'mag' (only magnetometers) for i=1:3, subplot(3,1,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(i,:)]); grid on; ylh = ylabel(a_handle(i),[axisName(i) '_S magnetometer [a.u.]']); set(ylh,'FontSize',fontSizeUsed-1); end tlh = title(a_handle(1),['Magnetometer data']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel('time [s]'); set(xlh,'FontSize',fontSizeUsed); case 4 % Euler angles for i=1:3, subplot(3,1,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(i,:)]); grid on; ylh = ylabel(a_handle(i),[eulerName(i) ' [deg]']); set(ylh,'FontSize',fontSizeUsed-1); end tlh = title(a_handle(1),['Euler angle orientation data']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel('time [s]'); set(xlh,'FontSize',fontSizeUsed); if figureUserData(2)==0, % try to get nice scales on graphs set(a_handle(1),'ytick',[-180:45:180]); set(a_handle(2),'ytick',[-90:45:90]); set(a_handle(3),'ytick',[-180:45:180]); elseif figureUserData==1, set(a_handle(1),'ytick',[-180:2:180]); set(a_handle(2),'ytick',[-90:2:90]); set(a_handle(3),'ytick',[-180:2:180]); end case 5 % Quaternion for i=1:4, subplot(4,1,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(i,:)]); grid on; ylh = ylabel(a_handle(i),quatName(i)); set(ylh,'FontSize',fontSizeUsed-1); end tlh = title(a_handle(1),['Quaternion orientation data q_G_S']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel('time [s]'); set(xlh,'FontSize',fontSizeUsed); case 6 % DCM rotation matrix p_handle(1)=surf(zeros(4,4),'EraseMode','none'); a_handle(1) = gca; tlh = title(['Rotation Matrix Output R_G_S - MTi / MTx']); set(tlh,'FontSize',fontSizeUsed,'Color','white'); axis ij; xlh = xlabel('cols'); ylh_1 = ylabel('rows'); % set(f_handle,'Renderer','OpenGL'); % Use OpenGL renderer for smoother plotting set(f_handle,'Color','black','Colormap',colormap(hsv)); view(2); shading flat; set(a_handle(1),'CLim',[-1 1]); cbh = colorbar('vert'); set(cbh,'YColor','white') end set(f_handle,'CloseRequestFcn',{@mt_figure_close,h,f_handle}); set(f_handle,'KeyPressFcn',{@mt_figure_keypress,h,f_handle}); set(f_handle,'UserData', figureUserData); % ------------------------------------------------------------------------- % end of function %% ------------------------------------------------------------------------- function mt_figure_keypress(obj, eventdata, h, f_handle) % local function to handle KeyPress events on figure. % Is used to (P)ause plot, (Z)oom in/out, (D)efault display, % (A)ccelerometer only, rate (G)yro only, (M)agnetometer only % % envoked when a key is pressed when figure is in focus in_key=lower(get(f_handle,'CurrentCharacter')); tmp = get(f_handle,'UserData'); switch in_key case 'p' % pause to view graph disp('Paused, press any key to continue...') pause(0.2);% introduce a slight break, because otherwise 1 keystroke is recorded as multiple figure(f_handle);% raise figure to foreground pause; % wait for next key stroke case 'z' % toggle zoom mode pause(0.2) figure(f_handle) if tmp(2) == 0, % check zoom level set(f_handle,'UserData',[tmp(1) 1 tmp(3)]); % toggle to next zoom mode else set(f_handle,'UserData',[tmp(1) 0 tmp(3)]); % toggle to default zoom mode end case 'r' % reset orientation disp('Resetting heading orientation (boresight)...') pause(0.2);% introduce a slight break, because otherwise 1 keystroke is recorded as multiple figure(f_handle);% raise figure to foreground MT_ResetOrientation(h,0,0); % default reset type 0 = heading, do not save to MTS = 0 (second parameter) case 'a' disp('Switching to display only 3D accelerometer data stream...') pause(0.2) figure(f_handle) set(f_handle,'UserData',[tmp(1:2) 1]); % set to accelerometer mode case 'g' disp('Switching to display only 3D rate gyroscope data stream...') pause(0.2) figure(f_handle) set(f_handle,'UserData',[tmp(1:2) 2]); % set to gyro mode case 'm' disp('Switching to display only 3D magnetometer data stream...') pause(0.2) figure(f_handle) set(f_handle,'UserData',[tmp(1:2) 3]); % set to mag mode case 'd' disp('Switching the default display mode, all 9 data streams...') pause(0.2) figure(f_handle) set(f_handle,'UserData',[tmp(1:2) 0]); % set to default mode case 'q' disp('Quitting demo MT_DisplayRealtimeData...') pause(0.2) figure(f_handle) close(f_handle) otherwise disp('Unknown command option....displaying help data') disp(' ') eval('help MT_DisplayRealtimeData') end if ishandle(f_handle) % needed to check if figure exists (using Q to quit) if tmp(3)>3,% If in Orientation output mode, IGNORE any change in PlotMode!!! tmp_new = get(f_handle,'UserData'); set(f_handle,'UserData',[tmp_new(1:2) tmp(3)]); end % reset CurrentCharater to no value... set(f_handle,'CurrentCharacter',' '); end % ------------------------------------------------------------------------- % end of function %% ------------------------------------------------------------------------- function YLims = mt_plot_data(d, last_d, t, CurrentFigureUserData, p_handle) % local function to plot the data using "low-level" set fucntions for smooth plotting switch CurrentFigureUserData(3) % check plot type case 0 %default if CurrentFigureUserData(2), % check if zoomed band = [0.8 50 0.1]; % define zoom range YLims = [min(d(1,1:3))-band(1) max(d(1,1:3))+band(1); min(d(1,4:6)./pi.*180)-band(2) max(d(1,4:6)./pi.*180)+band(2);... min(d(1,7:9))-band(3) max(d(1,7:9))+band(3)]; else % default values of zoom (full range of MT9) YLims = [-22 22; -1200 1200; -1.8 1.8]; end % plot the data set(p_handle(1),'XData',t,'YData',[last_d(1,1) d(:,1)'],'Color','b','LineWidth',2) set(p_handle(4),'XData',t,'YData',[last_d(1,2) d(:,2)'],'Color','g','LineWidth',2) set(p_handle(7),'XData',t,'YData',[last_d(1,3) d(:,3)'],'Color','r','LineWidth',2) % convert the rate of turn data to deg/s instead of rad/s set(p_handle(2),'XData',t,'YData',([last_d(1,4) d(:,4)'])./pi.*180,'Color','b','LineWidth',2) set(p_handle(5),'XData',t,'YData',([last_d(1,5) d(:,5)'])./pi.*180,'Color','g','LineWidth',2) set(p_handle(8),'XData',t,'YData',([last_d(1,6) d(:,6)'])./pi.*180,'Color','r','LineWidth',2) set(p_handle(3),'XData',t,'YData',[last_d(1,7) d(:,7)'],'Color','b','LineWidth',2) set(p_handle(6),'XData',t,'YData',[last_d(1,8) d(:,8)'],'Color','g','LineWidth',2) set(p_handle(9),'XData',t,'YData',[last_d(1,9) d(:,9)'],'Color','r','LineWidth',2) case 1 % Only accelerometer if CurrentFigureUserData(2), % check if zoomed band = 0.8; % define zoom range (in m/s2) YLims = [min(d(:,1))-band max(d(:,1))+band; min(d(:,2))-band max(d(:,2))+band; ... min(d(:,3))-band max(d(:,3))+band]; else % default values of zoom (full range of MT9) YLims = [-25 25; -25 25; -25 25]; end % plot the data set(p_handle(1),'XData',t,'YData',[last_d(1,1) d(:,1)'],'Color','b','LineWidth',2) set(p_handle(2),'XData',t,'YData',[last_d(1,2) d(:,2)'],'Color','g','LineWidth',2) set(p_handle(3),'XData',t,'YData',([last_d(1,3) d(:,3)']),'Color','r','LineWidth',2) case 2 % Only rate gyros if CurrentFigureUserData(2), % check if zoomed band = 50; % define zoom range (in deg/s) YLims = [min(d(:,4)./pi.*180)-band max(d(:,4)./pi.*180)+band;... min(d(:,5)./pi.*180)-band max(d(:,5)./pi.*180)+band; min(d(:,6)./pi.*180)-band max(d(:,6)./pi.*180)+band]; else % default values of zoom (full range of MT9) YLims = [-1200 1200; -1200 1200; -1200 1200]; end % plot the data set(p_handle(1),'XData',t,'YData',([last_d(1,4) d(:,4)'])./pi.*180,'Color','b','LineWidth',2) set(p_handle(2),'XData',t,'YData',([last_d(1,5) d(:,5)'])./pi.*180,'Color','g','LineWidth',2) set(p_handle(3),'XData',t,'YData',([last_d(1,6) d(:,6)'])./pi.*180,'Color','r','LineWidth',2) case 3 % Only magnetometers if CurrentFigureUserData(2), % check if zoomed band = 0.1; % define zoom range (in a.u.) YLims = [min(d(:,7))-band max(d(:,7))+band; min(d(:,8))-band max(d(:,8))+band; min(d(:,9))-band max(d(:,9))+band]; else % default values of zoom (full range of MT9) YLims = [-2.5 2.5; -2.5 2.5; -2.5 2.5]; end % plot the data set(p_handle(1),'XData',t,'YData',[last_d(1,7) d(:,7)'],'Color','b','LineWidth',2) set(p_handle(2),'XData',t,'YData',[last_d(1,8) d(:,8)'],'Color','g','LineWidth',2) set(p_handle(3),'XData',t,'YData',[last_d(1,9) d(:,9)'],'Color','r','LineWidth',2) case 4 % Euler angles if CurrentFigureUserData(2), % zoom UserData band = 6; % define zoom range (in degrees) YLims = [min(d(:,1))-band max(d(:,1))+band; min(d(:,2))-band max(d(:,2))+band; ... min(d(:,3))-band max(d(:,3))+band]; else % default values of zoom (full range of Euler angles) YLims = [-180 180;-90 90;-180 180]; end set(p_handle(1),'XData',t,'YData',[last_d(1,1) d(:,1)'],'Color','b','LineWidth',2) set(p_handle(2),'XData',t,'YData',[last_d(1,2) d(:,2)'],'Color','g','LineWidth',2) set(p_handle(3),'XData',t,'YData',[last_d(1,3) d(:,3)'],'Color','r','LineWidth',2) case 5 % Quaternions if CurrentFigureUserData(2), % zoom UserData band = 0.14; % define zoom range YLims = [min(d(1,1))-band max(d(1,1))+band; min(d(1,2))-band max(d(1,2))+band;... min(d(1,3))-band max(d(1,3))+band; min(d(1,4))-band max(d(1,4))+band]; % not so useful for quaternions... else % default values of zoom (full range of Euler angles) YLims = [-1 1; -1 1; -1 1; -1 1;]; end set(p_handle(1),'XData',t,'YData',[last_d(1,1) d(:,1)'],'Color','k','LineWidth',2) set(p_handle(2),'XData',t,'YData',[last_d(1,2) d(:,2)'],'Color','b','LineWidth',2) set(p_handle(3),'XData',t,'YData',[last_d(1,3) d(:,3)'],'Color','g','LineWidth',2) set(p_handle(4),'XData',t,'YData',[last_d(1,4) d(:,4)'],'Color','r','LineWidth',2) case 6 % Matrix YLims = [0 4]; % not used % only display latest data available in DCM orientation matrix mode set(p_handle(1),'cdata',[d(end,1:3); d(end,4:6); d(end,7:9)]'); end % switch % flush the graphics to screen drawnow % ------------------------------------------------------------------------- % end of function %% ------------------------------------------------------------------------- function mt_figure_close(obj, eventdata, h, f_handle) % local function to properly release MTObj when the user kills the figure window. % release MTObj MT_StopProcess(h) delete(h); clear h; % kill figure window as requested delete(f_handle) % ------------------------------------------------------------------------- % end of function
github
umariqb/3D_Pose_Estimation_CVPR2016-master
XM_DisplayRealtimeData.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/XSensMatlab/XM_DisplayRealtimeData.m
24,551
utf_8
dd8819c5bd670a9720d47dff072c9c2d
function XM_DisplayRealtimeData(varargin) %% XM_DisplayRealtimeData(varargin); % % Real-time display of calibrated data or 3D orientation data from an MTi % or MTx % % varargin: Input arguments % 1. COM-port [integer] to which Xbus Master is connected (default = 1 , i.e. COM1) % 2. Display mode [string], choose to view: % 'caldata' Calibrated inertial and magnetic data (default) % 'euler' Orientation output in Euler-angles (see Tech Doc for definition) % 'quat' Orientation output in Quaternions % 'matrix' Orientation output in rotation Matrix format % 3. zoom-level, [1=12 s chart, 2=8 s chart (default), 3=4 s chart] % 4. update rate, [1=slow, 2=medium (default), 3=fast] % % example function call: % "XM_DisplayRealtimeData(1,'euler',2,3)" % % Press key on keyboard while running: % % Calibrated Inertial and magnetic data MODE: % "Q" = Quit % "]" = Switch to display next MTx connected on Xbus % "P" = Pause/Start real-time plot % "Z" = Toggle Zoom in/out % "A" = View only accelerometer data % "G" = View only rate gyro data % "M" = View only magnetometer data % "D" = View all MTi / MTx data (default) % % Orientation data output MODE: % "Q" = Quit % "P" = Pause/Start real-time plot % "R" = Reset reference orientation (refer to Tech Doc for details) % "Z" = Zoom in/out (not applicable for Matrix output mode) % (it is not possible to switch orientation output mode during run-time) % % Xsens Technologies B.V., 2002-2007 % v.2.8.4 % tested to be compatible with MATLAB 2006b. % The display code in this demo code has been changed due to a bug in MATLAB 7.x % please refer to: % http://www.mathworks.com/support/bugreports/details.html?rp=207276 % Check to see if number of input arguments is correct if nargin>4, error('too many input arguments') end % set default values if needed defaultValues={4,'caldata',2,1.0,1,1.0}; nonemptyIdx=~cellfun('isempty',varargin); defaultValues(nonemptyIdx)=varargin(nonemptyIdx); [COMport,DisplayMode,zoom_level_setting,filterSettings_gain,filterSettings_corr,filterSettings_weight]... =deal(defaultValues{:}); % set up MTObj h=actxserver('MotionTracker.FilterComponent'); try % use try-catch to avoid the need to shutdown MATLAB if m-function fails (e.g. during debugging) % This is needed because MATLAB does not properly release COM-objects when % the m-function fails/crasehes and the object is not explicitly released with "delete(h)" % call XM_SetCOMPort is required, unless using COM 1 h.XM_SetCOMPort(COMport); % request the Sample Frequency (update rate) of the MTi or MTx SF = h.XM_GetXbusMasterSampleFrequency; % Query XM for connected sensors [num_MTs,DIDs]=h.XM_QueryXbusMasterB; if num_MTs==0, disp('Xbus Master not found or no sensors found by Xbus Master...exiting.') disp('Did you select the correct COM-port?') delete(h); clear h; close(f_handle) return end for i=1:num_MTs, % Note: Creating Cell array of device IDs for use in Set functions % below MT_IDs{i} = DIDs((i*8 - 7):(i*8)); h.XM_SetFilterSettings(char(MT_IDs(i)),filterSettings_gain,filterSettings_corr, filterSettings_weight); end % init figure plotting variables % set time scale zoom level zoom_levels=[12*SF,8*SF,4*SF]; % in seconds zoom_level=zoom_levels(zoom_level_setting); OldFigureUserData = [0 0 0]; status = 0; last_t=0; % default vertical zoom YLims = [-22 22; -1200 1200; -1.8 1.8; -1 1]; ResetFigure =1; first_time=1; % create figure % NOTE, the releasing of MTObj is done in the Figure Close Request function % "mt_figure_close" [f_handle, p_handle] = xm_create_figure(OldFigureUserData(3), -1 ,h, YLims, SF,... zoom_level, OldFigureUserData, 1, ' '); % choose what data to ask from MTObj and store in figure UserData if strcmp(DisplayMode,'caldata') Channels = 10; % request calibrated inertial and magnetic data h.XM_SetCalibratedOutput(1); % set figure UserData to appropriate values (format: % [MT_being_plotted, Zoom, PlotType]) set(f_handle,'UserData', [0 0 0]) elseif strcmp(DisplayMode,'euler') Channels = 3; % request orientation data in Euler-angles h.XM_SetOutputMode(1); % set figure UserData to appropriate values (format: % [MT_being_plotted, Zoom, PlotType]) set(f_handle,'UserData', [0 0 4]) elseif strcmp(DisplayMode,'quat') Channels = 4; % request orientation data in quaternions h.XM_SetOutputMode(0); % set figure UserData to appropriate values (format: % [MT_being_plotted, Zoom, PlotType]) set(f_handle,'UserData', [0 0 5]) elseif strcmp(DisplayMode,'matrix') Channels = 9; % request orientation data in DCM rotation matrix h.XM_SetOutputMode(2); % set figure UserData to appropriate values (format: % [MT_being_plotted, Zoom, PlotType]) set(f_handle,'UserData', [0 0 6]) else disp('unkown mode....stopping, check variable "Channels"!!') % clean up, release MTObj delete(h); clear h; end % That's it! % MTObj is ready to start processing the data stream from the MTi or MTx h.XM_StartProcess; % start processing data % init data variable d=zeros(1,Channels); last_d = d; MT_BeingPlotted = 1; while ishandle(f_handle) && ishandle(h), % check if all objects are alive if status ~= 0, last_d=d(end,:); end % retreive data from MTObj object [d,status,N]=XM_get_data(h, Channels, MT_BeingPlotted); % Now the data is available! The rest of the code is only to % display the data and to make it look nice and smooth on display.... if status==1, % default mode... % retrieve values from figure CurrentFigureUserData = get(f_handle,'UserData'); if ResetFigure ==1, % check if figure should be reset last_t=0; % wrap plot around figureUserData = get(f_handle,'UserData'); % call local function to (re)setup figure [f_handle, p_handle] = xm_create_figure(CurrentFigureUserData(3), f_handle,h, YLims, SF,... zoom_level, figureUserData, MT_BeingPlotted, MT_IDs); ResetFigure = 0; end % create timebase t=[last_t:last_t+N]./SF; last_t=last_t+N; % check if to change MTx being plotted if CurrentFigureUserData(1) MT_BeingPlotted = mod(MT_BeingPlotted+1,num_MTs); if MT_BeingPlotted==0, MT_BeingPlotted = num_MTs; end CurrentFigureUserData(1) = 0;% reset next MT toggle set(f_handle,'UserData', CurrentFigureUserData); ResetFigure =1; % make sure plot is reset first_time =1; % re-initialize zoom levels too % check if figures should be reset elseif any(CurrentFigureUserData ~= OldFigureUserData), % check if figure UserData changed by KeyPress ResetFigure =1; % make sure plot is reset first_time =1; % re-initialize zoom levels too elseif last_t>zoom_level || first_time==1 ResetFigure =1; % make sure plot is reset first_time =0; YLims = mt_plot_data(d, last_d, t, CurrentFigureUserData, p_handle); else % other wise --> plot % plot the data using a local funtion YLims = mt_plot_data(d, last_d, t, CurrentFigureUserData, p_handle); end OldFigureUserData = CurrentFigureUserData; elseif status>1, % MTObj not correctly configured, stopping [str_out]=MT_return_error(status); disp(str_out); disp('MTObj not correctly configured, stopping.....'); break end % if end % while % release MTObj is done on figure close...not here if ishandle(f_handle), % check to make sure figure is not already gone close(f_handle) end catch % try catch for debugging % make sure MTObj is released even on error h.XM_StopProcess; delete(h); clear h; % display some information for tracing errors disp('Error was catched by try-catch.....MTobj released') crashInfo = lasterror; % retrieve last error message from MATLAB disp('Line:') crashInfo.stack.line disp('Name:') crashInfo.stack.name disp('File:') crashInfo.stack.file rethrow(lasterror) end % ------------------------------------------------------------------------- % end of function XM_DisplayRealtimeData(varargin); %% ------------------------------------------------------------------------- % LOCAL FUNCTIONS % ------------------------------------------------------------------------- function [f_handle, p_handle] = xm_create_figure(type, f_handle, h, YLims,SF, zoom_level, figureUserData, MT_BeingPlotted, MT_IDs) % local function to create the figure for real time plotting of data. % accepts plot type information for custom plots % % if figure does not yet exist enter -1 in figure_handle input if ~ishandle(f_handle), % create figure f_handle = figure('Name','Real-time display of MTi or MTx data','NumberTitle','off'); end fontSizeUsed = 12; axisName = {'X' 'Y' 'Z'}; eulerName = {'Roll' 'Pitch' 'Yaw'}; quatName = {'img w q_0' 'x q_1' 'y q_2' 'z q_3'}; % init p_handle = zeros(9); a_handle = zeros(9); figure(f_handle); % raise figure switch type case 0% calibrated inertial and magnetic data(default) for i=1:9, subplot(3,3,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(mod(i-1,3)+1,:)]); grid on; end tlh = title(a_handle(1),['Acceleration [m/s^2] (press A)']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel(a_handle(7),'time [s]'); ylh = ylabel(a_handle(1),'X_S'); tlh = title(a_handle(2),['Gyro [deg/s] (press G)']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel(a_handle(8),'time [s]'); ylh = ylabel(a_handle(4),'Y_S'); tlh = title(a_handle(3),['Magnetometer [a.u.] (press M)']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel(a_handle(9),'time [s]'); ylh = ylabel(a_handle(7),'Z_S'); case 1 %'acc' (only accelerometer) for i=1:3, subplot(3,1,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(i,:)]); grid on; ylh = ylabel(a_handle(i),[axisName{i} '_S acceleration [m/s^2]']); set(ylh,'FontSize',fontSizeUsed-1); end tlh = title(a_handle(1),['Accelerometer data']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel('time [s]'); set(xlh,'FontSize',fontSizeUsed); case 2 % 'gyr' (only gyroscopes) for i=1:3, subplot(3,1,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(i,:)]); grid on; ylh = ylabel(a_handle(i),[axisName(i) '_S angular rate [deg/s]']); set(ylh,'FontSize',fontSizeUsed-1); end tlh = title(a_handle(1),['Rate gyroscope data']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel('time [s]'); set(xlh,'FontSize',fontSizeUsed); case 3 % 'mag' (only magnetometers) for i=1:3, subplot(3,1,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(i,:)]); grid on; ylh = ylabel(a_handle(i),[axisName(i) '_S magnetometer [a.u.]']); set(ylh,'FontSize',fontSizeUsed-1); end tlh = title(a_handle(1),['Magnetometer data']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel('time [s]'); set(xlh,'FontSize',fontSizeUsed); case 4 % Euler angles for i=1:3, subplot(3,1,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(i,:)]); grid on; ylh = ylabel(a_handle(i),[eulerName(i) ' [deg]']); set(ylh,'FontSize',fontSizeUsed-1); end tlh = title(a_handle(1),['Euler angle orientation data']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel('time [s]'); set(xlh,'FontSize',fontSizeUsed); if figureUserData(2)==0, % try to get nice scales on graphs set(a_handle(1),'ytick',[-180:45:180]); set(a_handle(2),'ytick',[-90:45:90]); set(a_handle(3),'ytick',[-180:45:180]); elseif figureUserData==1, set(a_handle(1),'ytick',[-180:2:180]); set(a_handle(2),'ytick',[-90:2:90]); set(a_handle(3),'ytick',[-180:2:180]); end case 5 % Quaternion for i=1:4, subplot(4,1,i), p_handle(i)=plot(0,0,'EraseMode','none');a_handle(i) = gca; axis(a_handle(i),[0 (zoom_level+1)./SF YLims(i,:)]); grid on; ylh = ylabel(a_handle(i),quatName(i)); set(ylh,'FontSize',fontSizeUsed-1); end tlh = title(a_handle(1),['Quaternion orientation data q_G_S']); set(tlh,'FontSize',fontSizeUsed); xlh = xlabel('time [s]'); set(xlh,'FontSize',fontSizeUsed); case 6 % DCM rotation matrix subplot(1,1,1), p_handle(1)=surf(zeros(4,4),'EraseMode','none'); a_handle(1) = gca; tlh = title(['Rotation Matrix Output R_G_S - MTi / MTx']); set(tlh,'FontSize',fontSizeUsed,'Color','white'); axis ij; xlh = xlabel('cols'); ylh_1 = ylabel('rows'); % set(f_handle,'Renderer','OpenGL'); % Use OpenGL renderer for smoother plotting set(f_handle,'Color','black','Colormap',colormap(hsv)); view(2); shading flat; set(a_handle(1),'CLim',[-1 1]); cbh = colorbar('vert'); set(cbh,'YColor','white') end % add text about which MTx data is displayed from % text will be displayed wrt last axis active... vertPos = 1.25* min(get(gca,'Ylim'))- 0.25 * max(get(gca,'YLim')); txtMT_DID = text(0,vertPos,['MTx number ' num2str(MT_BeingPlotted) ': MTx DID = ' char(MT_IDs(MT_BeingPlotted))]); set(txtMT_DID,'FontSize',fontSizeUsed+1); set(f_handle,'CloseRequestFcn',{@mt_figure_close,h,f_handle}); set(f_handle,'KeyPressFcn',{@mt_figure_keypress,h,f_handle}); set(f_handle,'UserData', figureUserData); % ------------------------------------------------------------------------- % end of function %% ------------------------------------------------------------------------- function mt_figure_keypress(obj, eventdata, h, f_handle) % local function to handle KeyPress events on figure. % Is used to (P)ause plot, (Z)oom in/out, (D)efault display, % (A)ccelerometer only, rate (G)yro only, (M)agnetometer only % % envoked when a key is pressed when figure is in focus in_key=lower(get(f_handle,'CurrentCharacter')); tmp = get(f_handle,'UserData'); switch in_key case ']' % view next connected sensor... pause(0.2) figure(f_handle); tmp = get(f_handle,'UserData'); tmp(1) = 1;% indicate that next MT9 should be plotted set(f_handle,'UserData', tmp); case 'p' % pause to view graph disp('Paused, press any key to continue...') pause(0.2);% introduce a slight break, because otherwise 1 keystroke is recorded as multiple figure(f_handle);% raise figure to foreground pause; % wait for next key stroke case 'z' % toggle zoom mode pause(0.2) figure(f_handle) if tmp(2) == 0, % check zoom level set(f_handle,'UserData',[tmp(1) 1 tmp(3)]); % toggle to next zoom mode else set(f_handle,'UserData',[tmp(1) 0 tmp(3)]); % toggle to default zoom mode end case 'r' % reset orientation disp('Resetting heading orientation (boresight)...') pause(0.2);% introduce a slight break, because otherwise 1 keystroke is recorded as multiple figure(f_handle);% raise figure to foreground XM_ResetOrientation(h,0,0); % default reset type 0 = heading, do not save to MTS = 0 (second parameter) case 'a' disp('Switching to display only 3D accelerometer data stream...') pause(0.2) figure(f_handle) set(f_handle,'UserData',[tmp(1:2) 1]); % set to accelerometer mode case 'g' disp('Switching to display only 3D rate gyroscope data stream...') pause(0.2) figure(f_handle) set(f_handle,'UserData',[tmp(1:2) 2]); % set to gyro mode case 'm' disp('Switching to display only 3D magnetometer data stream...') pause(0.2) figure(f_handle) set(f_handle,'UserData',[tmp(1:2) 3]); % set to mag mode case 'd' disp('Switching the default display mode, all 9 data streams...') pause(0.2) figure(f_handle) set(f_handle,'UserData',[tmp(1:2) 0]); % set to default mode case 'q' disp('Quitting demo XM_DisplayRealtimeData...') pause(0.2) figure(f_handle) close(f_handle) otherwise disp('Unknown command option....displaying help data') disp(' ') eval('help XM_DisplayRealtimeData') end if ishandle(f_handle) % needed to check if figure exists (using Q to quit) if tmp(3)>3,% If in Orientation output mode, IGNORE any change in PlotMode!!! tmp_new = get(f_handle,'UserData'); set(f_handle,'UserData',[tmp_new(1:2) tmp(3)]); end % reset CurrentCharater to no value... set(f_handle,'CurrentCharacter',' '); end % ------------------------------------------------------------------------- % end of function %% ------------------------------------------------------------------------- function YLims = mt_plot_data(d, last_d, t, CurrentFigureUserData, p_handle) % local function to plot the data using "low-level" set fucntions for smooth plotting switch CurrentFigureUserData(3) % check plot type case 0 %default if CurrentFigureUserData(2), % check if zoomed band = [0.8 40 0.1]; % define zoom range YLims = [min(d(1,1:3))-band(1) max(d(1,1:3))+band(1); min(d(1,4:6)./pi.*180)-band(2) max(d(1,4:6)./pi.*180)+band(2);... min(d(1,7:9))-band(3) max(d(1,7:9))+band(3)]; else % default values of zoom (full range of MT9) YLims = [-22 22; -1200 1200; -1.8 1.8]; end % plot the data set(p_handle(1),'XData',t,'YData',[last_d(1,1) d(:,1)'],'Color','b','LineWidth',2) set(p_handle(4),'XData',t,'YData',[last_d(1,2) d(:,2)'],'Color','g','LineWidth',2) set(p_handle(7),'XData',t,'YData',[last_d(1,3) d(:,3)'],'Color','r','LineWidth',2) % convert the rate of turn data to deg/s instead of rad/s set(p_handle(2),'XData',t,'YData',([last_d(1,4) d(:,4)'])./pi.*180,'Color','b','LineWidth',2) set(p_handle(5),'XData',t,'YData',([last_d(1,5) d(:,5)'])./pi.*180,'Color','g','LineWidth',2) set(p_handle(8),'XData',t,'YData',([last_d(1,6) d(:,6)'])./pi.*180,'Color','r','LineWidth',2) set(p_handle(3),'XData',t,'YData',[last_d(1,7) d(:,7)'],'Color','b','LineWidth',2) set(p_handle(6),'XData',t,'YData',[last_d(1,8) d(:,8)'],'Color','g','LineWidth',2) set(p_handle(9),'XData',t,'YData',[last_d(1,9) d(:,9)'],'Color','r','LineWidth',2) case 1 % Only accelerometer if CurrentFigureUserData(2), % check if zoomed band = 0.8; % define zoom range (in m/s2) YLims = [min(d(:,1))-band max(d(:,1))+band; min(d(:,2))-band max(d(:,2))+band; ... min(d(:,3))-band max(d(:,3))+band]; else % default values of zoom (full range of MT9) YLims = [-25 25; -25 25; -25 25]; end % plot the data set(p_handle(1),'XData',t,'YData',[last_d(1,1) d(:,1)'],'Color','b','LineWidth',2) set(p_handle(2),'XData',t,'YData',[last_d(1,2) d(:,2)'],'Color','g','LineWidth',2) set(p_handle(3),'XData',t,'YData',([last_d(1,3) d(:,3)']),'Color','r','LineWidth',2) case 2 % Only rate gyros if CurrentFigureUserData(2), % check if zoomed band = 40; % define zoom range (in deg/s) YLims = [min(d(:,4)./pi.*180)-band max(d(:,4)./pi.*180)+band;... min(d(:,5)./pi.*180)-band max(d(:,5)./pi.*180)+band; min(d(:,6)./pi.*180)-band max(d(:,6)./pi.*180)+band]; else % default values of zoom (full range of MT9) YLims = [-1200 1200; -1200 1200; -1200 1200]; end % plot the data set(p_handle(1),'XData',t,'YData',([last_d(1,4) d(:,4)'])./pi.*180,'Color','b','LineWidth',2) set(p_handle(2),'XData',t,'YData',([last_d(1,5) d(:,5)'])./pi.*180,'Color','g','LineWidth',2) set(p_handle(3),'XData',t,'YData',([last_d(1,6) d(:,6)'])./pi.*180,'Color','r','LineWidth',2) case 3 % Only magnetometers if CurrentFigureUserData(2), % check if zoomed band = 0.1; % define zoom range (in a.u.) YLims = [min(d(:,7))-band max(d(:,7))+band; min(d(:,8))-band max(d(:,8))+band; min(d(:,9))-band max(d(:,9))+band]; else % default values of zoom (full range of MT9) YLims = [-2.5 2.5; -2.5 2.5; -2.5 2.5]; end % plot the data set(p_handle(1),'XData',t,'YData',[last_d(1,7) d(:,7)'],'Color','b','LineWidth',2) set(p_handle(2),'XData',t,'YData',[last_d(1,8) d(:,8)'],'Color','g','LineWidth',2) set(p_handle(3),'XData',t,'YData',[last_d(1,9) d(:,9)'],'Color','r','LineWidth',2) case 4 % Euler angles if CurrentFigureUserData(2), % zoom UserData band = 6; % define zoom range (in degrees) YLims = [min(d(:,1))-band max(d(:,1))+band; min(d(:,2))-band max(d(:,2))+band; ... min(d(:,3))-band max(d(:,3))+band]; else % default values of zoom (full range of Euler angles) YLims = [-180 180;-90 90;-180 180]; end set(p_handle(1),'XData',t,'YData',[last_d(1,1) d(:,1)'],'Color','b','LineWidth',2) set(p_handle(2),'XData',t,'YData',[last_d(1,2) d(:,2)'],'Color','g','LineWidth',2) set(p_handle(3),'XData',t,'YData',[last_d(1,3) d(:,3)'],'Color','r','LineWidth',2) case 5 % Quaternions if CurrentFigureUserData(2), % zoom UserData band = 0.14; % define zoom range YLims = [min(d(1,1))-band max(d(1,1))+band; min(d(1,2))-band max(d(1,2))+band;... min(d(1,3))-band max(d(1,3))+band; min(d(1,4))-band max(d(1,4))+band]; % not so useful for quaternions... else % default values of zoom (full range of Euler angles) YLims = [-1 1; -1 1; -1 1; -1 1;]; end set(p_handle(1),'XData',t,'YData',[last_d(1,1) d(:,1)'],'Color','k','LineWidth',2) set(p_handle(2),'XData',t,'YData',[last_d(1,2) d(:,2)'],'Color','b','LineWidth',2) set(p_handle(3),'XData',t,'YData',[last_d(1,3) d(:,3)'],'Color','g','LineWidth',2) set(p_handle(4),'XData',t,'YData',[last_d(1,4) d(:,4)'],'Color','r','LineWidth',2) case 6 % Matrix YLims = [0 4]; % not used % only display latest data available in DCM orientation matrix mode set(p_handle(1),'cdata',[d(end,1:3); d(end,4:6); d(end,7:9)]'); end % switch % flush the graphics to screen drawnow % ------------------------------------------------------------------------- % end of function %% ------------------------------------------------------------------------- function mt_figure_close(obj, eventdata, h, f_handle) % local function to properly release MTObj when the user kills the figure window. % release MTObj XM_StopProcess(h) delete(h); clear h; % kill figure window as requested delete(f_handle) % ------------------------------------------------------------------------- % end of function
github
umariqb/3D_Pose_Estimation_CVPR2016-master
buildTensorStyleActRep.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/buildTensorStyleActRep.m
6,442
utf_8
ee9af2e2baeb0930757e0db140fa496b
function [Tensor,mots,skels]=buildTensorStyleActRep(p,varargin) % T=buildTensorStyleActRep(dir,[maxRep[,dataRep[,Styles]]]); % example: % T=buildTensorStyleActRep('R:\HDM05\HDM05_cut_amc',3); switch nargin case 1 maxRep =3; dataRep='Quat'; Styles ={'walk4StepsRstart', ... 'walkLeftCircle4StepsRstart', ... 'walkRightCircle4StepsRstart'}; case 2 maxRep =varargin{1}; dataRep='Quat'; Styles ={'walk4StepsRstart', ... 'walkLeftCircle4StepsRstart', ... 'walkRightCircle4StepsRstart'}; case 3 maxRep =varargin{1}; dataRep=varargin{2}; Styles ={'walk4StepsRstart', ... 'walkLeftCircle4StepsRstart', ... 'walkRightCircle4StepsRstart'}; case 4 maxRep =varargin{1}; dataRep=varargin{2}; Styles =varargin{3}; otherwise error('Wrong number of Args'); end Tensor.DataRep=dataRep; % define size of representation: switch dataRep case 'Quat' dimDataRep=4; case 'Position' dimDataRep=3; case 'ExpMap' dimDataRep=3; case 'Acc' dimDataRep=3; otherwise error('buildTensorStyleActRep_jt: Wrong Date specified in var: dataRep'); end % Check if Backslash is included in path and append extension: if(p(end)~=filesep) p=[p filesep]; end ext='*.amc'; % Check if there is a directory for every style: numStyles=size(Styles,2); for s=1:numStyles if(~exist([p Styles{1,s}],'dir')) error(['buildTensorStyleActRep_jt: Dir for Style ' Styles{1,s} ' does not exist!']); end end Tensor.styles=Styles; % Get Lists of files: for s=1:numStyles listofFiles{s}=dir([p Styles{1,s} filesep ext]); end %% Collect Information about the given files/styles/classes: % Known Actors: bd,bk,mm,dg,tr actors{1}='HDM_bd'; actors{2}='HDM_bk'; actors{3}='HDM_dg'; actors{4}='HDM_mm'; actors{5}='HDM_tr'; numActors=size(actors,2); for s=1:numStyles %Count repetitions of each actor for a=1:numActors reps(a,s)=countActor(listofFiles{s},actors{a}); end end % Motions to fit by DTW skelfile=fullfile(p, Styles{1,1}, [actors{1} '.asf']); motfile =fullfile(p, Styles{1,1}, listofFiles{1}(1).name); [fitskel,fitmot]=readMocap(skelfile,motfile); fprintf('Reference Motion: '); fprintf([listofFiles{1}(1).name '\n']) fitmot=changeFrameRate(fitskel,fitmot,30); Tensor.numTechnicalModes = 3; Tensor.dimTechnicalModes = [dimDataRep fitmot.nframes fitmot.njoints]; Tensor.dimNaturalModes = [numStyles numActors maxRep]; Tensor.dimNaturalModes = Tensor.dimNaturalModes(Tensor.dimNaturalModes~=1); Tensor.numNaturalModes = length(Tensor.dimNaturalModes); mots = cell(numStyles,numActors,maxRep); skels = cell(numStyles,numActors,maxRep); Tensor.data=zeros([Tensor.dimTechnicalModes Tensor.dimNaturalModes]); for s=1:numStyles file=1; for a=1:numActors for r=1:max(maxRep,reps(a,s)) if (r<=maxRep) fprintf('Fitting motion %i%i%i - ',s,a,r); skelfile = fullfile(p, Styles{1,s}, [actors{a} '.asf']); motfile = fullfile(p, Styles{1,s}, listofFiles{s}(file).name); Tensor.motions{s,a,r} = motfile; Tensor.skeletons{s,a,r} = skelfile; [skel,mot] = readMocap(skelfile,motfile); mot = changeFrameRate(skel,mot,30); mot = fitMotion(skel,mot); [D,w] = pointCloudDTW(fitmot,mot,'pos',1:31,1); mot = warpMotion(w,skel,mot); Tensor.rootdata(:,:,s,a,r) = mot.rootTranslation; for joint=1:mot.njoints % Tensor.joints{joint,s,a,r}=mot.jointNames{joint}; switch dataRep case 'Quat' if(~isempty(mot.rotationQuat{joint})) % align all quaternions mot.rotationQuat{joint}(:,dot(mot.rotationQuat{joint},fitmot.rotationQuat{joint})<0)... =-mot.rotationQuat{joint}(:,dot(mot.rotationQuat{joint},fitmot.rotationQuat{joint})<0); Tensor.data(:,:,joint,s,a,r)=mot.rotationQuat{joint}; else Tensor.data(1,:,joint,s,a,r) =1; Tensor.data(2:4,:,joint,s,a,r)=0; end case 'Position' if(~isempty(mot.jointTrajectories{joint})) Tensor.data(:,:,joint,s,a,r)=mot.jointTrajectories{joint}; else Tensor.data(:,:,joint,s,a,r)=0; end case 'ExpMap' if(~isempty(mot.rotationQuat{joint})) Tensor.data(:,:,joint,s,a,r)=quatlog(mot.rotationQuat{joint}); else Tensor.data(:,:,joint,s,a,r)=0; end case 'Acc' mot = addAccToMot(mot); if(~isempty(mot.jointAccelerations{joint})) Tensor.data(:,:,joint,s,a,r)=mot.jointAccelerations{joint}; else Tensor.data(:,:,joint,s,a,r)=0; end otherwise error('buildTensorStyleActRep_jt: Wrong Type specified in var: dataRep\n'); end end [mots{s,a,r},skels{s,a,r}]=deal(mot,skel); end if (r<reps(a,s)||r==max(maxRep,reps(a,s))) file=file+1; end end end end Tensor.data=squeeze(Tensor.data); Tensor.rootdata=squeeze(Tensor.rootdata); Tensor=HOSVDv2(Tensor); end function num=countActor(files,actor) LoFN=[files(:).name]; tmp=size(strfind(LoFN,actor)); num=tmp(2); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
compareAngles.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/compareAngles.m
1,720
utf_8
af58585e18a5b41ed729fc6a30ae9b47
function [res] = compareAngles(mot1,mot2,varargin) mot1=addBonesToMot(mot1); mot2=addBonesToMot(mot2); endEffectors = [6,11,17,23,24,30,31]; regardedJoints = setxor((1:31),endEffectors); weights = ones(1,length(regardedJoints)); switch nargin case 2 case 3 if ~isempty(intersect(varargin{1},endEffectors)) fprintf('End effectors selected - ignoring end effectors...\n'); end regardedJoints = intersect(varargin{1},regardedJoints); weights = ones(1,length(regardedJoints)); case 4 if length(varargin{1})~=length(varargin{2}) error('Number of selected joints does not equal number of weights!'); end if ~isempty(intersect(varargin{1},endEffectors)) fprintf('End effectors selected - ignoring end effectors...\n'); end [regardedJoints,pos1] = intersect(varargin{1},regardedJoints); weights = varargin{2}(pos1); otherwise error('Wrong number og argins!'); end fprintf('Joints: \t'); fprintf('%.3i ',regardedJoints); fprintf('\nWeights: \t'); fprintf('%.1f ',weights); fprintf('\n'); counter=0; for i=regardedJoints counter=counter+1; res(counter,:)=weights(counter)*computeAngleDiff(mot1,mot2,i); end function diff=computeAngleDiff(mot1,mot2,joint) switch joint case 3 %lknee z = arrayfun(@(x)intersect(x.f1, x.f2),mot1.bones{:,5}) end angle1=real(acosd(dot(-mot1.bones{2,4},mot1.bones{3,4}))); angle2=real(acosd(dot(-mot2.bones{2,4},mot2.bones{3,4}))); dot(cross(-mot1.bones{2,4},mot1.bones{3,4}),cross(-mot2.bones{2,4},mot2.bones{3,4})) diff=abs(angle1-angle2);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
diff5point2.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/diff5point2.m
2,637
utf_8
d17ccf79ec510a81dd4d2db6d2064f3a
% function newStream = diff5point(stream,samplingRate,varargin) % 5-point derivation % author: Jochen Tautges ([email protected]) function newStream = diff5point2(stream,samplingRate,varargin) % defaults options.padding = true; options.derivative = 1; options.side = 'center'; nrOfFrames = size(stream,2); if nargin>2 options = mergeOptions(varargin{1},options); end if options.padding newStream = zeros(size(stream)); else newStream = zeros(size(stream,1),nrOfFrames-4); end prepadding = []; postpadding = []; switch options.side case 'left' left = 4; right = 0; if options.padding prepadding = interp1(1:nrOfFrames,stream',-3:0,'linear','extrap')'; postpadding = []; end switch options.derivative case 1 weights = [3 -16 36 -48 25]; divisor = 12/samplingRate; case 2 weights = -[-11 56 -114 104 -35]; divisor = 12/samplingRate^2; otherwise error('Not yet implemented!'); end case 'right' left = 0; right = 4; if options.padding prepadding = []; postpadding = interp1(1:nrOfFrames,stream',nrOfFrames+1:nrOfFrames+4,'linear','extrap')'; end switch options.derivative case 1 weights = [-25 48 -36 16 -3]; divisor = 12/samplingRate; case 2 weights = [35 -104 114 -56 11]; divisor = 12/samplingRate^2; otherwise error('Not yet implemented!'); end case 'center' left = 2; right = 2; if options.padding prepadding = interp1(1:nrOfFrames,stream',-1:0,'linear','extrap')'; postpadding = interp1(1:nrOfFrames,stream',nrOfFrames+1:nrOfFrames+2,'linear','extrap')'; end switch options.derivative case 1 weights = [1 -8 0 8 -1]; divisor = 12/samplingRate; case 2 weights = [-1 16 -30 16 -1]; divisor = 12/samplingRate^2; otherwise error('Not yet implemented!'); end end if size(stream,1)==1 prepadding = prepadding'; postpadding = postpadding'; end stream = [prepadding stream postpadding]; for i = left+1:size(stream,2)-right newStream(:,i-left) = stream(:,i-left:i+right) * weights'; end newStream = newStream / divisor;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
buildTensor.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/buildTensor.m
20,295
utf_8
dcc2bdb7af8b33478e4603d910c363b5
% function buildTensor % builds a motion tensor with specified form and order of modes % % Use upper cases for Technical Modes, lower cases for Natural Modes! % Valid characters for Technical Modes: % I: (Q)uaternions / (E)uler angles / Exponential (M)aps / (P)ositions / % (V)elocities / (A)ccelerations; (necessary) % II: (F)rames (necessary) % III: (J)oints (necessary) % Valid characters for Natural Modes: % i: (a)ctors (necessary) % ii: (s)tyles (necessary) % iii: (r)epetitions (necessary) % iv: (m)irrored motions (optional) % % [Tensor,skels,mots] = buildTensor(form) % example: T = buildTensor('QFJsar'); % author: Jochen Tauges ([email protected]) function [T,skels,mots]=buildTensor(form) home='R:\HDM05\'; if (isempty(strfind(form,'J')))... || (isempty(strfind(form,'F')))... || (isempty(strfind(form,'a')))... || (isempty(strfind(form,'s')))... || (isempty(strfind(form,'r'))) error('Invalid input!'); end T.DataRep = []; T.numTechnicalModes = 0; T.numNaturalModes = 0; dimDataRep = 3; T.dimTechnicalModes = []; T.dimNaturalModes = []; nrOfActors = 0; nrOfStyles = 0; nrOfRepetitions = 0; mirroring = false; TechOrder = zeros(1,sum(int8(form)<91)); NatOrder = zeros(1,sum(int8(form)>97)); for i=1:length(form) if length(strfind(form,form(i)))>1 error('Invalid input!'); end switch form(i) case 'Q' if (T.numNaturalModes>0 || ~isempty(T.DataRep)) error('Invalid input!'); else T.form{i} = 'QUAT'; T.DataRep = 'quat'; dimDataRep = 4; T.numTechnicalModes = T.numTechnicalModes+1; TechOrder(i) = 1; end case 'E' if (T.numNaturalModes>0 || ~isempty(T.DataRep)) error('Invalid input!'); else T.form{i} = 'EULER'; T.DataRep = 'euler'; T.numTechnicalModes = T.numTechnicalModes+1; TechOrder(i) = 1; end case 'M' if (T.numNaturalModes>0 || ~isempty(T.DataRep)) error('Invalid input!'); else T.form{i} = 'EXPMAP'; T.DataRep = 'expmap'; T.numTechnicalModes = T.numTechnicalModes+1; TechOrder(i) = 1; end case 'P' if (T.numNaturalModes>0 || ~isempty(T.DataRep)) error('Invalid input!'); else T.form{i} = 'POS'; T.DataRep = 'pos'; T.numTechnicalModes = T.numTechnicalModes+1; TechOrder(i) = 1; end case 'V' if (T.numNaturalModes>0 || ~isempty(T.DataRep)) error('Invalid input!'); else T.form{i} = 'VEL'; T.DataRep = 'vel'; T.numTechnicalModes = T.numTechnicalModes+1; TechOrder(i) = 1; end case 'A' if (T.numNaturalModes>0 || ~isempty(T.DataRep)) error('Invalid input!'); else T.form{i} = 'ACC'; T.DataRep = 'acc'; T.numTechnicalModes = T.numTechnicalModes+1; TechOrder(i) = 1; end case 'F' if (T.numNaturalModes>0) error('Invalid input!'); else T.form{i} = 'FRAMES'; T.numTechnicalModes = T.numTechnicalModes+1; TechOrder(i) = 2; end case 'J' if (T.numNaturalModes>0) error('Invalid input!'); else T.form{i} = 'JOINTS'; T.numTechnicalModes = T.numTechnicalModes+1; TechOrder(i) = 3; end jointModeID = i; case 's' T.form{i} = 'styles'; NatOrder(i-T.numTechnicalModes) = 4; T.numNaturalModes = T.numNaturalModes+1; case 'a' T.form{i} = 'actors'; NatOrder(i-T.numTechnicalModes) = 5; T.numNaturalModes = T.numNaturalModes+1; case 'r' T.form{i} = 'repetitions'; NatOrder(i-T.numTechnicalModes) = 6; T.numNaturalModes = T.numNaturalModes+1; while nrOfRepetitions<=0 nrOfRepetitions = input('How many repetitions of each motion do you want to store? '); end fprintf('Size of repetition mode: %i\n',nrOfRepetitions); case 'm' T.form{i} = 'mirrors'; mirroring = true; NatOrder(i-T.numTechnicalModes) = 7; T.numNaturalModes = T.numNaturalModes+1; otherwise help buildTensor; error('Invalid character: ''%c''!',form(i)); end end extension='*.amc'; if exist(home,'dir'); AMCfolder=home; else AMCfolder=''; end % Hack for tensor construction EG08 ;-) AMCfolder='/data/HDM/HDM05_EG08/HDM05_EG08_cut_amc_training/'; %reading the .asf-files: FilterIndex=1; while (FilterIndex~=0 || nrOfActors==0) fprintf('\nSpecify asf-file(s)! '); [ASFfile,ASFPathName,FilterIndex] = uigetfile(fullfile(AMCfolder,'*.asf'),'MultiSelect','on'); if iscell(ASFfile) for j=1:length(ASFfile) fprintf('%s ',ASFfile{j}); nrOfActors = nrOfActors+1; actors{nrOfActors} = ASFfile{j}; actorsFullFile{nrOfActors} = fullfile(ASFPathName, ASFfile{j}); end else if FilterIndex~=0 fprintf('%s ',ASFfile); nrOfActors = nrOfActors+1; actors{nrOfActors} = ASFfile; actorsFullFile{nrOfActors} = fullfile(ASFPathName, ASFfile); elseif nrOfActors>0 fprintf('\nSize of actors mode: %i\n',nrOfActors); end end end %reading the .amc files %file names have to match the .asf file names! while (ischar(AMCfolder) || nrOfStyles==0) dialog_title=['Specify folder of amc-files for style ' num2str(nrOfStyles+1) '!']; fprintf('\n%s ',dialog_title); if AMCfolder==0 AMCfolder=''; end AMCfolder = uigetdir(AMCfolder,dialog_title); if (AMCfolder~=0) nrOfStyles = nrOfStyles+1; for a=1:nrOfActors actorString{a} = actors{a}(1:end-4); listOfAMCFiles_tmp = dir(fullfile(AMCfolder,['*',actorString{a},'*',extension])); listOfAMCFiles{nrOfStyles,a} = listOfAMCFiles_tmp; reps(a,nrOfStyles) = size(listOfAMCFiles{nrOfStyles,a},1); end AMCpaths{nrOfStyles} = AMCfolder; T.styles{nrOfStyles} = fliplr(strtok(fliplr(AMCfolder),filesep)); else fprintf('\nSize of style mode: %i\n',nrOfStyles); end end refMotFileName = fullfile(AMCpaths{1},listOfAMCFiles{1,1}(1).name); fprintf('\nSelect reference motion for DTW (Cancel for default)!\n '); [refFileName,refPathName,FilterIndex] = uigetfile(fullfile(AMCpaths{1},'*.amc')); if FilterIndex~=0 refMotFileName=fullfile(refPathName,refFileName); end refSkelFileName=[]; for a=1:nrOfActors if size(strfind(refMotFileName,actorString{a}))>0 refSkelFileName=actorsFullFile{a}; break; end end if isempty(refSkelFileName) [refFileName,refSkelPathName,FilterIndex] = uigetfile(fullfile(ASFPathName,'*.asf'), 'Choose ASF file for reference motion!'); if FilterIndex~=0 refSkelFileName=fullfile(refSkelPathName,refFileName); end end [fitskel,fitmot] = readMocap(refSkelFileName,refMotFileName); %%% Vorsicht: readMocap liest samplingRate nicht korrekt ein! default=120 % fitmot.samplingRate = 30; % fitmot.frametime = 1/30; T.samplingRate = input('\nSpecify frame rate for all motions: '); fitmot = changeFrameRate(fitskel,fitmot,T.samplingRate); fitmot = fitMotion(fitskel,fitmot); T.DTW.refMot = fliplr(strtok(fliplr(fitmot.filename),filesep)); for i=1:length(form) switch form(i) case {'Q','E','M','P','V','A'} T.dimTechnicalModes = [T.dimTechnicalModes dimDataRep]; case 'F' T.dimTechnicalModes = [T.dimTechnicalModes fitmot.nframes]; case 'J' T.dimTechnicalModes = [T.dimTechnicalModes fitmot.njoints]; case 'a' T.dimNaturalModes = [T.dimNaturalModes nrOfActors]; case 's' T.dimNaturalModes = [T.dimNaturalModes nrOfStyles]; case 'r' T.dimNaturalModes = [T.dimNaturalModes nrOfRepetitions]; case 'm' T.dimNaturalModes = [T.dimNaturalModes 2]; end end T.form = T.form([(T.dimTechnicalModes>1) (T.dimNaturalModes>1)]); T.dimTechnicalModes = T.dimTechnicalModes(T.dimTechnicalModes>1); T.dimNaturalModes = T.dimNaturalModes(T.dimNaturalModes>1); T.numNaturalModes = length(T.dimNaturalModes); T.numTechnicalModes = length(T.dimTechnicalModes); if mirroring mots = cell(nrOfStyles,nrOfActors,nrOfRepetitions,2); skels = cell(nrOfStyles,nrOfActors,nrOfRepetitions,2); T.motions = cell(nrOfStyles,nrOfActors,nrOfRepetitions,2); T.skeletons = cell(nrOfStyles,nrOfActors,nrOfRepetitions,2); else mots = cell(nrOfStyles,nrOfActors,nrOfRepetitions); skels = cell(nrOfStyles,nrOfActors,nrOfRepetitions); T.motions = cell(nrOfStyles,nrOfActors,nrOfRepetitions); T.skeletons = cell(nrOfStyles,nrOfActors,nrOfRepetitions); end motfile_tmp = ''; T.numMissingMots = 0; T.DTW.warpingCosts = 0; for s=1:nrOfStyles for a=1:nrOfActors file=1; for r=1:max(nrOfRepetitions,reps(a,s)) if (r<=nrOfRepetitions) skelfile = actorsFullFile{a}; motfile = fullfile(AMCpaths{s},listOfAMCFiles{s,a}(file).name); T.motions{s,a,r,1} = motfile; T.skeletons{s,a,r,1} = skelfile; if strcmp(motfile,refMotFileName) if strcmp(motfile,motfile_tmp) fprintf('\nMotion %i%i%i is not existent and set equal to previous motion.\n',s,a,r); else fprintf('\nMotion %i%i%i is the reference motion of the DTW and does not have to be aligned again.\n',s,a,r); skel = fitskel; mot = fitmot; if ~isfield(T.DTW,'refMotID') T.DTW.refMotID=[s,a,r,1]; end end T.DTW.warpingPaths{s,a,r,1} = repmat((mot.nframes:-1:1)',1,2); elseif strcmp(motfile,motfile_tmp) fprintf('\nMotion %i%i%i is not existent and set equal to previous motion.\n',s,a,r); T.DTW.warpingPaths{s,a,r,1} = w; T.DTW.warpingCosts = [T.DTW.warpingCosts D(fitmot.nframes,mot.nframes)/fitmot.nframes]; T.numMissingMots = T.numMissingMots+1; else fprintf('\nFitting motion %i%i%i - ',s,a,r); [skel,mot] = readMocap(skelfile,motfile); mot = changeFrameRate(skel,mot,T.samplingRate); mot = fitMotion(skel,mot); [D,w] = pointCloudDTW_pos(fitmot,mot,2); T.DTW.warpingPaths{s,a,r,1} = w; T.DTW.warpingCosts = [T.DTW.warpingCosts D(fitmot.nframes,mot.nframes)/fitmot.nframes]; mot = warpMotion(w,skel,mot); motfile_tmp = motfile; end T.rootdata(:,:,s,a,r,1) = mot.rootTranslation; for joint=1:mot.njoints switch lower(T.DataRep) case 'quat' if(~isempty(mot.rotationQuat{joint}) && ~isempty(fitmot.rotationQuat{joint})) % align all quaternions mot.rotationQuat{joint}(:,dot(mot.rotationQuat{joint},fitmot.rotationQuat{joint})<0)... = -mot.rotationQuat{joint}(:,dot(mot.rotationQuat{joint},fitmot.rotationQuat{joint})<0); T.data(:,:,joint,s,a,r,1) = mot.rotationQuat{joint}; else T.data(1,:,joint,s,a,r) = 1; T.data(2:4,:,joint,s,a,r) = 0; end case 'euler' [xxx,mot]=convert2euler(skel,mot); if(~isempty(mot.rotationEuler{joint})) T.data(:,:,joint,s,a,r,1) = mot.rotationEuler{joint}; else T.data(:,:,joint,s,a,r,1) = 0; end case 'expmap' if(~isempty(mot.rotationQuat{joint})) T.data(:,:,joint,s,a,r,1) = quatlog(mot.rotationQuat{joint}); else T.data(:,:,joint,s,a,r,1) = 0; end case 'pos' if(~isempty(mot.jointTrajectories{joint})) T.data(:,:,joint,s,a,r,1) = mot.jointTrajectories{joint}; else T.data(:,:,joint,s,a,r,1) = 0; end case 'vel' mot = addVelToMot(mot); if(~isempty(mot.jointVelocities{joint})) T.data(:,:,joint,s,a,r,1) = mot.jointVelocities{joint}; else T.data(:,:,joint,s,a,r,1) = 0; end case 'acc' mot = addAccToMot(mot); if(~isempty(mot.jointAccelerations{joint})) T.data(:,:,joint,s,a,r,1) = mot.jointAccelerations{joint}; else T.data(:,:,joint,s,a,r,1) = 0; end end % (switch lower(T.DataRep)) end % (for joint=1:motM.njoints) [skels{s,a,r,1},mots{s,a,r,1}] = deal(skel,mot); if mirroring [skelM,motM] = mirrorMot(skel,mot); motM = fitMotion(skelM,motM); [skels{s,a,r,2},mots{s,a,r,2}] = deal(skelM,motM); T.motions{s,a,r,2} = [motfile '.mirrored']; T.skeletons{s,a,r,2} = [skelfile '.mirrored']; T.DTW.warpingPaths{s,a,r,2} = T.DTW.warpingPaths{s,a,r,1}; T.rootdata(:,:,s,a,r,2) = motM.rootTranslation; for joint=1:motM.njoints switch lower(T.DataRep) case 'quat' if(~isempty(motM.rotationQuat{joint})) % aligning not necessary anymore T.data(:,:,joint,s,a,r,2) = motM.rotationQuat{joint}; else T.data(1,:,joint,s,a,r,2) = 1; T.data(2:4,:,joint,s,a,r,2) = 0; end case 'euler' [xxx,motM]=convert2euler(skelM,motM); if(~isempty(motM.rotationEuler{joint})) T.data(:,:,joint,s,a,r,2) = motM.rotationEuler{joint}; else T.data(:,:,joint,s,a,r,2) = 0; end case 'expmap' if(~isempty(motM.rotationQuat{joint})) T.data(:,:,joint,s,a,r,2) = quatlog(motM.rotationQuat{joint}); else T.data(:,:,joint,s,a,r,2) = 0; end case 'pos' if(~isempty(motM.jointTrajectories{joint})) T.data(:,:,joint,s,a,r,2) = motM.jointTrajectories{joint}; else T.data(:,:,joint,s,a,r,2) = 0; end case 'vel' motM = addVelToMot(motM); if(~isempty(motM.jointVelocities{joint})) T.data(:,:,joint,s,a,r,2) = motM.jointVelocities{joint}; else T.data(:,:,joint,s,a,r,2) = 0; end case 'acc' motM = addAccToMot(motM); if(~isempty(motM.jointAccelerations{joint})) T.data(:,:,joint,s,a,r,2) = motM.jointAccelerations{joint}; else T.data(:,:,joint,s,a,r,2) = 0; end end % (switch lower(T.DataRep)) end % (for joint=1:motM.njoints) end % (if mirroring) end % (if (r<=nrOfRepetitions)) if (r<reps(a,s)||r==max(nrOfRepetitions,reps(a,s))) file=file+1; end end end end dataOrder = [TechOrder NatOrder]; rootdataOrder = dataOrder(dataOrder~=jointModeID); rootdataOrder(rootdataOrder>jointModeID)=... rootdataOrder(rootdataOrder>jointModeID)-1; order = NatOrder-T.numTechnicalModes; T.data = squeeze(permute(T.data,dataOrder)); T.rootdata = squeeze(permute(T.rootdata,rootdataOrder)); T.motions = squeeze(permute(T.motions,order)); T.skeletons = squeeze(permute(T.skeletons,order)); T.DTW.warpingPaths = squeeze(permute(T.DTW.warpingPaths,order)); skels = squeeze(permute(skels,order)); mots = squeeze(permute(mots,order)); if isfield(T.DTW,'refMotID') T.DTW.refMotID = T.DTW.refMotID(order); T.DTW.refMotID = T.DTW.refMotID(T.dimNaturalModes>1); end T = HOSVDv2(T); end function num=countActor(files,actor) LoFN=[files(:).name]; tmp=size(strfind(LoFN,actor)); num=tmp(2); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
pointCloudDTW.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/pointCloudDTW.m
3,102
utf_8
83f6115f6c0f4180cbd4fdd61dcf3716
% function [D,w,d]=pointCloudDTW(motRef,motToWarp[,traj,joints,rho]) % % Output: % D = GDM (Global Distance Matrix) % w = warping path % d = LDM (Local Distance Matrix) % % Required Input: % motref: reference motion % motToWarp: motion which is to warp % % Optional input: % traj: 'jointTrajectories' (default), 'jointVelocities' or % 'jointAccelerations' % joints: joints for which the trajectories are to be compared % (for joint IDs see the skel structure, default: [1:31]) % rho: windowsize for point cloud distance (default: 1) function [D,w,d]=pointCloudDTW(motRef,motToWarp,varargin) % default values trajField='jointTrajectories'; joints=(1:31); rho=0; switch nargin case 3 trajField=varargin{1}; case 4 trajField=varargin{1}; joints=varargin{2}; case 5 trajField=varargin{1}; joints=varargin{2}; rho = varargin{3}; end TrajectoriesRef = cell(length(joints),1); TrajectoriesToWarp = cell(length(joints),1); % if ~(isfield(motRef,'jointAccelerations')) % motRef=addAccToMot(motRef); % end % if ~(isfield(motToWarp,'jointAccelerations')) % motToWarp=addAccToMot(motToWarp); % end for i=1:length(joints) switch trajField case {'jointAccelerations','a','acc','A','Acc','accelerations','Accelerations'} TrajectoriesRef{i} = motRef.jointAccelerations{joints(i)}; TrajectoriesToWarp{i} = motToWarp.jointAccelerations{joints(i)}; case {'jointVelocities','v','vel','V','Vel','velocities','Velocities'} TrajectoriesRef{i} = motRef.jointVelocities{joints(i)}; TrajectoriesToWarp{i} = motToWarp.jointVelocities{joints(i)}; case {'jointTrajectories','p','pos','P','Pos','positions','Positions'} TrajectoriesRef{i} = motRef.jointTrajectories{joints(i)}; TrajectoriesToWarp{i} = motToWarp.jointTrajectories{joints(i)}; otherwise fprintf('\nNo valid trajectory specification: %s\n\n', trajField); [D,w,d]=deal([],[],[]); help pointCloudDTW_jt return end end N = size(TrajectoriesRef{1},2); M = size(TrajectoriesToWarp{1},2); % Calculation of the LDM: d = distMatrix_pointCloudDistance_jt(TrajectoriesRef,TrajectoriesToWarp,rho); % Calculation of the GDM: D = inf(size(d)); D(1,:) = cumsum(d(1,:)); D(:,1) = cumsum(d(:,1)); for n=2:N for m=2:M D(n,m) = d(n,m)+min([D(n-1,m-1),D(n-1,m),D(n,m-1)]); end end % Search for the optimal path on the GDM: n=N; m=M; w=[]; w(1,:)=[N,M]; while (n~=1 && m~=1) [values,number]=min([D(n-1,m-1),D(n-1,m),D(n,m-1)]); switch number case 2 n=n-1; case 3 m=m-1; case 1 n=n-1; m=m-1; end w=[w;[n,m]]; end if (n==1 && m>1) w=[w;[ones(m-1,1),(m-1:-1:1)']]; elseif (m==1 && n>1) w=[w;[(n-1:-1:1)',ones(n-1,1)]]; end % plotDTWpath(d,w);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
resampleMot2.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/resampleMot2.m
3,220
utf_8
d8f75da0022de6825c0010d62c4eec37
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function resampleMot2 % for doc see "resampleMot" % resampleMot2 uses arbitrary interpolation method instead of linear interpolation % Note: resampleMot is faster, but resampleMot2 is nicer! % % author: Jochen Tautges ([email protected]) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [resmot,newSamp,oldSamp] = resampleMot2(skel,mot,varargin) rootTranslation = mot.rootTranslation; mot.rootTranslation(:,:) = 0; mot.jointTrajectories = C_forwardKinematicsQuat(skel,mot); switch nargin case 2 numberOfSamples = mot.nframes; joints = 1:mot.njoints; method = 'spline'; case 3 numberOfSamples = varargin{1}; joints = 1:mot.njoints; method = 'spline'; case 4 numberOfSamples = varargin{1}; joints = varargin{2}; method = 'spline'; case 5 numberOfSamples = varargin{1}; joints = varargin{2}; method = varargin{3}; otherwise help resampleMot; error('Wrong number of argins!'); end data = cell2mat(mot.jointTrajectories(joints)); dists = sqrt(sum(diff(data,1,2).^2)); delta = sum(dists)/(numberOfSamples-1); dists = [0 cumsum(dists)]; oldSamp = 1:mot.nframes; newSamp = zeros(1,numberOfSamples); newSamp(1) = 1; newSamp(end) = mot.nframes; c=1; i=2; d = delta; while i<=size(dists,2) if dists(i)>delta c=c+1; r=dists(i)-dists(i-1); p=delta-dists(i-1); newSamp(c) = i-1+p/r; delta = delta+d; else i=i+1; end end dofs = getDOFsFromSkel(skel); resmot = emptyMotion(mot); resmot.nframes = numberOfSamples; rotationQuat = cell2mat(mot.rotationQuat(mot.animated)); % rotationQuat = spline(oldSamp,rotationQuat,newSamp); rotationQuat = interp1(oldSamp,rotationQuat',newSamp,method)'; resmot.rotationQuat = mat2cell(rotationQuat,dofs.quat,numberOfSamples); resmot.rotationQuat = cellfun(@(x) normalizeColumns(x),resmot.rotationQuat,'UniformOutput',0); resmot.rootTranslation = spline(oldSamp,rootTranslation,newSamp); if isfield(mot,'jointAccelerations') jointAccelerations = cell2mat(mot.jointAccelerations); jointAccelerations = spline(oldSamp,jointAccelerations,newSamp); resmot.jointAccelerations = mat2cell(jointAccelerations,dofs.pos,numberOfSamples); end if isfield(mot,'jointVelocities') jointVelocities = cell2mat(mot.jointVelocities); jointVelocities = spline(oldSamp,jointVelocities,newSamp); resmot.jointVelocities = mat2cell(jointVelocities,dofs.pos,numberOfSamples); end resmot.jointTrajectories = C_forwardKinematicsQuat(skel,resmot); resmot.boundingBox = computeBoundingBox(resmot); resmot.rotationEuler = []; resmot.documentation = 'resampled';
github
umariqb/3D_Pose_Estimation_CVPR2016-master
addDOFIDsToSkel.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/addDOFIDsToSkel.m
646
utf_8
11e095a26ec25bb14198480b779910f8
% function addDOFIDsToSkel % adds struct "DOFIDs" to each node of denoted skel with indices % identifying its respective (rotational) dofs (->efficiency) % x -> 1, y -> 2, z -> 3 % example: % skel = addDOFIDsToSkel(skel) % author: Jochen Tautges, [email protected] function skel = addDOFIDsToSkel(skel) for i=1:skel.njoints skel.nodes(i).DOFIDs = []; for j=1:size(skel.nodes(i).DOF,1) dof = lower(skel.nodes(i).DOF{j}); if strcmp(dof(1),'r'); skel.nodes(i).DOFIDs = [skel.nodes(i).DOFIDs ... strfind(lower(skel.nodes(i).rotationOrder),dof(2))]; end end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
reconstructMotionFromWiiData.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/reconstructMotionFromWiiData.m
4,757
utf_8
bd78c7bd53046a5480a073842545f393
function res = reconstructMotionFromWiiData(Tensor,skel,wii_output,motOrig) joint = input('Choose jointID for wii output: '); % wii_output = wii_output(:,9:11)'; % wii_output(3,:) = -9.81 * wii_output(3,:); % wii_output = wii_output(:,1:3)'; % wii_output(3,:) = -wii_output(3,:); X0 = cell(1,Tensor.numNaturalModes); x0 = []; % X0{1}=[0 1 0]; % X0{2}=[1 0 0 0 0]; % X0{3}=[1 0 0]; for i=1:Tensor.numNaturalModes X0{i} = ones(1,Tensor.dimNaturalModes(i))/Tensor.dimNaturalModes(i); x0 = [x0 X0{i}]; end % x0 = [1 0 0 1 0 0 0 0 1 0 0]; % [xx,refMot] = constructMotion(Tensor,X0,skel); % refMot = addAccToMot(refMot); % refdata = refMot.jointAccelerations{joint}; % % refdata=mean{joint}; % refdata(2,:) = refdata(2,:) + 9.81; % % framerate % oldRate = 50; % newRate = 30; % wii_output = changeSamplingRate(wii_output,oldRate,newRate); % wii_output = filterTimeline(wii_output,2,'bin'); % wiiData = cutWiiData(wii_output,refdata); % wiiData = resample(wii_output',floor(86/length(wii_output)*1000),1000)'; wiiData = wii_output; % DTW options = optimset( 'Display','iter',... 'MaxFunEvals',100000,... 'MaxIter',100,... 'TolFun',0.001,... 'PlotFcns', @optimplotx); core = Tensor.core; rootcore = Tensor.rootcore; for i=1:Tensor.numTechnicalModes core = modeNproduct(core,Tensor.factors{i},i); end for i=1:Tensor.numTechnicalModes-1 rootcore = modeNproduct(rootcore,Tensor.rootfactors{i},i); end optimStruct.motOrig = motOrig; optimStruct.wiiData = wiiData; optimStruct.joint = joint; optimStruct.tensor = Tensor; optimStruct.preparedCore = core; optimStruct.preparedRootCore = rootcore; optimStruct.skel = skel; lb = -0.1 * ones(1,length(x0)); ub = 1.1 * ones(1,length(x0)); coeffs = lsqnonlin(@(x) objfunWii(x,optimStruct),x0,lb,ub,options); res.coeffs = mat2cell(coeffs,1,Tensor.dimNaturalModes)'; for i=1:Tensor.numNaturalModes core = modeNproduct(core,... res.coeffs{i}*Tensor.factors{i+Tensor.numTechnicalModes},... i+Tensor.numTechnicalModes); end for i=1:Tensor.numNaturalModes rootcore = modeNproduct(rootcore,... res.coeffs{i}/sum(res.coeffs{i})*... Tensor.rootfactors{i+Tensor.numTechnicalModes-1},i+Tensor.numTechnicalModes-1); end res.motRec = createMotionFromCoreTensor_jt(core,rootcore,skel,true,true,Tensor.DataRep); end %% function f = objfunWii(x,optimStruct) X = mat2cell(x,1,optimStruct.tensor.dimNaturalModes)'; for i=1:optimStruct.tensor.numNaturalModes optimStruct.preparedCore = modeNproduct(optimStruct.preparedCore,... X{i}*optimStruct.tensor.factors{i+optimStruct.tensor.numTechnicalModes},... i+optimStruct.tensor.numTechnicalModes); optimStruct.preparedRootCore = modeNproduct(optimStruct.preparedRootCore,... X{i}*optimStruct.tensor.rootfactors{i+optimStruct.tensor.numTechnicalModes-1},... i+optimStruct.tensor.numTechnicalModes-1); end motRec = createMotionFromCoreTensor_jt(optimStruct.preparedCore,... optimStruct.preparedRootCore,... optimStruct.skel,... true,... true,... optimStruct.tensor.DataRep); motRec = addAccToMot(motRec); recData = motRec.jointAccelerations{optimStruct.joint}; recData(2,:)=recData(2,:)+9.81; motRec = computeLocalSystems(optimStruct.skel,motRec); P = C_quatrot(recData,C_quatinv(motRec.localSystems{optimStruct.joint})); Q = optimStruct.wiiData; % [R,T] = icp(P,Q); T = findOptimalPCtransformation(P,Q); f = T.pc1_new - Q; end %% function wii_cut = cutWiiData(wiidata,refdata) wiiNorm = normOfColumns(wiidata); refNorm = normOfColumns(refdata); mindist = inf; for i=1:length(wiiNorm)-length(refNorm)+1 T = findOptimalPCtransformation(wiidata(:,i:i+length(refdata)-1),refdata); dist = sqrt(sum((T.pc1_new - refdata).^2)); % fprintf('%i\n',sum(dist)); if sum(dist)<mindist mindist=sum(dist); strt=i; end end wii_cut = wiidata(:,strt:strt+length(refNorm)-1); fprintf('\nstart frame: %i, end frame: %i\n',strt,strt+length(refNorm)-1); plot(wiiNorm(:,strt:strt+length(refNorm)-1)); hold all; plot(refNorm); drawnow(); end %% function newdata = changeSamplingRate(data,oldRate,newRate) oldSampling=1:length(data); newSampling=1:oldRate/newRate:length(data); newdata = spline(oldSampling,data,newSampling); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
translateMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/translateMotion.m
698
utf_8
33e6539750837edc3271f125a42f6ec7
% function translateMotion % translates a motion with specified translation % mot = translateMotion(skel,mot,x,y,z) % author: Jochen Tautges ([email protected]) function mot = translateMotion(skel,mot,x,y,z) mot.rootTranslation = mot.rootTranslation+repmat([x;y;z],1,mot.nframes); mot.jointTrajectories = forwardKinematicsQuat(skel,mot); mot.boundingBox = computeBoundingBox(mot); if (isfield(mot,'jointVelocities')&&~isempty(mot.jointVelocities)) mot=addVelToMot(mot); end if (isfield(mot,'jointAccelerations')&&~isempty(mot.jointAccelerations)) mot=addAccToMot(mot); end %fprintf('Motion successfully translated with x=%.2f, y=%.2f, z=%.2f.\n',x,y,z);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
mirrorMot.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/mirrorMot.m
1,554
utf_8
31552f5474f3dde982ed755a26923111
% function mirrorMot % mirrors specified skeleton and motion on the yz-plane % [newskel,newmot] = mirrorMot(skel,mot) % author: Jochen Tautges ([email protected]) function [newskel,newmot]=mirrorMot(skel,mot) newskel = mirrorSkel(skel); % if isempty(mot.rotationEuler) mot = C_convert2euler(skel,mot); % end newmot = mot; newmot.rootTranslation(1,:) = -newmot.rootTranslation(1,:); pairs{1} = [6,11]; pairs{2} = [5,10]; pairs{3} = [9,4]; pairs{4} = [3,8]; pairs{5} = [2,7]; pairs{6} = [18,25]; pairs{7} = [19,26]; pairs{8} = [20,27]; pairs{9} = [21,28]; pairs{10} = [22,29]; pairs{11} = [23,30]; pairs{12} = [24,31]; for i=1:length(pairs) newmot.rotationEuler{pairs{i}(1)} = mot.rotationEuler{pairs{i}(2)}; newmot.rotationEuler{pairs{i}(2)} = mot.rotationEuler{pairs{i}(1)}; end newmot.rotationEuler{1}(2,:) = -newmot.rotationEuler{1}(2,:); newmot.rotationEuler{1}(3,:) = -newmot.rotationEuler{1}(3,:); for i=2:mot.njoints idx = strmatch('ry', lower(skel.nodes(i).DOF), 'exact'); if ~isempty(idx) newmot.rotationEuler{i}(idx,:) = -newmot.rotationEuler{i}(idx,:); end idx = strmatch('rz', lower(skel.nodes(i).DOF), 'exact'); if ~isempty(idx) newmot.rotationEuler{i}(idx,:) = -newmot.rotationEuler{i}(idx,:); end end newmot = C_convert2quat(newskel,newmot); newmot.jointTrajectories = iterativeForwKinematics(newskel,newmot); newmot.boundingBox = computeBoundingBox(newmot);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
diff5point.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/diff5point.m
1,268
utf_8
d19f6076adaa6ec1abfbb4f8d9262385
% function newStream = diff5point(stream,samplingRate,varargin) % 5-point derivation % author: Jochen Tautges ([email protected]) function newStream = diff5point(stream,samplingRate,varargin) switch nargin case 2 weights = [1 -8 0 8 -1]; divisor = 12/samplingRate; case 3 if varargin{1}==1 weights = [1 -8 0 8 -1]; divisor = 12/samplingRate; elseif varargin{1}==2; weights = [-1 16 -30 16 -1]; divisor = 12/samplingRate^2; else error('Not implemented yet!'); end otherwise error('Wrong number of argins'); end newStream = zeros(size(stream)); % padding stream = [ 3*stream(:,1)-2*stream(:,2),... 2*stream(:,1)-stream(:,2),... stream,... 2*stream(:,end)-stream(:,end-1),... 3*stream(:,end)-2*stream(:,end-1)]; for i = 3:size(newStream,2)+2 newStream(:,i-2) = ... weights(1) * stream(:,i-2) ... + weights(2) * stream(:,i-1) ... + weights(3) * stream(:,i) ... + weights(4) * stream(:,i+1) ... + weights(5) * stream(:,i+2); end newStream = newStream / divisor;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
readNrOfFramesFromFile.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/readNrOfFramesFromFile.m
809
utf_8
516fa9a9fee29687bc51f14188778810
% function readNrOfFramesFroMFile % reads number of frames from specified amc-file % cf. function readNumFrames function nrOfFrames = readNrOfFramesFromFile(filename) fid = fopen(filename,'rt'); found = false; % found last frame number fseek(fid,-1,'eof'); % jump to end of file while (ftell(fid) > 0 && ~found) % not at bof AND not found last frame number pos = ftell(fid); ch = fread(fid,1,'uchar'); % read current character if (ch == 10) % line feed l = fgetl(fid); fseek(fid,pos-1,'bof'); if (l ~= -1) % no eof encountered nrOfFrames = str2double(l); if ~isnan(nrOfFrames) found = true; end end else fseek(fid,-2,'cof'); % jump 2 characters back end end fclose(fid);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
getStepSizes.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/getStepSizes.m
4,160
utf_8
fb6790e712da00511e990048a8359fbc
% function getStepSizes % (naively) computes stepSizes for walking motions % stepSizes = getStepSizes(skel,mot) % author: Jochen Tautges ([email protected]) function [stepSizesMin,stepSizesMax] = getStepSizes(mot) leftJoint = 4; rightJoint = 9; % for i=1:mot.nframes-1 % if ((mot.jointTrajectories{leftJoint}(2,i)<=mot.jointTrajectories{rightJoint}(2,i))... % && (mot.jointTrajectories{leftJoint}(2,i+1)>mot.jointTrajectories{rightJoint}(2,i+1)))... % || ((mot.jointTrajectories{leftJoint}(2,i)>=mot.jointTrajectories{rightJoint}(2,i))... % && (mot.jointTrajectories{leftJoint}(2,i+1)<mot.jointTrajectories{rightJoint}(2,i+1))) % % counter=counter+1; % stepSizes(counter)=normOfColumns(mot.jointTrajectories{5}(:,i)-mot.jointTrajectories{10}(:,i)); % % elseif ((i==mot.nframes-1)... % && (mot.jointTrajectories{leftJoint}(2,i+1)==mot.jointTrajectories{rightJoint}(2,i+1))) % % counter=counter+1; % stepSizes(counter)=normOfColumns(mot.jointTrajectories{5}(:,i+1)-mot.jointTrajectories{10}(:,i+1)); % end % end leftToRight=findstr([0 sign((mot.jointTrajectories{leftJoint}(2,:))-(mot.jointTrajectories{rightJoint}(2,:)))],[-1 1]); rightToLeft=findstr([0 sign((mot.jointTrajectories{rightJoint}(2,:))-(mot.jointTrajectories{leftJoint}(2,:)))],[-1 1]); frameIDs=union(1,[leftToRight,rightToLeft,mot.nframes]); if mot.jointTrajectories{leftJoint}(2,1)<=mot.jointTrajectories{rightJoint}(2,1) % left foot on floor in first frame joints=[leftJoint rightJoint]; else joints=[rightJoint leftJoint]; end maxPositions = zeros(1,length(frameIDs)-1); minPositions = zeros(1,length(frameIDs)-1); maxValues = zeros(3,length(frameIDs)-1); minValues = zeros(3,length(frameIDs)-1); for i=2:length(frameIDs) [minValue,minPos]=min(mot.jointTrajectories{joints(1)}(2,frameIDs(i-1):frameIDs(i))); [maxValue,maxPos]=max(mot.jointTrajectories{joints(2)}(2,frameIDs(i-1):frameIDs(i))); maxPositions(i-1)=maxPos+frameIDs(i-1)-1; minPositions(i-1)=minPos+frameIDs(i-1)-1; minValues(:,i-1)=mot.jointTrajectories{joints(1)}(:,minPositions(i-1)); maxValues(:,i-1)=mot.jointTrajectories{joints(1)}(:,maxPositions(i-1)); % joints(1) is correct! joints=fliplr(joints); end stepSizesMin = zeros(1,length(minValues)-1); stepSizesMax = zeros(1,length(maxValues)-1); for i=2:length(minValues) stepSizesMin(i-1)=normOfColumns(minValues(:,i)-minValues(:,i-1)); end for i=2:length(maxValues) stepSizesMax(i-1)=normOfColumns(maxValues(:,i)-maxValues(:,i-1)); end % lastOnFloor=''; % counter=0; % minID=0; % coordinates=[]; % % for i=1:mot.nframes % if mot.jointTrajectories{leftJoint}(2,i)<=mot.jointTrajectories{rightJoint}(2,i) % left foot on floor % if ~strcmp(lastOnFloor,'left') % counter=counter+1; % minSoFar=inf; % if minID~=0 % if ~isempty(coordinates) % stepSizes(counter)=normOfColumns(coordinates-mot.jointTrajectories{rightJoint}(:,minID)); % end % coordinates=mot.jointTrajectories{rightJoint}(:,minID); % end % end % if mot.jointTrajectories{leftJoint}(2,i)<minSoFar % minSoFar=mot.jointTrajectories{leftJoint}(2,i); % minID=i; % end % lastOnFloor='left'; % else % right foot on Floor % if ~strcmp(lastOnFloor,'right') % counter=counter+1; % minSoFar=inf; % if minID~=0 % if ~isempty(coordinates) % stepSizes(counter)=normOfColumns(coordinates-mot.jointTrajectories{leftJoint}(:,minID)); % end % coordinates=mot.jointTrajectories{leftJoint}(:,minID); % end % end % if mot.jointTrajectories{rightJoint}(2,i)<minSoFar % minSoFar=mot.jointTrajectories{rightJoint}(2,i); % minID=i; % end % lastOnFloor='right'; % end % end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
recMotWithPCAmat.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/recMotWithPCAmat.m
9,092
utf_8
8e2d52213cfa8169d8d9e2c0ae5f401f
% function recMotWithPCA(dataMat,skel,mot,dataRep) % % dataMat = dofs x frames % skel = skel struct of original motion % mot = mot struct of original motion % dataRep = 'quat' or 'euler' function res = recMotWithPCAmat(dataMat,skel,mot,dataRep) mot.rootTranslation = zeros(3,mot.nframes); mot = fitRootOrientationsFrameWise(skel,mot); mot.boundingBox = computeBoundingBox(mot); res.controlJoints = [4 9 20 27]; res.kdJoints = [3 4 8 9 19 20 26 27]; Xr = []; switch dataRep case 'euler' optimStruct.dofs = [3 0 3 1 2 1 0 3 1 2 1 3 3 3 3 3 3 2 3 1 1 2 1 2 2 3 1 1 2 1 2]; case 'quat' optimStruct.dofs = [4 0 4 4 4 4 0 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4]; end dofsCum = [0 cumsum(optimStruct.dofs)]; for i=res.kdJoints Xr = [Xr ; dataMat(dofsCum(i)+1:dofsCum(i+1),:)]; end % -------------------------------------------- % maximum number of nearest neightbours: size(dataMat,2); res.k = size(dataMat,2); % maximum number of nearest neighbours for PCA: res.k; % res.kForOptimization = 50; % maximum number of principal components: size(dataMat,1); res.nrOfPrinComps = 30; res.nrOfPrinCompsForCovMat = 20; % --------------------------------------------- lb = []; ub = []; options = optimset( 'Display','iter',... 'MaxFunEvals',100000,... 'MaxIter',100,... 'TolFun',0.01);%,... % 'PlotFcns', @optimplotx); startFrame = 1; % endFrame = mot.nframes; endFrame = 20; optimStruct.dataRep = dataRep; optimStruct.q = cell(mot.nframes,1); optimStruct.q{startFrame} = cutMotion(mot,startFrame,startFrame); optimStruct.q{startFrame+1} = cutMotion(mot,startFrame+1,startFrame+1); res.recMot = cutMotion(mot,startFrame,startFrame+1); switch dataRep case 'euler' angles_curr = cell2mat(optimStruct.q{startFrame+1}.rotationEuler); Xq = cell2mat(optimStruct.q{startFrame+1}.rotationEuler(res.kdJoints)); case 'quat' angles_curr = cell2mat(optimStruct.q{startFrame+1}.rotationQuat); Xq = cell2mat(optimStruct.q{startFrame+1}.rotationQuat(res.kdJoints)); end [nnidx,dists] = annquery(Xr, Xq, res.k); optimStruct.dataMatKD = dataMat(:,nnidx'); [optimStruct.coeffs,optimStruct.score] = princomp(optimStruct.dataMatKD'); optimStruct.meanVec = mean(optimStruct.dataMatKD,2); % optimStruct.dataMatKD == % optimStruct.coeffs * optimStruct.score' + repmat(optimStruct.meanVec,1,res.k) optimStruct.priorFactor = pinv(optimStruct.coeffs(:,1:res.nrOfPrinCompsForCovMat)')... * inv(cov(optimStruct.score(:,1:res.nrOfPrinCompsForCovMat)))... * pinv(optimStruct.coeffs(:,1:res.nrOfPrinCompsForCovMat)); % s = (dists(res.kForOptimization)*ones(res.kForOptimization,1)-dists(1:res.kForOptimization)); % w = s/sum(s); % angles_curr = optimStruct.dataMatKD(:,1:res.kForOptimization)*w; % startValue = (angles_curr-optimStruct.meanVec)' ... % * pinv(optimStruct.coeffs(:,1:res.nrOfPrinComps)') ... % * pinv(optimStruct.score(1:res.kForOptimization,1:res.nrOfPrinComps)); startValue = (angles_curr-optimStruct.meanVec)' ... * pinv(optimStruct.coeffs(:,1:res.nrOfPrinComps)'); res.origMot = cutMotion(mot,startFrame,endFrame); res.skel = skel; for i=startFrame+2:endFrame fprintf('\nReconstructing frame %i...\n',i); optimStruct.frame = i; optimStruct.q_orig = cutMotion(res.origMot,i,i); X = lsqnonlin(@(x) objfunPCAlocal(x,res,optimStruct),startValue,lb,ub,options); % angles_curr = (X * optimStruct.score(1:res.kForOptimization,1:res.nrOfPrinComps)... % * optimStruct.coeffs(1:res.nrOfPrinComps,:)')'... % + optimStruct.meanVec; angles_curr = optimStruct.coeffs(:,1:res.nrOfPrinComps) * X'... + optimStruct.meanVec; optimStruct.q{i} = buildMotFromAngles(angles_curr,skel,optimStruct.dofs,dataRep); res.recMot = addFrame2Motion(res.recMot,optimStruct.q{i}); save('res','res'); switch dataRep case 'euler' Xq = cell2mat(optimStruct.q{i}.rotationEuler(res.kdJoints)); case 'quat' Xq = cell2mat(optimStruct.q{i}.rotationQuat(res.kdJoints)); end [nnidx,dists] = annquery(Xr, Xq, res.k); optimStruct.dataMatKD = dataMat(:,nnidx'); [optimStruct.coeffs,optimStruct.score] = princomp(optimStruct.dataMatKD'); optimStruct.meanVec = mean(optimStruct.dataMatKD,2); optimStruct.priorFactor = pinv(optimStruct.coeffs(:,1:res.nrOfPrinCompsForCovMat)')... * inv(cov(optimStruct.score(:,1:res.nrOfPrinCompsForCovMat)))... * pinv(optimStruct.coeffs(:,1:res.nrOfPrinCompsForCovMat)); % s = (dists(res.kForOptimization)*ones(res.kForOptimization,1)-dists(1:res.kForOptimization)); % w = s/sum(s); % angles_curr = optimStruct.dataMatKD(:,1:res.kForOptimization)*w; % startValue = ((angles_curr-optimStruct.meanVec)'... % * pinv(optimStruct.coeffs(:,1:res.nrOfPrinComps)'))... % * pinv(optimStruct.score(1:res.kForOptimization,1:res.nrOfPrinComps)); startValue = (angles_curr-optimStruct.meanVec)' ... * pinv(optimStruct.coeffs(:,1:res.nrOfPrinComps)'); end res.recMot.samplingRate = res.origMot.samplingRate; end %% function objfunPCAlocal function f = objfunPCAlocal(x,res,optimStruct) % angles_curr = (x * optimStruct.score(1:res.kForOptimization,1:res.nrOfPrinComps)... % * optimStruct.coeffs(1:res.nrOfPrinComps,:)')'... % + optimStruct.meanVec; angles_curr = optimStruct.coeffs(:,1:res.nrOfPrinComps) * x'... + optimStruct.meanVec; q_curr = buildMotFromAngles(angles_curr,res.skel,optimStruct.dofs,optimStruct.dataRep); % ------- control term ---------- e_control = cell2mat(q_curr.jointTrajectories(res.controlJoints))... - cell2mat(optimStruct.q_orig.jointTrajectories(res.controlJoints)); % e_control = mean(e_control.^2); % ------- smoothness ------------ e_smooth = cell2mat(q_curr.jointTrajectories)... - 2 * cell2mat(optimStruct.q{optimStruct.frame-1}.jointTrajectories)... + cell2mat(optimStruct.q{optimStruct.frame-2}.jointTrajectories); % e_smooth = mean(e_smooth.^2); % ------- prior ----------------- e_prior = (angles_curr-optimStruct.meanVec)'... * optimStruct.priorFactor... * (angles_curr-optimStruct.meanVec); % e_prior = e_prior / length(angles_curr); % ------- overall error -------- % weights control_w = 1 / numel(e_control); smooth_w = 1 / numel(e_smooth); prior_w = 1 / numel(e_prior); % f = control_w * e_control ... % + smooth_w * e_smooth ... % + prior_w * e_prior; f = [control_w * e_control(:);... smooth_w * e_smooth(:);... prior_w * e_prior(:)]; % bar([control_w*sum(e_control.^2) smooth_w*sum(e_smooth.^2) prior_w*e_prior^2]); % drawnow(); end %% function buildMotFromAngles function q_curr = buildMotFromAngles(angles_curr,skel,dofs,dataRep) q_curr = emptyMotion; q_curr.njoints = 31; q_curr.nframes = 1; q_curr.rootTranslation = [0;0;0]; switch dataRep case 'euler' q_curr.rotationEuler = mat2cell(angles_curr,dofs); q_curr = convert2quat(skel,q_curr); case 'quat' q_curr.rotationQuat = mat2cell(angles_curr,dofs); % q_curr = convert2euler(skel,q_curr); end q_curr.jointTrajectories = forwardKinematicsQuat(skel,q_curr); q_curr.boundingBox = computeBoundingBox(q_curr); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
cutMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/cutMotion.m
3,166
utf_8
22b84462b6dea40f66c0315e91e41e86
% function cutMotion % cuts a motion sequence to specified start and end frame % mot = cutMotion(mot,startFrame,endFrame) % authors: Bjoern Krueger ([email protected]), % Jochen Tautges ([email protected]) function [mot] = cutMotion(mot,startF,endF) if startF~=1 || endF~=mot.nframes if (startF<1 || startF>endF || startF>mot.nframes || endF>mot.nframes) error('Forbidden values for start and end frame! sF=%i eF=%i mot.nframes=%i',startF, endF, mot.nframes); end mot.nframes = endF-startF+1; % computePos = false; if (isfield(mot,'jointTrajectories') && ~isempty(mot.jointTrajectories)) % computePos = true; if iscell(mot.jointTrajectories) if size(mot.jointTrajectories{1},2)>=endF mot.jointTrajectories = cellfun(@(x) x(:,startF:endF),mot.jointTrajectories,'UniformOutput',0); end mot.boundingBox = computeBoundingBox(mot); else mot.jointTrajectories = mot.jointTrajectories(:,startF:endF); end end % computeVel = false; if (isfield(mot,'jointVelocities') && ~isempty(mot.jointVelocities)) if iscell(mot.jointVelocities) mot.jointVelocities = cellfun(@(x) x(:,startF:endF),mot.jointVelocities,'UniformOutput',0); else mot.jointVelocities = mot.jointVelocities(:,startF:endF); end % computeVel = true; end % computeAcc = false; if (isfield(mot,'jointAccelerations')&& ~isempty(mot.jointAccelerations)) % computeAcc = true; if iscell(mot.jointAccelerations) mot.jointAccelerations = cellfun(@(x) x(:,startF:endF),mot.jointAccelerations,'UniformOutput',0); else mot.jointAccelerations = mot.jointAccelerations(:,startF:endF); end end % computeQuat = false; if (isfield(mot,'rotationQuat') && ~isempty(mot.rotationQuat)) if(iscell(mot.rotationQuat)) % computeQuat = true; mot.rotationQuat(mot.animated) = cellfun(@(x) x(:,startF:endF),mot.rotationQuat(mot.animated),'UniformOutput',0); mot.rotationQuat(mot.unanimated) = {[]}; else mot.rotationQuat = mot.rotationQuat(:,startF:endF); end end % computeEuler = false; if (isfield(mot,'rotationEuler') && ~isempty(mot.rotationEuler)) % computeEuler = true; mot.rotationEuler(mot.animated) = cellfun(@(x) x(:,startF:endF),mot.rotationEuler(mot.animated),'UniformOutput',0); mot.rotationEuler(mot.unanimated) = {[]}; end if ~isempty(mot.rootTranslation) mot.rootTranslation = mot.rootTranslation(:,startF:endF); end if isfield(mot,'footprints') mot.footprints = mot.footprints(:,startF:endF); end if isfield(mot,'timestamp') mot.timestamp = mot.timestamp(:,startF:endF); end % crazy people special field if (isfield(mot,'rootOri') && ~isempty(mot.rootOri)) mot.rootOri = mot.rootOri(:,startF:endF); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
mirrorSkel.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/mirrorSkel.m
1,411
utf_8
083463bbc71dba379e79c0608dae419f
% function mirrorSkel % mirrors specified skeleton on the yz-plane % newskel = mirrorSkel(skel) % author: Jochen Tautges ([email protected]) function newskel=mirrorSkel(skel) newskel = skel; newskel.filename = [skel.filename '.mirrored']; pairs{1} = [6,11]; pairs{2} = [5,10]; pairs{3} = [9,4]; pairs{4} = [3,8]; pairs{5} = [2,7]; pairs{6} = [18,25]; pairs{7} = [19,26]; pairs{8} = [20,27]; pairs{9} = [21,28]; pairs{10} = [22,29]; pairs{11} = [23,30]; pairs{12} = [24,31]; for i=1:length(pairs) newskel.nodes(pairs{i}(1)).length = skel.nodes(pairs{i}(2)).length; newskel.nodes(pairs{i}(2)).length = skel.nodes(pairs{i}(1)).length; newskel.nodes(pairs{i}(1)).offset = skel.nodes(pairs{i}(2)).offset; newskel.nodes(pairs{i}(2)).offset = skel.nodes(pairs{i}(1)).offset; newskel.nodes(pairs{i}(1)).direction = skel.nodes(pairs{i}(2)).direction; newskel.nodes(pairs{i}(2)).direction = skel.nodes(pairs{i}(1)).direction; newskel.nodes(pairs{i}(1)).axis = -skel.nodes(pairs{i}(2)).axis; newskel.nodes(pairs{i}(2)).axis = -skel.nodes(pairs{i}(1)).axis; end for i=1:skel.njoints newskel.nodes(i).offset(1) = -newskel.nodes(i).offset(1); newskel.nodes(i).direction(1) = -newskel.nodes(i).direction(1); newskel.nodes(i).axis(1) = -newskel.nodes(i).axis(1); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
recMotFromAcc.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/recMotFromAcc.m
4,581
utf_8
9f50d3e6824a1923102a16358de9bac5
% function recMotFromAcc % % db.acc % db.quat % % open questions concerning db: % - coordinate frame transformation % - resampling % - sensor/joint offsets % - flips that screw up accelerations % % more unsolved problems % - initialization (t-pose) % - choice of skeleton (optimization?) function res = recMotFromAcc(db,skel,mot) %% optional settings -------------------------------------------------------- nrOfNN = 1; eps = 0.1; % radius = 5; res.joints = [5,10,21,28]; acc_direction = 'xyz'; newFrameRate = db.frameRate; startFrame = 1; endFrame = mot.nframes; res.windowSize = 16; %% preprocessing ---------------------------------------------------------- fprintf('Preprocessing:\n'); res.joints = sort(res.joints); idx = jointIDsToMatrixIndices(res.joints); nrOfJoints = numel(res.joints); acc_idx = []; if sum(acc_direction=='x')~=0, acc_idx=[acc_idx 1:3:nrOfJoints*3]; end if sum(acc_direction=='y')~=0, acc_idx=[acc_idx 2:3:nrOfJoints*3]; end if sum(acc_direction=='z')~=0, acc_idx=[acc_idx 3:3:nrOfJoints*3]; end acc_idx = sort(acc_idx); % % modification of original motion % fprintf('Modification of original motion started...'); tic; % mot = cutMotion(mot,startFrame,endFrame); % mot = changeFrameRate(skel,mot,newFrameRate); % res.origmot = mot; % mot.rootTranslation(:,:) = 0; % mot = fitRootOrientationsFrameWise(skel,mot); % if ~isfield(mot,'jointAcceleration'); % mot = addAccToMot(mot); % end % mot.boundingBox = computeBoundingBox(mot); % res.origmot_mod = mot; % fprintf(' finished in %.2f seconds.\n',toc); mot = cutMotion(mot,startFrame,endFrame); mot = changeFrameRate(skel,mot,newFrameRate); res.origmot_mod = mot; % tree construction treeData = zeros(nrOfJoints*res.windowSize*length(acc_direction),size(db.pos,2)-res.windowSize+1); fprintf('kd-tree construction started (#frames = %i, #dims = %i = %i joints x %i accs x %i frames)...\n',... size(treeData'), nrOfJoints,length(acc_direction),res.windowSize); tic; % treeHandle = ann_buildTree(double(db.acc(idx.pos,:))); for i=1:size(db.acc,2)-res.windowSize+1 tmp = db.acc(idx.pos(acc_idx),i:i+res.windowSize-1)'; treeData(:,i) = tmp(:); end treeHandle = ann_buildTree(treeData); fprintf('finished in %.2f seconds.\n',toc); % treeQuery = cell2mat(mot.jointAccelerations(res.joints)); ma = cell2mat(mot.jointAccelerations(res.joints)); ma = ma(acc_idx,:); treeQuery = zeros(nrOfJoints*res.windowSize*length(acc_direction),floor(mot.nframes/res.windowSize)); for i=1:res.windowSize:mot.nframes-res.windowSize+1 tmp = ma(:,i:i+res.windowSize-1)'; treeQuery(:,(i-1)/res.windowSize+1) = tmp(:); end fprintf('nn-search started (#frames = %i, #neighbours = %i)...',mot.nframes,nrOfNN);tic; % [nnidx,nndists] = ann_queryTree(treeHandle,treeQuery,nrOfNN,'eps',eps,'search_sch','fr','radius',radius); [res.nnidx,res.nndists] = ann_queryTree(treeHandle,treeQuery,nrOfNN,'eps',eps); fprintf(' finished in %.2f seconds.\n',toc); %% reconstruction --------------------------------------------------------- fprintf('Reconstruction:\n'); hit = 1; fprintf('Concatenating hits of rank %i and length %i...', hit, res.windowSize); res.recmot = buildMotFromRotData(db.quat(:,res.nnidx(hit,1):res.nnidx(hit,1)+res.windowSize-1),skel); res.recmot.samplingRate = 30; res.recmot.frameTime = 1/30; res.recmot.jointAccelerations = mat2cell(db.acc(:,res.nnidx(hit,1):res.nnidx(hit,1)+res.windowSize-1),3*ones(1,31),res.windowSize); % res.recmot = addAccToMot(res.recmot); for i=2:size(res.nnidx,2) tmp_mot = buildMotFromRotData(db.quat(:,res.nnidx(hit,i):res.nnidx(hit,i)+res.windowSize-1),skel); tmp_mot.samplingRate = 30; tmp_mot.frameTime = 1/30; tmp_mot.jointAccelerations = mat2cell(db.acc(:,res.nnidx(hit,i):res.nnidx(hit,i)+res.windowSize-1),3*ones(1,31),res.windowSize); % tmp_mot = addAccToMot(tmp_mot); res.recmot = addFrame2Motion(res.recmot,tmp_mot); end fprintf(' finished in %.2f seconds.\n',toc); %% postprocessing --------------------------------------------------------- fprintf('Postprocessing:\n'); tic; ann_cleanup; fprintf('\b in %.2f seconds.\n',toc);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
reconstructCMUmotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/reconstructCMUmotion.m
1,714
utf_8
5496ac3f901d2b3599492c4a250f9c60
% res=reconstructCMUmotion(TensorForOptimization,CMUresult[,joints[,TensorForReconstruction]]]) function res = reconstructCMUmotion(TensorForReconstruction,skel,origmot,varargin) switch nargin case 3 joints = (1:31); case 4 joints = varargin{1}; case 5 joints = varargin{1}; TensorForReconstruction=varargin{2}; otherwise ('Wrong number of argins!'); end % folder='\\breithorn\shareII\MoCap-Daten\CMU_DB\CMU_D180\AMC\locomotion\walking\'; % % asfName = strcat(folder,CMUresult.asf); % res.skel = readASF(asfName); % amcName = strcat(folder,CMUresult.amc(max(strfind(CMUresult.amc,'/'))+1:end)); % origmot = readAMC(amcName,res.skel); % res.skel = CMUresult.orgSkel; % origmot = CMUresult.orgMot; res.skel = skel; res.origmot = changeFrameRate(skel,origmot,30); [mot,angle,x0,z0] = fitMotion(res.skel,res.origmot); [s,motRef] = extractMotion(TensorForReconstruction,[1,1,1]); [D,warpingPath] = pointCloudDTW_jt(motRef,mot); mot = warpMotion(warpingPath,res.skel,mot); set = defaultSet; set.regardedJoints = joints; [res.X,recmot] = reconstructMotion(TensorForReconstruction,res.skel,mot,'set',set); if nargin==5 [s,recmot] = constructMotion(TensorForReconstruction,res.X,res.skel); end recmot = warpMotion(fliplr(warpingPath),res.skel,recmot); recmot = rotateMotion(res.skel,recmot,-angle,'y'); res.recmot = translateMotion(res.skel,recmot,-x0,0,-z0); % recmot = removeSkating(skel,recmot);
github
umariqb/3D_Pose_Estimation_CVPR2016-master
zupt.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/zupt.m
3,001
utf_8
23a157324073343dc07482c998979a90
% zero velocity updates % input: % a - global accelerations (nSamples x 3), gravity removed % t0 - start frame of motion (here velocity is said to be zero) % T - end frame of motion (here velocity is said to be zero) % frameRate - frame rate % output: % res.v - velocity before correction % res.vc - velocity after correction % res.x - position before correction % res.xc - position after correction % % author: Jochen Tautges ([email protected]) function res = zupt(a,t0,T,frameRate) % a(:,1)=a(:,1)-mean(a([1:t0 T:end],1)); % a(:,2)=a(:,2)-mean(a([1:t0 T:end],2)); % a(:,3)=a(:,3)-mean(a([1:t0 T:end],3)); offsetX_left = mean(a(1:t0,1)); offsetY_left = mean(a(1:t0,2)); offsetZ_left = mean(a(1:t0,3)); offsetX_right = mean(a(T:end,1)); offsetY_right = mean(a(T:end,2)); offsetZ_right = mean(a(T:end,3)); offsetX = offsetX_left:(-offsetX_left+offsetX_right)/(T-t0):offsetX_right; offsetY = offsetY_left:(-offsetY_left+offsetY_right)/(T-t0):offsetY_right; offsetZ = offsetZ_left:(-offsetZ_left+offsetZ_right)/(T-t0):offsetZ_right; res.a = a(t0:T,:); res.a(:,1)=res.a(:,1)-offsetX'; res.a(:,2)=res.a(:,2)-offsetY'; res.a(:,3)=res.a(:,3)-offsetZ'; T = T-t0+1; t0 = 1; nSamples = size(res.a,1); res.v = cumtrapz(res.a); res.vc = zeros(size(res.a)); for t = 1:nSamples res.vc(t,:) = res.v(t,:) + (res.v(t0,:)-res.v(T,:))*(t/T) - res.v(t0,:); end res.x = cumtrapz(res.v); res.xc = zeros(size(res.a)); for t = 1:nSamples res.xc(t,:) = res.x(t,:) + (res.v(t0,:)-res.v(T,:))*(t^2)/(2*T) - res.v(t0,:)*t - res.x(t0,:); end res.v = res.v / frameRate; res.vc = res.vc / frameRate; res.x = res.x / frameRate^2; res.xc = res.xc / frameRate^2; % nSamples = size(a,1); % % res.a = a; % % res.v = cumtrapz(a); % res.vc = zeros(size(a)); % % for t = 1:nSamples % res.vc(t,:) = res.v(t,:) + (res.v(t0,:)-res.v(T,:))*((t-t0+1)/(T-t0+1)) - res.v(t0,:); % end % % res.x = cumtrapz(res.v); % res.xc = zeros(size(a)); % % for t = 1:nSamples % res.xc(t,:) = res.x(t,:) + (res.v(t0,:)-res.v(T,:))*((t-t0+1)^2)/(2*(T-t0+1)) - res.v(t0,:)*(t-t0+1) - res.x(t0,:); % end % % res.v = res.v / frameRate; % res.vc = res.vc / frameRate; % res.x = res.x / frameRate^2; % res.xc = res.xc / frameRate^2; figure; subplot(2,4,1); plot(res.a); title('Global Accelerations'); subplot(2,4,2); plot(res.v); title('Velocities without correction'); subplot(2,4,3); plot(res.x); title('Positions without correction'); subplot(2,4,4); plot3(res.x(:,1),res.x(:,2),res.x(:,3)); axis equal; title('3D-positions without correction'); subplot(2,4,5); plot(res.a); title('Global accelerations'); subplot(2,4,6); plot(res.vc); title('Velocities with correction'); subplot(2,4,7); plot(res.xc); title('Positions with correction'); subplot(2,4,8); plot3(res.xc(:,1),res.xc(:,2),res.xc(:,3)); axis equal; title('3d-positions with correction');
github
umariqb/3D_Pose_Estimation_CVPR2016-master
editMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/editMotion.m
2,216
utf_8
724f383800cf40f393dfd8ffa43699d6
% constraints.jointID % constraints.jointList % constraints.pos % constraints.frame % constraints.windowsize function mot = editMotion(skel,mot,constraints) A = []; b = []; Aeq = []; beq = []; lb = []; ub = []; for i=constraints.jointList' lb = [lb; skel.nodes(i).limits(:,1)]; ub = [ub; skel.nodes(i).limits(:,2)]; end options=optimset('Display','iter',... 'MaxIter', 10,... 'TolFun',0.1,... 'TolCon',0.1,... 'Algorithm','active-set'); dofs = getDOFsFromSkel(skel); regardedDOFs = dofs.euler(constraints.jointList); x0 = zeros(sum(regardedDOFs),1); frame = cutMotion(mot,constraints.frame,constraints.frame); X = fmincon(@objfun_local,x0,A,b,Aeq,beq,lb,ub,@(x) nonlcon_local(x,constraints,regardedDOFs,skel,frame),options); y = [zeros(size(X,1),1) zeros(size(X,1),1) X zeros(size(X,1),1) zeros(size(X,1),1)]; x = [1 2 constraints.windowsize+1 2*constraints.windowsize 2*constraints.windowsize+1]; xx = 1:2*constraints.windowsize+1; yy = spline(x,y,xx); eulers = cell2mat(cellfun(@(x) x(:,constraints.frame-constraints.windowsize:constraints.frame+constraints.windowsize),... mot.rotationEuler(constraints.jointList),'UniformOutput',0)); eulers = eulers + yy; eulers = mat2cell(eulers,regardedDOFs,size(eulers,2)); c=0; for i=constraints.jointList' c=c+1; mot.rotationEuler{i}(:,constraints.frame-constraints.windowsize:constraints.frame+constraints.windowsize)=eulers{c}; end mot = convert2quat(skel,mot); mot.jointTrajectories = forwardKinematicsQuat(skel,mot); end %% local functions function F = objfun_local(x) S = eye(size(x,1)); F = 1/2 * x' * S * x; end function [c,ceq] = nonlcon_local(x,constraints,regardedDOFs,skel,frame) newEulers = cell2mat(frame.rotationEuler(constraints.jointList)) + x; frame.rotationEuler(constraints.jointList) = mat2cell(newEulers,regardedDOFs,1); frame = convert2quat(skel,frame); frame.jointTrajectories = forwardKinematicsQuat(skel,frame); ceq = frame.jointTrajectories{constraints.jointID}-constraints.pos; c=[]; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
uipickfiles.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/uipickfiles.m
23,893
utf_8
fa44e011ea5d774cceebf0f15764edd5
function out = uipickfiles(varargin) %uipickfiles: GUI program to select file(s) and/or directories. % % Syntax: % files = uipickfiles('PropertyName',PropertyValue,...) % % The current directory can be changed by operating in the file navigator: % double-clicking on a directory in the list to move further down the tree, % using the popup menu to move up the tree, typing a path in the box to % move to any directory or right-clicking on the path box to revisit a % previously-listed directory. % % 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. Files in the list can be removed or re-ordered. % When finished, a press of the Done button will return the full paths to % the selected files in a cell array, structure array or character array. % If the Cancel button is pressed then zero is returned. % % The following optional property/value pairs can be specified as arguments % to control the indicated behavior: % % Property Value % ---------- ---------------------------------------------------------- % FilterSpec String to specify starting directory and/or file filter. % Ex: 'C:\bin' will start up in that directory. '*.txt' % will list only files ending in '.txt'. 'c:\bin\*.txt' will % do both. Default is to start up in the current directory % 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. % % 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. % % 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.0, 25 April 2006 % Author: Douglas M. Schwarz % Email: dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu % Real_email = regexprep(Email,{'=','*'},{'@','.'}) % Define properties and set default values. prop.filterspec = '*'; prop.refilter = ''; prop.prompt = 'Select files'; prop.numfiles = []; prop.output = 'cell'; % Process inputs and set prop fields. properties = fieldnames(prop); arg_index = 1; while arg_index <= nargin arg = varargin{arg_index}; if ischar(arg) prop_index = find(strncmpi(arg,properties,length(arg))); if length(prop_index) == 1 prop.(properties{prop_index}) = varargin{arg_index + 1}; else error('Property ''%s'' does not exist or is ambiguous.',arg) end arg_index = arg_index + 2; elseif isstruct(arg) arg_fn = fieldnames(arg); for i = 1:length(arg_fn) prop_index = find(strncmpi(arg_fn{i},properties,... length(arg_fn{i}))); if length(prop_index) == 1 prop.(properties{prop_index}) = arg.(arg_fn{i}); else error('Property ''%s'' does not exist or is ambiguous.',... arg_fn{i}) end end arg_index = arg_index + 1; else error(['Properties must be specified by property/value pairs',... ' or structures.']) end end % 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 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 file.'; elseif length(prop.numfiles) == 1 numstr = sprintf('Select exactly %d files.',prop.numfiles); else numstr = sprintf('Select %d to %d files.',prop.numfiles); 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 % Initialize file lists. [current_dir,f,e] = fileparts(prop.filterspec); filter = [f,e]; if isempty(current_dir) current_dir = pwd; end if isempty(filter) filter = '*'; end re_filter = prop.refilter; full_filter = fullfile(current_dir,filter); path_cell = path2cell(current_dir); fdir = filtered_dir(full_filter,re_filter); filenames = {fdir.name}'; filenames = annotate_file_names(filenames,fdir); % Initialize some data. file_picks = {}; full_file_picks = {}; dir_picks = dir(' '); % Create empty directory structure. show_full_path = false; nodupes = true; history = {current_dir}; % Create figure. gray = get(0,'DefaultUIControlBackgroundColor'); fig = figure('Position',[0 0 740 445],... 'Color',gray,... 'WindowStyle','modal',... 'Resize','off',... 'NumberTitle','off',... 'Name',prop.prompt,... 'IntegerHandle','off',... 'CloseRequestFcn',@cancel,... 'CreateFcn',{@movegui,'center'}); % Create uicontrols. uicontrol('Style','frame',... 'Position',[255 260 110 70]) uicontrol('Style','frame',... 'Position',[275 135 110 100]) navlist = uicontrol('Style','listbox',... 'Position',[10 10 250 320],... 'String',filenames,... 'Value',[],... 'BackgroundColor','w',... 'Callback',@clicknav,... 'Max',2); pickslist = uicontrol('Style','listbox',... 'Position',[380 10 350 320],... 'String',{},... 'BackgroundColor','w',... 'Callback',@clickpicks,... 'Max',2); openbut = uicontrol('Style','pushbutton',... 'Position',[270 300 80 20],... 'String','Open',... 'Enable','off',... 'Callback',@open); arrow = [2 2 2 2 2 2 2 2 1 2 2 2;... 2 2 2 2 2 2 2 2 2 0 2 2;... 2 2 2 2 2 2 2 2 2 2 0 2;... 0 0 0 0 0 0 0 0 0 0 0 0;... 2 2 2 2 2 2 2 2 2 2 0 2;... 2 2 2 2 2 2 2 2 2 0 2 2;... 2 2 2 2 2 2 2 2 1 2 2 2]; arrow(arrow == 2) = NaN; arrow_im = NaN*ones(16,76); arrow_im(6:12,45:56) = arrow/2; im = repmat(arrow_im,[1 1 3]); addbut = uicontrol('Style','pushbutton',... 'Position',[270 270 80 20],... 'String','Add ',... 'Enable','off',... 'CData',im,... 'Callback',@add); removebut = uicontrol('Style','pushbutton',... 'Position',[290 205 80 20],... 'String','Remove',... 'Enable','off',... 'Callback',@remove); moveupbut = uicontrol('Style','pushbutton',... 'Position',[290 175 80 20],... 'String','Move Up',... 'Enable','off',... 'Callback',@moveup); movedownbut = uicontrol('Style','pushbutton',... 'Position',[290 145 80 20],... 'String','Move Down',... 'Enable','off',... 'Callback',@movedown); uicontrol('Position',[10 380 250 16],... 'Style','text',... 'String','Current Directory',... 'HorizontalAlignment','center') dir_popup = uicontrol('Style','popupmenu',... 'Position',[10 335 250 20],... 'BackgroundColor','w',... 'String',path_cell(end:-1:1),... 'Value',1,... 'Callback',@dirpopup); hist_cm = uicontextmenu; pathbox = uicontrol('Position',[10 360 250 20],... 'Style','edit',... 'BackgroundColor','w',... 'String',current_dir,... 'HorizontalAlignment','left',... 'Callback',@change_path,... 'UIContextMenu',hist_cm); hist_menus = []; hist_cb = @history_cb; hist_menus = make_history_cm(hist_cb,hist_cm,hist_menus,history); uicontrol('Position',[10 425 80 16],... 'Style','text',... 'String','File Filter',... 'HorizontalAlignment','left') uicontrol('Position',[100 425 160 16],... 'Style','text',... 'String','Reg. Exp. Filter',... 'HorizontalAlignment','left') showallfiles = uicontrol('Position',[270 405 100 20],... 'Style','checkbox',... 'String','Show All Files',... 'Value',0,... 'HorizontalAlignment','left',... 'Callback',@togglefilter); filter_ed = uicontrol('Position',[10 405 80 20],... 'Style','edit',... 'BackgroundColor','w',... 'String',filter,... 'HorizontalAlignment','left',... 'Callback',@setfilspec); refilter_ed = uicontrol('Position',[100 405 160 20],... 'Style','edit',... 'BackgroundColor','w',... 'String',re_filter,... 'HorizontalAlignment','left',... 'Callback',@setrefilter); viewfullpath = uicontrol('Style','checkbox',... 'Position',[380 335 230 20],... 'String','Show full paths',... 'Value',show_full_path,... 'HorizontalAlignment','left',... 'Callback',@showfullpath); remove_dupes = uicontrol('Style','checkbox',... 'Position',[380 360 230 20],... 'String','Remove duplicates (as per full path)',... 'Value',nodupes,... 'HorizontalAlignment','left',... 'Callback',@removedupes); uicontrol('Position',[380 405 350 20],... 'Style','text',... 'String','Selected Files',... 'HorizontalAlignment','center') uicontrol('Position',[280 80 80 30],'String','Done',... 'Callback',@done); uicontrol('Position',[280 30 80 30],'String','Cancel',... 'Callback',@cancel); if ~isempty(prop.numfiles) uicontrol('Position',[380 385 350 16],... 'Style','text',... 'String',numstr,... 'ForegroundColor','r',... 'HorizontalAlignment','center') end set(fig,'HandleVisibility','off') 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 % -------------------- Callback 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; full_file_picks{end + 1} = pick_full; dir_picks(end + 1) = dir_pick; 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 if strcmp(fdir(values).name,'.') return elseif strcmp(fdir(values).name,'..') set(dir_popup,'Value',min(2,length(path_cell))) dirpopup(); return end current_dir = fullfile(current_dir,fdir(values).name); history{end+1} = current_dir; history = unique(history); hist_menus = make_history_cm(hist_cb,hist_cm,hist_menus,... history); full_filter = fullfile(current_dir,filter); path_cell = path2cell(current_dir); fdir = filtered_dir(full_filter,re_filter); filenames = {fdir.name}'; filenames = annotate_file_names(filenames,fdir); set(dir_popup,'String',path_cell(end:-1:1),'Value',1) set(pathbox,'String',current_dir) set(navlist,'ListboxTop',1,'Value',[],'String',filenames) set(addbut,'Enable','off') set(openbut,'Enable','off') 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 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 dirpopup(varargin) value = get(dir_popup,'Value'); len = length(path_cell); path_cell = path_cell(1:end-value+1); if ispc && value == len current_dir = ''; full_filter = filter; fdir = struct('name',getdrives,'date',datestr(now),... 'bytes',0,'isdir',1); else current_dir = cell2path(path_cell); history{end+1} = current_dir; history = unique(history); hist_menus = make_history_cm(hist_cb,hist_cm,hist_menus,... history); full_filter = fullfile(current_dir,filter); fdir = filtered_dir(full_filter,re_filter); end filenames = {fdir.name}'; filenames = annotate_file_names(filenames,fdir); set(dir_popup,'String',path_cell(end:-1:1),'Value',1) set(pathbox,'String',current_dir) set(navlist,'String',filenames,'Value',[]) set(addbut,'Enable','off') end function change_path(varargin) proposed_path = get(pathbox,'String'); % Process any directories 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 directory. if ~exist(proposed_path,'dir') uiwait(errordlg(['Directory "',proposed_path,... '" does not exist.'],'','modal')) return end current_dir = proposed_path; history{end+1} = current_dir; history = unique(history); hist_menus = make_history_cm(hist_cb,hist_cm,hist_menus,history); full_filter = fullfile(current_dir,filter); path_cell = path2cell(current_dir); fdir = filtered_dir(full_filter,re_filter); filenames = {fdir.name}'; filenames = annotate_file_names(filenames,fdir); set(dir_popup,'String',path_cell(end:-1:1),'Value',1) set(pathbox,'String',current_dir) set(navlist,'String',filenames,'Value',[]) set(addbut,'Enable','off') set(openbut,'Enable','off') 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)); order = sort(num_picks + 1 - rev_order); full_file_picks = full_file_picks(order); file_picks = file_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); 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); 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) 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); filenames = {fdir.name}'; filenames = annotate_file_names(filenames,fdir); set(navlist,'String',filenames,'Value',[]) set(addbut,'Enable','off') end function setfilspec(varargin) 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); filenames = {fdir.name}'; filenames = annotate_file_names(filenames,fdir); set(navlist,'String',filenames,'Value',[]) set(addbut,'Enable','off') end function setrefilter(varargin) re_filter = get(refilter_ed,'String'); fdir = filtered_dir(full_filter,re_filter); filenames = {fdir.name}'; filenames = annotate_file_names(filenames,fdir); set(navlist,'String',filenames,'Value',[]) set(addbut,'Enable','off') 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 files selected.',numstr}; uiwait(errordlg(msg,'','modal')) return elseif numfiles > prop.numfiles(end) msg = {'Too many files selected.',numstr}; uiwait(errordlg(msg,'','modal')) return end end delete(fig) end function cancel(varargin) prop.output = 'cancel'; delete(fig) end function history_cb(varargin) current_dir = history{varargin{3}}; full_filter = fullfile(current_dir,filter); path_cell = path2cell(current_dir); fdir = filtered_dir(full_filter,re_filter); filenames = {fdir.name}'; filenames = annotate_file_names(filenames,fdir); set(dir_popup,'String',path_cell(end:-1:1),'Value',1) set(pathbox,'String',current_dir) set(navlist,'ListboxTop',1,'Value',[],'String',filenames) set(addbut,'Enable','off') set(openbut,'Enable','off') end end % -------------------- Subfunctions -------------------- function c = path2cell(p) % Turns a path string into a cell array of path elements. c = strread(p,'%s','delimiter','\\/'); if ispc c = [{'My Computer'};c]; else c = [{filesep};c(2:end)]; 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) % Like dir, but applies filters and sorting. p = fileparts(full_filter); if isempty(p) && full_filter(1) == '/' p = '/'; end if exist(full_filter,'dir') c = cell(0,1); dfiles = struct('name',c,'date',c,'bytes',c,'isdir',c); else dfiles = dir(full_filter); end if ~isempty(dfiles) dfiles([dfiles.isdir]) = []; end ddir = dir(p); ddir = ddir([ddir.isdir]); % Additional regular expression filter. if nargin > 1 && ~isempty(re_filter) if ispc no_match = cellfun('isempty',regexpi({dfiles.name},re_filter)); else no_match = cellfun('isempty',regexp({dfiles.name},re_filter)); end dfiles(no_match) = []; end % Set navigator style: % 1 => mix file and directory names % 2 => means list all files before all directories % 3 => means list all directories before all files % 4 => same as 2 except put . and .. directories first if isunix style = 4; else style = 4; end switch style case 1 d = [dfiles;ddir]; [unused,index] = sort({d.name}); d = d(index); case 2 [unused,index1] = sort({dfiles.name}); [unused,index2] = sort({ddir.name}); d = [dfiles(index1);ddir(index2)]; case 3 [unused,index1] = sort({dfiles.name}); [unused,index2] = sort({ddir.name}); d = [ddir(index2);dfiles(index1)]; case 4 [unused,index1] = sort({dfiles.name}); dot1 = find(strcmp({ddir.name},'.')); dot2 = find(strcmp({ddir.name},'..')); ddot1 = ddir(dot1); ddot2 = ddir(dot2); ddir([dot1,dot2]) = []; [unused,index2] = sort({ddir.name}); d = [ddot1;ddot2;dfiles(index1);ddir(index2)]; end end function drives = getdrives % 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)) = []; end function filenames = annotate_file_names(filenames,dir_listing) % Adds a trailing filesep character to directory names. fs = filesep; for i = 1:length(filenames) if dir_listing(i).isdir filenames{i} = [filenames{i},fs]; end end end function hist_menus = make_history_cm(cb,hist_cm,hist_menus,history) % Make context menu for history. if ~isempty(hist_menus) delete(hist_menus) end num_hist = length(history); hist_menus = zeros(1,num_hist); for i = 1:num_hist hist_menus(i) = uimenu(hist_cm,'Label',history{i},... 'Callback',{cb,i}); end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
reconstructXsensMotion.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/reconstructXsensMotion.m
2,018
utf_8
2f580dc44896b8d1f48068954ce01bda
function recmot=reconstructXsensMotion(Tensor,skel,mot,varargin) switch nargin case 3 consideredJoints=mot.animated'; case 4 consideredJoints=varargin{1}; otherwise error('Wrong number of input arguments!'); end X0 = cell(1,Tensor.numNaturalModes); for i=1:Tensor.numNaturalModes X0{i} = ones(1,Tensor.dimNaturalModes(i))/Tensor.dimNaturalModes(i); end fprintf('Computing average accelerations out of Tensor...\n'); [s,m] = constructMotion(Tensor,X0,skel); m=addAccToMot(m); fprintf('...done.\n'); mot = changeFrameRate(skel,mot,m.samplingRate); fprintf('\nFinding subsequence of captured motion...\n'); XsensData = mot.jointAccelerations{consideredJoints}; refData = m.jointAccelerations{consideredJoints}; [xx,start] = cutXsensData(XsensData,refData); mot=cutMotion(mot,start,start+m.nframes-1); % fprintf('...done. Start frame: %i, end frame: %i\n',startOS,endOS); % Warpen der aufgenommenen Bewegung % fprintf('\nWarping the captured motion...\n'); % [D,w] = pointCloudDTW(m,mot,'a',mot.animated',0); % mot = warpMotion(w,s,mot); % fprintf('...done.\n'); fprintf('\nComputing coefficients for reconstructing the captured motion...\n'); set=defaultSet; set.regardedJoints=consideredJoints; res = reconstructMotion(Tensor,skel,mot,'set',set); fprintf('...done.\n'); recmot = res.motRec; % recmot = warpMotion(fliplr(w),skel,recmot); end function [Xsens_cut,start] = cutXsensData(XsensData,refdata) XsensNorm = normOfColumns(XsensData); refNorm = normOfColumns(refdata); mindist = inf; for i=1:length(XsensNorm)-length(refNorm)+1 dist = sum(abs(XsensNorm(i:i+length(refNorm)-1)-refNorm)); if dist<mindist mindist=dist; start=i; end end Xsens_cut = XsensData(:,start:start+length(refNorm)-1); plot(XsensNorm(:,start:start+length(refNorm)-1)); hold all; plot(refNorm); drawnow(); end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
linearCombinationOfSkeletons.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/linearCombinationOfSkeletons.m
945
utf_8
e48142f9ab8c6c415213225131adfcd5
% example: skel=linearCombinationOfSkeletons({skel1,skel2},[0.5 0.5]); function skel=linearCombinationOfSkeletons(skels,weights) numSkeletons=length(skels); if numSkeletons~=length(weights) error('Error: Number of skeletons must equal number of weights!'); end % Initialization skel=skels{1}; skel.filename='synthesizedSkeleton'; skel.version=[]; skel.name=[]; for i=1:skel.njoints skel.nodes(i).length = skel.nodes(i).length*weights(1); skel.nodes(i).direction = skel.nodes(i).direction*weights(1); for j=2:numSkeletons skel.nodes(i).length = skel.nodes(i).length+weights(j)*skels{j}.nodes(i).length; skel.nodes(i).direction = skel.nodes(i).direction+weights(j)*skels{j}.nodes(i).direction; end skel.nodes(i).direction = skel.nodes(i).direction/normOfColumns(skel.nodes(i).direction); skel.nodes(i).offset = skel.nodes(i).direction*skel.nodes(i).length; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
findOptimalPCtransformation.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/findOptimalPCtransformation.m
1,655
utf_8
578de504452a5ed36113682f0e377274
function T = findOptimalPCtransformation(pc1,pc2) % pc1(1,:)=pc1(1,:)*9.81; % pc1(2,:)=-pc1(2,:); % pc1(3,:)=pc1(3,:)/9.81; T.pc1 = pc1; T.pc2 = pc2; T.pc1_abs = normOfColumns(T.pc1); T.pc2_abs = normOfColumns(T.pc2); figure() plot(T.pc1_abs); hold all plot(T.pc2_abs); hold off drawnow; figure() plot(T.pc1'); hold all plot(T.pc2'); hold off drawnow; % startValue = [0 0 0 1]; % lb = [-2*pi -2*pi -2*pi 0]; % ub = [ 2*pi 2*pi 2*pi 2]; startValue = [0 0 0]; lb = [-2*pi -2*pi -2*pi]; ub = [ 2*pi 2*pi 2*pi]; options = optimset( 'Display','iter' ,... 'MaxFunEvals',100000,... 'MaxIter',100,... 'TolFun',0.001);%,... % 'PlotFcns', @optimplotx); X = lsqnonlin(@(x) objfunLocal(x,pc1,pc2),startValue,lb,ub,options); T.rotation = X(1:3); % T.scale = X(4:6); T.qR = C_euler2quat(X(1:3)'); % T.pc1_new = C_quatrot(pc1,T.qR) .* repmat(T.scale',1,size(T.pc1,2)); T.pc1_new = C_quatrot(pc1,T.qR); figure subplot(3,1,1);plot(T.pc1') subplot(3,1,2);plot(T.pc2') subplot(3,1,3);plot(T.pc1_new') drawnow(); figure() plot(T.pc1_new'); hold all plot(T.pc2'); hold off drawnow; end %% local functions function f = objfunLocal(x,pc1,pc2) % qx = rotquat(x(1),'x'); % qy = rotquat(x(2),'y'); % qz = rotquat(x(3),'z'); % q = C_quatmult(qz,C_quatmult(qy,qx)); % pc1(1,:)=pc1(1,:)*x(4); % pc1(2,:)=pc1(1,:)*x(5); % pc1(3,:)=pc1(1,:)*x(6); q = C_euler2quat(x(1:3)'); % f = C_quatrot(pc1,q) * x(4) - pc2; f = C_quatrot(pc1,q) - pc2; end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
resampleMot.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/resampleMot.m
3,898
utf_8
c02cbf66d8145c49bea30ef2d6ce0c30
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function resampleMot % resamples a motion to create homogeneous point cloud trajectories % % resmot = resampleMot(skel,mot[,joints[,numberOfSamples]]) % % input: % - skel: skeleton (required for forward kinematics) % - mot: motion to be resampled % - joints: joint IDs of regarded joints % - numberOfSamples: new number of samples (== resmot.nframes) % % output: % - resmot: resampled motion % % original motion: % oo-o--o----o------o-----------o----------------o------------------------o % resampled motion: % x--------x--------x--------x--------x--------x--------x--------x--------x % o = old samples, x = new samples % % author: Jochen Tautges ([email protected]) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function resmot = resampleMot(skel,mot,varargin) rootTranslation = mot.rootTranslation; mot.rootTranslation(:,:) = 0; mot.jointTrajectories = C_forwardKinematicsQuat(skel,mot); switch nargin case 2 numberOfSamples = mot.nframes; joints = 1:mot.njoints; case 3 numberOfSamples = varargin{1}; joints = 1:mot.njoints; case 4 numberOfSamples = varargin{1}; joints = varargin{2}; otherwise help resampleMot; error('Wrong number of argins!'); end newRootTranslation = zeros(3,numberOfSamples); newRootTranslation(:,1) = rootTranslation(:,1); computeAcc = false; if isfield(mot,'jointAccelerations') computeAcc = true; accs = cell2mat(mot.jointAccelerations); accs_new = zeros(size(accs,1),numberOfSamples); accs_new(:,1) = accs(:,1); end computeVel = false; if isfield(mot,'jointVelocities') computeVel = true; vels = cell2mat(mot.jointVelocities); vels_new = zeros(size(vels,1),numberOfSamples); vels_new(:,1) = vels(:,1); end pos = cell2mat(mot.jointTrajectories(joints)); quats = cell2mat(mot.rotationQuat(mot.animated)); dists = sqrt(sum(diff(pos,1,2).^2)); delta = sum(dists)/(numberOfSamples-1); % delta = mean(dists); quats_new = zeros(size(quats,1),numberOfSamples); quats_new(:,1) = quats(:,1); akk = 0; tmp = 0; i=1; counter=1; while i<mot.nframes step = dists(i)-tmp; if akk + step < delta tmp = 0; akk = akk + step; i = i+1; else counter = counter+1; tmp = tmp + delta - akk; alpha = tmp / dists(i); quats_new(:,counter) = alpha * quats(:,i+1) + (1-alpha) * quats(:,i); if computeAcc accs_new(:,counter) = alpha * accs(:,i+1) + (1-alpha) * accs(:,i); end if computeVel vels_new(:,counter) = alpha * vels(:,i+1) + (1-alpha) * vels(:,i); end newRootTranslation(:,counter) = alpha * rootTranslation(:,i+1) + (1-alpha) * rootTranslation(:,i); akk = 0; end end dofs = getDOFsFromSkel(skel); resmot = emptyMotion(mot); resmot.nframes = numberOfSamples; resmot.rootTranslation = newRootTranslation(:,1:numberOfSamples); resmot.rotationQuat = mat2cell(quats_new(:,1:numberOfSamples),dofs.quat,numberOfSamples); resmot.jointTrajectories = C_forwardKinematicsQuat(skel,resmot); if computeAcc resmot.jointAccelerations = mat2cell(accs_new(:,1:numberOfSamples),dofs.pos,resmot.nframes); end if computeVel resmot.jointVelocities = mat2cell(vels_new(:,1:numberOfSamples),dofs.pos,resmot.nframes); end resmot.boundingBox = computeBoundingBox(resmot); % if ~isempty(mot.rotationEuler) % resmot = C_convert2euler(skel,resmot); % end mot.documentation = 'resampled';
github
umariqb/3D_Pose_Estimation_CVPR2016-master
recMotFromSimWiiData.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/Optimization/recMotFromSimWiiData.m
3,273
utf_8
19bb2e00e269f2cb7d9d4d6ed272b114
function res = recMotFromSimWiiData(ttQuats,ttRootPos,skel,mot,joints) mot = fitMotion(skel,mot); refMot = extractMotFromTTensor(skel,ttQuats,ttRootPos,[1,1,1]); [D,w] = pointCloudDTW_pos(refMot,mot,2); mot = warpMotion(w,skel,mot); res.skel = skel; res.origmot = mot; res.joints = joints; optimStruct.TensorInfo.jointModeID = 3; optimStruct.TensorInfo.frameModeID = 2; optimStruct.TensorInfo.dofModeID = 1; optimStruct.TensorInfo.modesForOpt = [4,5,6]; optimStruct.ttQuatsFact = tucker_als(ttQuats,ttQuats.size); optimStruct.ttRootPosFact = tucker_als(ttRootPos,ttRootPos.size); % simulate local accelerations res.noise = 1; optimStruct.simWiiData = cell(mot.njoints,1); for j=joints optimStruct.simWiiData{j} = simulateLocalAccs(skel,mot,j,res.noise); end % ttQuats_prepared = ttm(ttQuats_factorized.core,... % ttQuats_factorized.U(1:Tensor.numTechnicalModes),... % 1:Tensor.numTechnicalModes); % ttRootPos_prepared = ttm(ttRootPos_factorized.core,... % ttRootPos_factorized.U(1:Tensor.numTechnicalModes-1),... % 1:Tensor.numTechnicalModes-1); optimStruct.skel = skel; optimStruct.origmot = res.origmot; optimStruct.joints = joints; optimStruct.ttQuats = ttQuats; optimStruct.ttRootPos = ttRootPos; % optimStruct.ttQuats_prepared = ttQuats_prepared; % optimStruct.ttRootPos_prepared = ttRootPos_prepared; % optimization options ---------------------------------------------------- options = optimset( 'Display','iter',... 'MaxFunEvals',100000,... 'MaxIter',100,... 'TolFun',0.001,... 'PlotFcns', @optimplotx); optimStruct.dimQuats = ttQuats.size; startValue = buildStartValue(optimStruct.dimQuats(optimStruct.TensorInfo.modesForOpt)); lb = -0.2 * ones(1,length(startValue)); ub = 1.2 * ones(1,length(startValue)); % ------------------------------------------------------------------------- coeffs = lsqnonlin(@(x) objfunWii(x,optimStruct),startValue,lb,ub,options); res.coeffs = mat2cell(coeffs,1,optimStruct.dimQuats(optimStruct.TensorInfo.modesForOpt))'; res.recmot = ttensor2mot(optimStruct.ttQuatsFact,optimStruct.ttRootPosFact,optimStruct.skel,res.coeffs,optimStruct.TensorInfo,optimStruct.origmot); res.recmot.boundingBox = computeBoundingBox(res.recmot); end %% function f = objfunWii(x,optimStruct) X = mat2cell(x,1,optimStruct.dimQuats(optimStruct.TensorInfo.modesForOpt))'; motRec = ttensor2mot(optimStruct.ttQuatsFact,optimStruct.ttRootPosFact,optimStruct.skel,X,optimStruct.TensorInfo,optimStruct.origmot); motRec = addAccToMot(motRec); motRec = computeLocalSystems(optimStruct.skel,motRec); f= []; for i=optimStruct.joints recData = motRec.jointAccelerations{i}; recData(2,:)= recData(2,:)+9.81; P = C_quatrot(recData,C_quatinv(motRec.localSystems{i})); Q = optimStruct.simWiiData{i}; T = findOptimalPCtransformation(P,Q); f = [f;T.pc1_new - Q]; end end
github
umariqb/3D_Pose_Estimation_CVPR2016-master
dtwModStep.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/synthesis/dtwModStep.m
2,200
utf_8
e95ff16ef5caf73be712e049bcd19e07
function [Dist,D,k,w,d]=dtwModStep(t1,r1) %Dynamic Time Warping Algorithm %Dist is unnormalized distance between t1 and r1 %D is the accumulated distance matrix (GDM) %k is the normalizing factor %w is the optimal path %d is the local distance matrix (LDM) %t1 is the vector you are testing against %r1 is the vector you are testing %Transpose the given Matrices t1=t1'; r1=r1'; [rows,N]=size(t1); [rows,M]=size(r1); d=zeros(N,M); %Calculation of the LDM: for m=1:M for n=1:N %This calculates the distance per frame only for a 1-dim signal: %d(n,m)=eukl_dist1d(t1(n),r1(m)); %You should replace this by your own distance measure for n-dim signals: d(n,m)=highDimDistance(t1(:,n),r1(:,m),rows); % d(n,m)=winDist(t1(:,n-9:n+9),r1(:,m-9:m+9)); end end %Calculation of the GDM: D=NaN(size(d)); D(1,1)=d(1,1); for n=2:N D(n,1:2)=d(n,1:2)+D(n-1,1:2); end for m=2:M D(1:2,m)=d(1:2,m)+D(1:2,m-1); end for n=3:N for m=3:M D(n,m)=d(n,m)+min([D(n-2,m-1),D(n-1,m-1),D(n-1,m-2)]); end end %Search of the optimal path on the given matrix: Dist=D(N,M); n=N; m=M; k=1; w=[]; w(1,:)=[N,M]; while ((n+m)~=2) if (n-1)==0 m=m-1; elseif (m-1)==0 n=n-1; else [values,number]=min([D(n-1,m-1),D(n-1,m-2),D(n-1,m-2)]); switch number case 2 n=n-1;m=m-2; case 3 m=m-2;n=n-1; case 1 n=n-1; m=m-1; end end k=k+1; w=cat(1,w,[n,m]); end %End of DTW Algorithm % Euclidian distance measure function [distance]=eukl_dist1d(a1,b1) distance=abs((a1-b1)); % Add your function for the distance measurement here: function [distance]=highDimDistance(a1,b1,row) sum=0; %Berechnung des n-Dim. euklidischen Abstandes for i=1:row sum=sum+(a1(i)-b1(i))^2; end distance=sqrt(sum); function [dist]=dotDist(a,b) dist=1-dot(a/sqrt(sum(a.*a)),b/sqrt(sum(b.*b))); function [dist]=winDist(a,b) a=sum(a,2); b=sum(b,2); dist=1-dot(a/sqrt(sum(a.*a)),b/sqrt(sum(b.*b)));
github
umariqb/3D_Pose_Estimation_CVPR2016-master
dtw.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/synthesis/dtw.m
2,597
utf_8
a29941e18ad22ac3aedb4694fc9168bf
function [Dist,D,k,w,d]=dtw(varargin) %Dynamic Time Warping Algorithm %Dist is unnormalized distance between t1 and r1 %D is the accumulated distance matrix (GDM) %k is the normalizing factor %w is the optimal path %d is the local distance matrix (LDM) %t1 is the vector you are testing against %r1 is the vector you are testing switch nargin case 1 d = varargin{1}; N = size(d,1); M = size(d,2); case 2 %Transpose the given Matrices t1 = varargin{1}'; r1 = varargin{2}'; [rows,N] = size(t1); [rows,M] = size(r1); d = zeros(N,M); %Calculation of the LDM: for m=1:M for n=1:N %This calculates the distance per frame only for a 1-dim signal: %d(n,m)=eukl_dist1d(t1(n),r1(m)); %You should replace this by your own distance measure for n-dim signals: d(n,m)=highDimDistance(t1(:,n),r1(:,m)); % d(n,m)=winDist(t1(:,n-9:n+9),r1(:,m-9:m+9)); end end otherwise error('Wrong num of args!\n'); end %Calculation of the GDM: D=inf(size(d)); D(1,1)=d(1,1); for n=2:N D(n,1)=d(n,1)+D(n-1,1); % D(n,2)=d(n,2)+D(n-1,2); end for m=2:M D(1,m)=d(1,m)+D(1,m-1); % D(2,m)=d(2,m)+D(2,m-1); end for n=2:N for m=2:M D(n,m)=d(n,m)+min([D(n-1,m-1),D(n-1,m),D(n,m-1)]); % D(n,m)=d(n,m)+min([D(n-1,m-2),D(n-1,m-1),D(n-2,m-1)]); end end %Search of the optimal path on the given matrix: Dist=D(N,M); n=N; m=M; k=1; w=[]; w(1,:)=[N,M]; while ((n+m)~=2) if (n-1)==0 m=m-1; elseif (m-1)==0 n=n-1; else [values,number]=min([D(n-1,m-1),D(n-1,m),D(n,m-1)]); switch number case 2 n=n-1; case 3 m=m-1; case 1 n=n-1; m=m-1; end end k=k+1; w=cat(1,w,[n,m]); end %End of DTW Algorithm % Euclidian distance measure function [distance]=eukl_dist1d(a1,b1) distance=abs((a1-b1)); % Add your function for the distance measurement here: function [distance]=highDimDistance(a1,b1) % sum=0; tmp=a1-b1; distance=sqrt(sum(tmp.^2)); %Berechnung des n-Dim. euklidischen Abstandes function [dist]=dotDist(a,b) dist=1-dot(a/sqrt(sum(a.*a)),b/sqrt(sum(b.*b))); function [dist]=winDist(a,b) a=sum(a,2); b=sum(b,2); dist=1-dot(a/sqrt(sum(a.*a)),b/sqrt(sum(b.*b)));
github
umariqb/3D_Pose_Estimation_CVPR2016-master
ldm.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/synthesis/ldm.m
1,078
utf_8
c37961027af9710fa4d03ca8ab9e3f7b
function [d]=ldm(t1,r1) %Dynamic Time Warping Algorithm %d is the local distance matrix (LDM) %Transpose the given Matrices t1=t1'; r1=r1'; [rows,N]=size(t1); [rows,M]=size(r1); d=zeros(N,M); %Calculation of the LDM: fprintf('Row: '); tic; for m=1:M for n=1:N %This calculates the distance per frame only for a 1-dim signal: %d(n,m)=eukl_dist1d(t1(n),r1(m)); %You should replace this by your own distance measure for n-dim signals: d(n,m)=highDimDistance(t1(:,n),r1(:,m),rows); end fprintf('\b\b\b\b'); fprintf('%4i',m); end time=toc; disp(['Calculated LDM in:' num2str(time) ' seconds']); % Euclidian distance measure function [distance]=eukl_dist1d(a1,b1) distance=abs((a1-b1)); % Add your function for the distance measurement here: function [distance]=highDimDistance(a1,b1,row) %Berechnung des n-Dim. euklidischen Abstandes distance=a1-b1; distance=distance'*distance; % for i=1:row % sum=sum+(a1(i)-b1(i))^2; % end % distance=sum;
github
umariqb/3D_Pose_Estimation_CVPR2016-master
grMinSpanTree.m
.m
3D_Pose_Estimation_CVPR2016-master/tools_intern/synthesis/GrTheory/grMinSpanTree.m
2,174
utf_8
de38e2d0ce1875aae138ca0a0ca15931
function nMST=grMinSpanTree(E) % Function nMST=grMinSpanTree(E) solve % the minimal spanning tree problem for a connected graph. % Input parameter: % E(m,2) or (m,3) - the edges of graph and their weight; % 1st and 2nd elements of each row is numbers of vertexes; % 3rd elements of each row is weight of edge; % m - number of edges. % If we set the array E(m,2), then all weights is 1. % Output parameter: % nMST(n-1,1) - the list of the numbers of edges included % in the minimal (weighted) spanning tree in the including order. % Uses the greedy algorithm. % Author: Sergiy Iglin % e-mail: [email protected] % personal page: http://iglin.exponenta.ru % ============= Input data validation ================== if nargin<1, error('There are no input data!') end [m,n,E] = grValidation(E); % E data validation % ============= The data preparation ================== En=[(1:m)',E]; % we add the numbers En(:,2:3)=sort(En(:,2:3)')'; % edges on increase order ln=find(En(:,2)==En(:,3)); % the loops numbers En=En(setdiff([1:size(En,1)]',ln),:); % we delete the loops [w,iw]=sort(En(:,4)); % sort by weight Ens=En(iw,:); % sorted edges % === We build the minimal spanning tree by the greedy algorithm === Emst=Ens(1,:); % 1st edge include to minimal spanning tree Ens=Ens(2:end,:); % rested edges while (size(Emst,1)<n-1)&(~isempty(Ens)), Emst=[Emst;Ens(1,:)]; % we add next edge to spanning tree Ens=Ens(2:end,:); % rested edges if any((Emst(end,2)==Emst(1:end-1,2))&... (Emst(end,3)==Emst(1:end-1,3))) | ... IsCycle(Emst(:,2:3)), % the multiple edge or cycle Emst=Emst(1:end-1,:); % we delete the last added edge end end nMST=Emst(:,1); % numbers of edges return function ic=IsCycle(E); % true, if graph E have cycle n=max(max(E)); % number of vertexes A=zeros(n); A((E(:,1)-1)*n+E(:,2))=1; A=A+A'; % the connectivity matrix p=sum(A); % the vertexes power ic=false; while any(p<=1), % we delete all tails nc=find(p>1); % rested vertexes if isempty(nc), return end A=A(nc,nc); % new connectivity matrix p=sum(A); % new powers end ic=true; return