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
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_Infer_MeanField.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/infer/UGM_Infer_MeanField.m
1,956
utf_8
1a659d358023ab95cf73d2942da59c9f
function [nodeBel, edgeBel, logZ] = UGM_Infer_MF(nodePot,edgePot,edgeStruct) if edgeStruct.useMex [nodeBel,edgeBel,logZ] = UGM_Infer_MFC(nodePot,edgePot,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(edgeStruct.V),int32(edgeStruct.E),edgeStruct.maxIter); else [nodeBel,edgeBel,logZ] = Infer_MF(nodePot,edgePot,edgeStruct); end end function [nodeBel, edgeBel, logZ] = Infer_MF(nodePot,edgePot,edgeStruct) [nNodes,maxState] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; maxIter = edgeStruct.maxIter; nodeBel = nodePot; for n = 1:nNodes nodeBel(n,:) = nodeBel(n,:)/sum(nodeBel(n,:)); end for i = 1:maxIter oldNodeBel = nodeBel; for n = 1:nNodes b = zeros(1,nStates(n)); % Find Neighbors edges = E(V(n):V(n+1)-1); for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if n == edgeEnds(e,2); ep = edgePot(1:nStates(n1),1:nStates(n2),e); neigh = n1; else ep = edgePot(1:nStates(n1),1:nStates(n2),e)'; neigh = n2; end for s_n = 1:nStates(n) b(s_n) = b(s_n) + nodeBel(neigh,1:nStates(neigh))*log(ep(1:nStates(neigh),s_n)); end end nb(1,1:nStates(n)) = nodePot(n,1:nStates(n)).*exp(b); nodeBel(n,1:nStates(n)) = nb(1,1:nStates(n))/sum(nb(1,1:nStates(n))); end if sum(abs(nodeBel(:)-oldNodeBel(:))) < 1e-4 break; end end % Compute edgeBel edgeBel = zeros(size(edgePot)); for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); for s1 = 1:nStates(n1) for s2 = 1:nStates(n2) edgeBel(s1,s2,e) = nodeBel(n1,s1)*nodeBel(n2,s2); end end end % Compute logZ logZ = -UGM_MFGibbsFreeEnergy(nodePot,edgePot,nodeBel,nStates,edgeEnds,V,E); end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_makeCRFEdgePotentials.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/train/UGM_makeCRFEdgePotentials.m
2,061
utf_8
d92fcedfcf5f8b4897a7fd7a073c91d6
function [edgePot] = UGM_makeEdgePotentials(Xedge,v,edgeStruct,infoStruct) % [edgePot] = UGM_makeEdgePotentials(Xedge,v,edgeStruct,infoStruct) % % Makes pairwise class potentials for each node % % Xedge(1,feature,edge) % v(feature,variable,variable) - edge weights % nStates - number of States per node % % edgePot(class1,class2,edge) if edgeStruct.useMex % Mex Code edgePot = UGM_makeEdgePotentialsC(Xedge,v,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(infoStruct.tieEdges),int32(infoStruct.ising)); else % Matlab Code edgePot = makeEdgePotentials(Xedge,v,edgeStruct,infoStruct); end end function [edgePot] = makeEdgePotentials(Xedge,v,edgeStruct,infoStruct) nInstances = size(Xedge,1); nFeatures = size(Xedge,2); edgeEnds = edgeStruct.edgeEnds; nEdges = size(edgeEnds,1); tied = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; if tied ew = v; end % Compute Edge Potentials maxState = max(nStates); edgePot = zeros(maxState,maxState,nEdges,nInstances); for i = 1:nInstances for e = 1:nEdges if ~tied ew = v(:,:,e); end n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); ep = zeros(maxState); for s1 = 1:nStates(n1) for s2 = 1:nStates(n2) if ising == 2 if s1 == s2 ep(s1,s2) = exp(Xedge(i,:,e)*ew(:,s1)); else ep(s1,s2) = 1; end elseif ising if s1 == s2 ep(s1,s2) = exp(Xedge(i,:,e)*ew); else ep(s1,s2) = 1; end else if s1 == nStates(n1) && s2 == nStates(n2) ep(s1,s2) = 1; else s = (s2-1)*maxState + s1; % = sub2ind([maxState maxState],s1,s2); ep(s1,s2) = exp(Xedge(i,:,e)*ew(:,s)); end end end end edgePot(:,:,e,i) = ep; end end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_makeCRFNodePotentials.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/train/UGM_makeCRFNodePotentials.m
1,096
utf_8
9ba31d7e5a0c2c1075e59aeba48b41dd
function [nodePot] = UGM_makeCRFnodePotentials(X,w,edgeStruct,infoStruct) % [nodePot] = UGM_makeCRFnodePotentials(X,w,edgeStruct,infoStruct) % Makes class potentials for each node % % X(1,feature,node) % w(feature,variable,variable) - node weights % nStates - number of states per node % % nodePot(node,class) if edgeStruct.useMex % Mex Code nNodes = size(X,3); nStates = edgeStruct.nStates; nodePot = UGM_makeNodePotentialsC(X,w,int32(nStates),int32(infoStruct.tieNodes)); else % Matlab Code nodePot = makeNodePotentials(X,w,edgeStruct,infoStruct); end end % C code does the same as below: function [nodePot] = makeNodePotentials(X,w,edgeStruct,infoStruct) [nInstances,nFeatures,nNodes] = size(X); tied = infoStruct.tieNodes; nStates = edgeStruct.nStates; if tied nw = w; end % Compute Node Potentials nodePot = zeros(nNodes,max(nStates),nInstances); for i = 1:nInstances for n = 1:nNodes if ~tied nw = w(:,1:nStates(n)-1,n); end nodePot(n,1:nStates(n),i) = exp([X(i,:,n)*nw 0]); end end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_CRFLoss.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/train/UGM_CRFLoss.m
5,408
utf_8
c78c4a90e6e0470ad59081dab6b49b4d
function [f,g] = UGM_loss(wv,X,Xedge,y,edgeStruct,infoStruct,inferFunc,varargin) % wv(variable) % X(instance,feature,node) % Xedge(instance,feature,edge) % y(instance,node) % edgeStruct % inferFunc % varargin - additional parameters of inferFunc showErr = 0; [nInstances,nNodeFeatures,nNodes] = size(X); nEdgeFeatures = size(Xedge,2); nFeatures = nNodeFeatures+nEdgeFeatures; edgeEnds = edgeStruct.edgeEnds; nEdges = size(edgeEnds,1); tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; maxState = max(nStates); % Form weights [w,v] = UGM_splitWeights(wv,infoStruct); f = 0; if nargout > 1 gw = zeros(size(w)); gv = zeros(size(v)); end % Make Potentials nodePot = UGM_makeCRFNodePotentials(X,w,edgeStruct,infoStruct); if edgeStruct.useMex edgePot = UGM_makeEdgePotentialsC(Xedge,v,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(infoStruct.tieEdges),int32(infoStruct.ising)); else edgePot = UGM_makeCRFEdgePotentials(Xedge,v,edgeStruct,infoStruct); end % Check that potentials don't overflow if sum(nodePot(:))+sum(edgePot(:)) > 1e100 f = inf; if nargout > 1 gw = gw(infoStruct.wLinInd); gv = gv(infoStruct.vLinInd); g = [gw(:);gv(:)]; end return; end % Always use the same seed (makes learning w/ stochastic inference more robust) randState = rand('state'); rand('state',0); randnState= randn('state'); randn('state',0); if edgeStruct.useMex % Set f to be the negative sum of the unnormalized potentials f = UGM_Loss_subC(int32(y),nodePot,edgePot,int32(edgeEnds)); else f = -computeUnnormalizedPotentials(y,nodePot,edgePot,edgeEnds); end for i = 1:nInstances % For CRFs, we need to do inference on each example [nodeBel,edgeBel,logZ] = inferFunc(nodePot(:,:,i),edgePot(:,:,:,i),edgeStruct,varargin{:}); % Update objective based on this training example f = f + logZ; if nargout > 1 % Update gradient if edgeStruct.useMex % Update gw and gv in-place UGM_updateGradientC(gw,gv,X(i,:,:),Xedge(i,:,:),y(i,:),nodeBel,edgeBel,int32(nStates),int32(tieNodes),int32(tieEdges),int32(ising),int32(edgeEnds)); else [gw,gv] = updateGradient(gw,gv,X(i,:,:),Xedge(i,:,:),y(i,:),nodeBel,edgeBel,infoStruct,edgeStruct); end end end if nargout > 1 gw = gw(infoStruct.wLinInd); gv = gv(infoStruct.vLinInd); g = [gw(:);gv(:)]; end % Reset state rand('state',randState); randn('state',randnState); end function [f] = computeUnnormalizedPotentials(y,nodePot,edgePot,edgeEnds) [nInstances,nNodes] = size(y); nEdges = size(edgeEnds,1); f = 0; for i = 1:nInstances % Caculate Potential of Observed Labels pot = 0; for n = 1:nNodes pot = pot + log(nodePot(n,y(i,n),i)); end for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); pot = pot + log(edgePot(y(i,n1),y(i,n2),e,i)); end % Update based on this training example f = f + pot; end end function [gw,gv] = updateGradient(gw,gv,X,Xedge,y,nodeBel,edgeBel,infoStruct,edgeStruct) [nInstances nNodeFeatures nNodes] = size(X); nEdgeFeatures = size(Xedge,2); edgeEnds = edgeStruct.edgeEnds; nEdges = size(edgeEnds,1); tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; maxState = max(nStates); % Update gradient of node features for n = 1:nNodes for s = 1:nStates(n)-1 if s == y(1,n) O = X(1,:,n); else O = zeros(1,nNodeFeatures); end E = nodeBel(n,s)*X(1,:,n); if tieNodes gw(:,s) = gw(:,s) - (O - E)'; else gw(:,s,n) = gw(:,s,n) - (O - E)'; end end end % Update gradient of edge features for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if ising == 2 for s = 1:min(nStates(n1),nStates(n2)) if y(1,n1) == s && y(1,n2) == s O = Xedge(1,:,e); else O = zeros(1,nEdgeFeatures); end E = edgeBel(s,s,e)*Xedge(1,:,e); if tieEdges gv(:,s) = gv(:,s) - (O - E)'; else gv(:,s,e) = gv(:,s,e) - (O - E)'; end end elseif ising if y(1,n1)==y(1,n2) O = Xedge(1,:,e); else O = zeros(1,nEdgeFeatures); end E = (sum(diag(edgeBel(:,:,e))))*Xedge(1,:,e); if tieEdges gv = gv - (O - E)'; else gv(:,e) = gv(:,e) - (O - E)'; end else for s1 = 1:nStates(n1) for s2 = 1:nStates(n2) if s1 == nStates(n1) && s2 == nStates(n2) % This element is fixed at 0 continue; end if s1 == y(1,n1) && s2 == y(1,n2) O = Xedge(1,:,e); else O = zeros(1,nEdgeFeatures); end E = edgeBel(s1,s2,e)*Xedge(1,:,e); s = (s2-1)*maxState+s1; % = sub2ind([maxState maxState],s1,s2); if tieEdges gv(:,s) = gv(:,s) - (O-E)'; else gv(:,s,e) = gv(:,s,e) - (O-E)'; end end end end end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_MRFLoss.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/train/UGM_MRFLoss.m
5,252
utf_8
dd0fdaa52e758a4d99c50e16e1efe602
function [f,g] = UGM_MRFLoss(wv,y,edgeStruct,infoStruct,inferFunc,varargin) % [f,g] = UGM_MRFLoss(wv,y,edgeStruct,infoStruct,inferFunc,varargin) nNodeFeatures = 1; nEdgeFeatures = 1; [nInstances,nNodes] = size(y); nFeatures = nNodeFeatures+nEdgeFeatures; edgeEnds = edgeStruct.edgeEnds; nEdges = size(edgeEnds,1); tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; maxState = max(nStates); X = ones(1,1,nNodes); Xedge = ones(1,1,nEdges); % Form weights [w,v] = UGM_splitWeights(wv,infoStruct); f = 0; if nargout > 1 gw = zeros(size(w)); gv = zeros(size(v)); end % Make Potentials nodePot = UGM_makeMRFnodePotentials(w,edgeStruct,infoStruct); if edgeStruct.useMex edgePot = UGM_makeEdgePotentialsC(Xedge,v,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(infoStruct.tieEdges),int32(infoStruct.ising)); else edgePot = UGM_makeMRFedgePotentials(v,edgeStruct,infoStruct); end % Check that potentials don't overflow if sum(nodePot(:))+sum(edgePot(:)) > 1e100 f = inf; if nargout > 1 gw = gw(infoStruct.wLinInd); gv = gv(infoStruct.vLinInd); g = [gw(:);gv(:)]; end return; end % Always use the same seed (makes learning w/ stochastic inference more robust) randState = rand('state'); rand('state',0); randnState= randn('state'); randn('state',0); % For MRFs, we only do inference once [nodeBel,edgeBel,logZ] = inferFunc(nodePot,edgePot,edgeStruct,varargin{:}); if edgeStruct.useMex % Set f to be the negative sum of the unnormalized potentials f = UGM_MRFLoss_subC(int32(y),nodePot,edgePot,int32(edgeEnds)); else f = -computeUnnormalizedPotentials(y,nodePot,edgePot,edgeEnds); end for i = 1:nInstances % Update objective based on this training example f = f + logZ; if nargout > 1 % Update gradient if edgeStruct.useMex % Update gw and gv in-place UGM_updateGradientC(gw,gv,X,Xedge,y(i,:),nodeBel,edgeBel,int32(nStates),int32(tieNodes),int32(tieEdges),int32(ising),int32(edgeEnds)); else [gw,gv] = updateGradient(gw,gv,X,Xedge,y(i,:),nodeBel,edgeBel,infoStruct,edgeStruct); end end end if nargout > 1 gw = gw(infoStruct.wLinInd); gv = gv(infoStruct.vLinInd); g = [gw(:);gv(:)]; end % Reset state rand('state',randState); randn('state',randnState); end function [f] = computeUnnormalizedPotentials(y,nodePot,edgePot,edgeEnds) [nInstances,nNodes] = size(y); nEdges = size(edgeEnds,1); f = 0; for i = 1:nInstances % Caculate Potential of Observed Labels pot = 0; for n = 1:nNodes pot = pot + log(nodePot(n,y(i,n))); end for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); pot = pot + log(edgePot(y(i,n1),y(i,n2),e)); end % Update based on this training example f = f + pot; end end function [gw,gv] = updateGradient(gw,gv,X,Xedge,y,nodeBel,edgeBel,infoStruct,edgeStruct) [nInstances nNodeFeatures nNodes] = size(X); nEdgeFeatures = size(Xedge,2); edgeEnds = edgeStruct.edgeEnds; nEdges = size(edgeEnds,1); tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; maxState = max(nStates); % Update gradient of node features for n = 1:nNodes for s = 1:nStates(n)-1 if s == y(1,n) O = X(1,:,n); else O = zeros(1,nNodeFeatures); end E = nodeBel(n,s)*X(1,:,n); if tieNodes gw(:,s) = gw(:,s) - (O - E)'; else gw(:,s,n) = gw(:,s,n) - (O - E)'; end end end % Update gradient of edge features for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if ising == 2 for s = 1:min(nStates(n1),nStates(n2)) if y(1,n1) == s && y(1,n2) == s O = Xedge(1,:,e); else O = zeros(1,nEdgeFeatures); end E = edgeBel(s,s,e)*Xedge(1,:,e); if tieEdges gv(:,s) = gv(:,s) - (O - E)'; else gv(:,s,e) = gv(:,s,e) - (O - E)'; end end elseif ising if y(1,n1)==y(1,n2) O = Xedge(1,:,e); else O = zeros(1,nEdgeFeatures); end E = (sum(diag(edgeBel(:,:,e))))*Xedge(1,:,e); if tieEdges gv = gv - (O - E)'; else gv(:,e) = gv(:,e) - (O - E)'; end else for s1 = 1:nStates(n1) for s2 = 1:nStates(n2) if s1 == nStates(n1) && s2 == nStates(n2) % This element is fixed at 0 continue; end if s1 == y(1,n1) && s2 == y(1,n2) O = Xedge(1,:,e); else O = zeros(1,nEdgeFeatures); end E = edgeBel(s1,s2,e)*Xedge(1,:,e); s = (s2-1)*maxState+s1; % = sub2ind([maxState maxState],s1,s2); if tieEdges gv(:,s) = gv(:,s) - (O-E)'; else gv(:,s,e) = gv(:,s,e) - (O-E)'; end end end end end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_CRFpseudoLoss.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/train/UGM_CRFpseudoLoss.m
9,857
utf_8
4f2c7be5956dc41f8c3d0ffeb9e3cb83
function [f,g,H] = UGM_loss(wv,X,Xedge,y,edgeStruct,infoStruct) % wv(variable) % X(instance,feature,node) % Xedge(instance,feature,edge) % y(instance,node) % edgeStruct % inferFunc % tied % Form weights [w,v] = UGM_splitWeights(wv,infoStruct); % Make Potentials nodePot = UGM_makeCRFNodePotentials(X,w,edgeStruct,infoStruct); if edgeStruct.useMex edgePot = UGM_makeEdgePotentialsC(Xedge,v,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(infoStruct.tieEdges),int32(infoStruct.ising)); else edgePot = UGM_makeCRFEdgePotentials(Xedge,v,edgeStruct,infoStruct); end if nargout >= 3 assert(all(edgeStruct.nStates==2) && infoStruct.ising==1 && infoStruct.tieNodes==infoStruct.tieEdges,... 'Pseudo-Hessian only implemented for 2 state Ising w/ fully tied/untied params'); end if edgeStruct.useMex edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; ising = infoStruct.ising; gw = zeros(size(w)); gv = zeros(size(v)); if nargout >= 3 tied = infoStruct.tieNodes; Hw = zeros(numel(w)); Hv = zeros(numel(v)); Hwv = zeros(numel(v),numel(w)); % gw,gv,Hw,Hv,Hwv are updated in place [f] = UGM_PseudoHessC(gw,gv,w,v,X,Xedge,int32(y),nodePot,edgePot,int32(edgeEnds),int32(V),int32(E),int32(tied),Hw,Hv,Hwv); else tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; % gw and gv are updated in place [f] = UGM_PseudoLossC(gw,gv,w,v,X,Xedge,int32(y),nodePot,edgePot,int32(edgeEnds),int32(V),int32(E),int32(nStates),int32(tieNodes),int32(tieEdges),int32(ising)); end else if nargout >= 3 [f,gw,gv,Hw,Hv,Hwv] = PseudoLoss(w,v,X,Xedge,y,nodePot,edgePot,edgeStruct,infoStruct); else [f,gw,gv] = PseudoLoss(w,v,X,Xedge,y,nodePot,edgePot,edgeStruct,infoStruct); end end gw = gw(infoStruct.wLinInd); gv = gv(infoStruct.vLinInd); g = [gw(:);gv(:)]; if nargout >= 3 Hw = Hw(infoStruct.wLinInd,infoStruct.wLinInd); Hv = Hv(infoStruct.vLinInd,infoStruct.vLinInd); H = [Hw Hwv' Hwv Hv]; end end %% Matlab version function [f,gw,gv,Hw,Hv,Hwv] = PseudoLoss(w,v,X,Xedge,y,nodePot,edgePot,edgeStruct,infoStruct) [nInstances,nNodeFeatures,nNodes] = size(X); nEdgeFeatures = size(Xedge,2); edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nEdges = size(edgeEnds,1); tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; maxState = max(nStates); showMM = 0; f = 0; gw = zeros(size(w)); gv = zeros(size(v)); if nargout > 3 Hw = zeros(numel(w)); Hv = zeros(numel(v)); Hwv = zeros(numel(v),numel(w)); end for i = 1:nInstances for n = 1:nNodes %% Update Objective % Find Neighbors edges = E(V(n):V(n+1)-1); % Compute Probability of Each State with Neighbors Fixed pot = nodePot(n,1:nStates(n),i); for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if n == edgeEnds(e,1) ep = edgePot(1:nStates(n),y(i,n2),e,i).'; else ep = edgePot(y(i,n1),1:nStates(n),e,i); end pot = pot .* ep; end % Update Objective f = f - log(pot(y(i,n))) + log(sum(pot)); %% Update Gradient if nargout > 1 nodeBel = pot/sum(pot); % Update Gradient of Node Weights for s = 1:nStates(n)-1 if s == y(i,n) Obs = X(i,:,n); else Obs = zeros(1,nNodeFeatures); end Exp = nodeBel(s)*X(i,:,n); if tieNodes gw(:,s) = gw(:,s) - (Obs - Exp).'; else gw(:,s,n) = gw(:,s,n) - (Obs - Exp).'; end end % Update Gradient of Edge Weights for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if ising == 2 if y(i,n1) == y(i,n2) Obs = Xedge(i,:,e); else Obs = zeros(1,nEdgeFeatures); end y_neigh = UGM_getNeighborState(i,n,e,y,edgeEnds); if y_neigh <= length(nodeBel) Exp = nodeBel(y_neigh)*Xedge(i,:,e); else Exp = zeros(1,nEdgeFeatures); end if tieEdges gv(:,y_neigh) = gv(:,y_neigh) - (Obs - Exp).'; else gv(:,y_neigh,e) = gv(:,y_neigh,e) - (Obs - Exp).'; end elseif ising if y(i,n1) == y(i,n2) Obs = Xedge(i,:,e); else Obs = zeros(1,nEdgeFeatures); end y_neigh = UGM_getNeighborState(i,n,e,y,edgeEnds); if y_neigh <= length(nodeBel) Exp = nodeBel(y_neigh)*Xedge(i,:,e); else Exp = zeros(1,nEdgeFeatures); end if tieEdges gv = gv - (Obs - Exp).'; else gv(:,e) = gv(:,e) - (Obs - Exp).'; end else for s = 1:nStates(n) if n == edgeEnds(e,1) neigh = n2; else neigh = n1; end if s == nStates(n) && y(i,neigh) == nStates(neigh) % This element is fixed at 0 continue; end if s == y(i,n) Obs = Xedge(i,:,e); else Obs = zeros(1,nEdgeFeatures); end Exp = nodeBel(s)*Xedge(i,:,e); if n == edgeEnds(e,1) s1 = s; s2 = y(i,neigh); else s1 = y(i,neigh); s2 = s; end sInd = (s2-1)*maxState+s1; if tieEdges gv(:,sInd) = gv(:,sInd) - (Obs - Exp).'; else gv(:,sInd,e) = gv(:,sInd,e) - (Obs - Exp).'; end end end end end %% Update Hessian % (only for binary, ising, and tieNodes==tieEdges) if nargout >= 4 % Update Hessian of node weights inner = nodeBel(1)*nodeBel(2); if tieNodes ind1 = 1:nNodeFeatures; ind2 = 1:nNodeFeatures; else ind1 = sub2ind(size(gw),1:nNodeFeatures,repmat(1,[1 nNodeFeatures]),repmat(n,[1 nNodeFeatures])); ind2 = sub2ind(size(gw),1:nNodeFeatures,repmat(1,[1 nNodeFeatures]),repmat(n,[1 nNodeFeatures])); end Hw(ind1,ind2) = Hw(ind1,ind2) + X(i,:,n)'*inner*X(i,:,n); % Update Hessian of edge weights wrt node/edge weights if tieEdges A = zeros(1,nEdgeFeatures); for e = edges(:)' y_neigh = UGM_getNeighborState(i,n,e,y,edgeEnds); if y_neigh == 1 A = A + Xedge(i,:,e); else A = A - Xedge(i,:,e); end end Hwv = Hwv + A'*inner*X(i,:,n); Hv = Hv + A'*inner*A; else % Untied Edges for e1 = edges(:)' y_neigh1 = UGM_getNeighborState(i,n,e1,y,edgeEnds); ind1 = sub2ind(size(gv),1:nEdgeFeatures,repmat(1,[1 nEdgeFeatures]),repmat(e1,[1 nEdgeFeatures])); ind2 = sub2ind(size(gw),1:nNodeFeatures,repmat(1,[1 nNodeFeatures]),repmat(n,[1 nNodeFeatures])); if y_neigh1 == 1 Hwv(ind1,ind2) = Hwv(ind1,ind2) + Xedge(i,:,e1)'*inner*X(i,:,n); else Hwv(ind1,ind2) = Hwv(ind1,ind2) - Xedge(i,:,e1)'*inner*X(i,:,n); end for e2 = edges(:)' y_neigh2 = UGM_getNeighborState(i,n,e2,y,edgeEnds); ind2 = sub2ind(size(gv),1:nEdgeFeatures,repmat(1,[1 nEdgeFeatures]),repmat(e2,[1 nEdgeFeatures])); if y_neigh1 == y_neigh2 Hv(ind1,ind2) = Hv(ind1,ind2) + Xedge(i,:,e1)'*inner*Xedge(i,:,e2); else Hv(ind1,ind2) = Hv(ind1,ind2) - Xedge(i,:,e1)'*inner*Xedge(i,:,e2); end end end end end if showMM nodeBel = pot./sum(pot); [junk mm(i,n)] = max(nodeBel); end end end if showMM sum(mm(:) ~= y(:))/numel(y) pause; end end function [y_neigh] = UGM_getNeighborState(i,n,e,y,edgeEnds) % Returns state of neighbor of node n along edge e if n == edgeEnds(e,1) y_neigh = y(i,edgeEnds(e,2)); else y_neigh = y(i,edgeEnds(e,1)); end end % pot: (e^(w*n)*e^(v*a)*e^(v*b)) % Z: e^(w*n)*e^(v*a)*e^(v*b) + e^(m*n)*e^(v*c)*e^(v*d)
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_Decode_ICM.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/decode/UGM_Decode_ICM.m
1,503
utf_8
cd4313f1c39a3352242ef7e499b04336
function [y] = UGM_Decode_ICM(nodePot, edgePot, edgeStruct,y) % INPUT % nodePot(node,class) % edgePot(class,class,edge) where e is referenced by V,E (must be the same % between feature engine and inference engine) % % OUTPUT % nodeLabel(node) if nargin < 4 [junk y] = max(nodePot,[],2); end if edgeStruct.useMex y = UGM_Decode_ICMC(nodePot,edgePot,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(edgeStruct.V),int32(edgeStruct.E),int32(y)); else y = Infer_ICM(nodePot,edgePot,edgeStruct,edgeStruct,y); end function [y] = Infer_ICM(nodePot,edgePot,edgeStruct,y) [nNodes,maxStates] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; done = 0; while ~done done = 1; for n = 1:nNodes % Compute Node Potential pot = nodePot(n,1:nStates(n)); % Find Neighbors edges = E(V(n):V(n+1)-1); % Multiply Edge Potentials for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if n == edgeEnds(e,1) ep = edgePot(1:nStates(n1),y(n2),e)'; else ep = edgePot(y(n1),1:nStates(n2),e); end pot = pot .* ep; end % Assign to Maximum State [junk newY] = max(pot); if newY ~= y(n) y(n) = newY; done = 0; end end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
UGM_Decode_Exact.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/UGM/decode/UGM_Decode_Exact.m
1,354
utf_8
982b1e4d88dc1958161d17ca9abc1743
function [nodeLabels] = UGM_Infer_Exact(nodePot, edgePot, edgeStruct) % INPUT % nodePot(node,class) % edgePot(class,class,edge) where e is referenced by V,E (must be the same % between feature engine and inference engine) % % OUTPUT % nodeLabel(node) assert(prod(edgeStruct.nStates) < 50000000,'Brute Force Exact Decoding not recommended for models with > 50 000 000 states'); if edgeStruct.useMex nodeLabels = UGM_Decode_ExactC(nodePot,edgePot,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates)); else nodeLabels = Decode_Exact(nodePot,edgePot,edgeStruct); end function [nodeLabels] = Decode_Exact(nodePot,edgePot,edgeStruct) [nNodes,maxStates] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; nStates = edgeStruct.nStates; % Initialize y = ones(nNodes,1); maxPot = -1; while 1 pot = UGM_ConfigurationPotential(y,nodePot,edgePot,edgeEnds); % Compare against max if pot > maxPot maxPot = pot; nodeLabels = y; end % Go to next y for yInd = 1:nNodes y(yInd) = y(yInd) + 1; if y(yInd) <= nStates(yInd) break; else y(yInd) = 1; end end % Stop when we are done all y combinations if yInd == nNodes && y(end) == 1 break; end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
WolfeLineSearch.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/minFunc/WolfeLineSearch.m
11,395
utf_8
3d2acf1139093fe11df95ccdf888aab8
function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(... x,t,d,f,g,gtd,c1,c2,LS,maxLS,tolX,debug,doPlot,saveHessianComp,funObj,varargin) % % Bracketing Line Search to Satisfy Wolfe Conditions % % Inputs: % x: starting location % t: initial step size % d: descent direction % f: function value at starting location % g: gradient at starting location % gtd: directional derivative at starting location % c1: sufficient decrease parameter % c2: curvature parameter % debug: display debugging information % LS: type of interpolation % maxLS: maximum number of iterations % tolX: minimum allowable step length % doPlot: do a graphical display of interpolation % funObj: objective function % varargin: parameters of objective function % % Outputs: % t: step length % f_new: function value at x+t*d % g_new: gradient value at x+t*d % funEvals: number function evaluations performed by line search % H: Hessian at initial guess (only computed if requested % Evaluate the Objective and Gradient at the Initial Step if nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x+t*d,varargin{:}); end funEvals = 1; gtd_new = g_new'*d; % Bracket an Interval containing a point satisfying the % Wolfe criteria LSiter = 0; t_prev = 0; f_prev = f; g_prev = g; gtd_prev = gtd; done = 0; while LSiter < maxLS %% Bracketing Phase if ~isLegal(f_new) || ~isLegal(g_new) if 0 if debug fprintf('Extrapolated into illegal region, Bisecting\n'); end t = (t + t_prev)/2; if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; continue; else if debug fprintf('Extrapolated into illegal region, switching to Armijo line-search\n'); end t = (t + t_prev)/2; % Do Armijo if nargout == 5 [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(... x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,... funObj,varargin{:}); else [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(... x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,... funObj,varargin{:}); end funEvals = funEvals + armijoFunEvals; return; end end if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev) bracket = [t_prev t]; bracketFval = [f_prev f_new]; bracketGval = [g_prev g_new]; break; elseif abs(gtd_new) <= -c2*gtd bracket = t; bracketFval = f_new; bracketGval = g_new; done = 1; break; elseif gtd_new >= 0 bracket = [t_prev t]; bracketFval = [f_prev f_new]; bracketGval = [g_prev g_new]; break; end temp = t_prev; t_prev = t; minStep = t + 0.01*(t-temp); maxStep = t*10; if LS == 3 if debug fprintf('Extending Braket\n'); end t = maxStep; elseif LS ==4 if debug fprintf('Cubic Extrapolation\n'); end t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep); else t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot); end f_prev = f_new; g_prev = g_new; gtd_prev = gtd_new; if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; end if LSiter == maxLS bracket = [0 t]; bracketFval = [f f_new]; bracketGval = [g g_new]; end %% Zoom Phase % We now either have a point satisfying the criteria, or a bracket % surrounding a point satisfying the criteria % Refine the bracket until we find a point satisfying the criteria insufProgress = 0; Tpos = 2; LOposRemoved = 0; while ~done && LSiter < maxLS % Find High and Low Points in bracket [f_LO LOpos] = min(bracketFval); HIpos = -LOpos + 3; % Compute new trial value if LS == 3 || ~isLegal(bracketFval) || ~isLegal(bracketGval) if debug fprintf('Bisecting\n'); end t = mean(bracket); elseif LS == 4 if debug fprintf('Grad-Cubic Interpolation\n'); end t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot); else % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nonTpos = -Tpos+3; if LOposRemoved == 0 oldLOval = bracket(nonTpos); oldLOFval = bracketFval(nonTpos); oldLOGval = bracketGval(:,nonTpos); end t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot); end % Test that we are making sufficient progress if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1 if debug fprintf('Interpolation close to boundary'); end if insufProgress || t>=max(bracket) || t <= min(bracket) if debug fprintf(', Evaluating at 0.1 away from boundary\n'); end if abs(t-max(bracket)) < abs(t-min(bracket)) t = max(bracket)-0.1*(max(bracket)-min(bracket)); else t = min(bracket)+0.1*(max(bracket)-min(bracket)); end insufProgress = 0; else if debug fprintf('\n'); end insufProgress = 1; end else insufProgress = 0; end % Evaluate new point if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; if f_new > f + c1*t*gtd || f_new >= f_LO % Armijo condition not satisfied or not lower than lowest % point bracket(HIpos) = t; bracketFval(HIpos) = f_new; bracketGval(:,HIpos) = g_new; Tpos = HIpos; else if abs(gtd_new) <= - c2*gtd % Wolfe conditions satisfied done = 1; elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0 % Old HI becomes new LO bracket(HIpos) = bracket(LOpos); bracketFval(HIpos) = bracketFval(LOpos); bracketGval(:,HIpos) = bracketGval(:,LOpos); if LS == 5 if debug fprintf('LO Pos is being removed!\n'); end LOposRemoved = 1; oldLOval = bracket(LOpos); oldLOFval = bracketFval(LOpos); oldLOGval = bracketGval(:,LOpos); end end % New point becomes new LO bracket(LOpos) = t; bracketFval(LOpos) = f_new; bracketGval(:,LOpos) = g_new; Tpos = LOpos; end if ~done && abs((bracket(1)-bracket(2))*gtd_new) < tolX if debug fprintf('Line Search can not make further progress\n'); end break; end end %% if LSiter == maxLS if debug fprintf('Line Search Exceeded Maximum Line Search Iterations\n'); end end [f_LO LOpos] = min(bracketFval); t = bracket(LOpos); f_new = bracketFval(LOpos); g_new = bracketGval(:,LOpos); % Evaluate Hessian at new point if nargout == 5 && funEvals > 1 && saveHessianComp [f_new,g_new,H] = funObj(x + t*d,varargin{:}); funEvals = funEvals + 1; end end %% function [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot); alpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep); alpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep); if alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1) if debug fprintf('Cubic Extrapolation\n'); end t = alpha_c; else if debug fprintf('Secant Extrapolation\n'); end t = alpha_s; end end %% function [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot); % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nonTpos = -Tpos+3; gtdT = bracketGval(:,Tpos)'*d; gtdNonT = bracketGval(:,nonTpos)'*d; oldLOgtd = oldLOGval'*d; if bracketFval(Tpos) > oldLOFval alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot); if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval) if debug fprintf('Cubic Interpolation\n'); end t = alpha_c; else if debug fprintf('Mixed Quad/Cubic Interpolation\n'); end t = (alpha_q + alpha_c)/2; end elseif gtdT'*oldLOgtd < 0 alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) sqrt(-1) gtdT],doPlot); if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos)) if debug fprintf('Cubic Interpolation\n'); end t = alpha_c; else if debug fprintf('Quad Interpolation\n'); end t = alpha_s; end elseif abs(gtdT) <= abs(oldLOgtd) alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],... doPlot,min(bracket),max(bracket)); alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],... doPlot,min(bracket),max(bracket)); if alpha_c > min(bracket) && alpha_c < max(bracket) if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos)) if debug fprintf('Bounded Cubic Extrapolation\n'); end t = alpha_c; else if debug fprintf('Bounded Secant Extrapolation\n'); end t = alpha_s; end else if debug fprintf('Bounded Secant Extrapolation\n'); end t = alpha_s; end if bracket(Tpos) > oldLOval t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t); else t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t); end else t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); end end
github
ColumbiaDVMM/Weak-attributes-for-large-scale-image-retrieval-master
minFunc_processInputOptions.m
.m
Weak-attributes-for-large-scale-image-retrieval-master/UGM/minFunc/minFunc_processInputOptions.m
3,704
utf_8
dc74c67d849970de7f16c873fcf155bc
function [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,... corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,... HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,... DerivativeCheck,Damped,HvFunc,bbType,cycle,... HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ... minFunc_processInputOptions(o) % Constants SD = 0; CSD = 1; BB = 2; CG = 3; PCG = 4; LBFGS = 5; QNEWTON = 6; NEWTON0 = 7; NEWTON = 8; TENSOR = 9; verbose = 1; verboseI= 1; debug = 0; doPlot = 0; method = LBFGS; cgSolve = 0; o = toUpper(o); if isfield(o,'DISPLAY') switch(upper(o.DISPLAY)) case 0 verbose = 0; verboseI = 0; case 'FINAL' verboseI = 0; case 'OFF' verbose = 0; verboseI = 0; case 'NONE' verbose = 0; verboseI = 0; case 'FULL' debug = 1; case 'EXCESSIVE' debug = 1; doPlot = 1; end end LS_init = 0; c2 = 0.9; LS = 4; Fref = 1; Damped = 0; HessianIter = 1; if isfield(o,'METHOD') m = upper(o.METHOD); switch(m) case 'TENSOR' method = TENSOR; case 'NEWTON' method = NEWTON; case 'MNEWTON' method = NEWTON; HessianIter = 5; case 'PNEWTON0' method = NEWTON0; cgSolve = 1; case 'NEWTON0' method = NEWTON0; case 'QNEWTON' method = QNEWTON; Damped = 1; case 'LBFGS' method = LBFGS; case 'BB' method = BB; LS = 2; Fref = 20; case 'PCG' method = PCG; c2 = 0.2; LS_init = 2; case 'SCG' method = CG; c2 = 0.2; LS_init = 4; case 'CG' method = CG; c2 = 0.2; LS_init = 2; case 'CSD' method = CSD; c2 = 0.2; Fref = 10; LS_init = 2; case 'SD' method = SD; LS_init = 2; end end maxFunEvals = getOpt(o,'MAXFUNEVALS',1000); maxIter = getOpt(o,'MAXITER',500); tolFun = getOpt(o,'TOLFUN',1e-5); tolX = getOpt(o,'TOLX',1e-9); corrections = getOpt(o,'CORR',100); c1 = getOpt(o,'C1',1e-4); c2 = getOpt(o,'C2',c2); LS_init = getOpt(o,'LS_INIT',LS_init); LS = getOpt(o,'LS',LS); cgSolve = getOpt(o,'CGSOLVE',cgSolve); qnUpdate = getOpt(o,'QNUPDATE',3); cgUpdate = getOpt(o,'CGUPDATE',2); initialHessType = getOpt(o,'INITIALHESSTYPE',1); HessianModify = getOpt(o,'HESSIANMODIFY',0); Fref = getOpt(o,'FREF',Fref); useComplex = getOpt(o,'USECOMPLEX',0); numDiff = getOpt(o,'NUMDIFF',0); LS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1); DerivativeCheck = getOpt(o,'DERIVATIVECHECK',0); Damped = getOpt(o,'DAMPED',Damped); HvFunc = getOpt(o,'HVFUNC',[]); bbType = getOpt(o,'BBTYPE',0); cycle = getOpt(o,'CYCLE',3); HessianIter = getOpt(o,'HESSIANITER',HessianIter); outputFcn = getOpt(o,'OUTPUTFCN',[]); useMex = getOpt(o,'USEMEX',1); useNegCurv = getOpt(o,'USENEGCURV',1); precFunc = getOpt(o,'PRECFUNC',[]); end function [v] = getOpt(options,opt,default) if isfield(options,opt) if ~isempty(getfield(options,opt)) v = getfield(options,opt); else v = default; end else v = default; end end function [o] = toUpper(o) if ~isempty(o) fn = fieldnames(o); for i = 1:length(fn) o = setfield(o,upper(fn{i}),getfield(o,fn{i})); end end end
github
dbindel/matfeap-master
feapstart.m
.m
matfeap-master/mlab/feapstart.m
9,171
utf_8
e102bfd4fb20856b20b216ca58908106
% feap = feapstart(fname, params) % % Start a FEAP process using an input file given by ifname. % The optional param argument may be used to set parameters % for the input deck; for example, if a parameter 'n' is used % in a deck 'Ifoo', then % % param.n = 10 % p = feapstart('Ifoo', param) % % will give n a default value of 10. % % The params structure can also contain special fields that % control details of the deck processing: % % verbose - Indicate whether we want to see FEAP interactions or not % sockname - If defined, connect to FEAP via a UNIX domain socket % command - If defined, connect to the indicated FEAP via a pipe % server - Host name for FEAP server (default: '127.0.0.1') % port - Port for FEAP server (default: 3490) % % Parameters can also be passed through a global variable called % matfeap_globals. feapstart reads control parameters from matfeap_globals % as though they were entered through the params structure; if the control % parameters are specified via matfeap_globals and via a parameter argument, % the latter has precedence. %@T % \section{Starting FEAP} % % The [[feapstart]] command is used to launch a new FEAP process: %@c function p = feapstart(fname, params) %@T % % The file name argument is required. The optional [[params]] % argument plays double duty: a set of special parameters are used % to control things about the MATFEAP interface, and the remaining % parameters are used to initialize the FEAP variable list before % opening the designated input deck. %@q % --- Checking input parameters --- if ~ischar(fname), error('Expected filename as string'); end if nargin > 1, if ~isstruct(params) & ~isempty(params) error('Expected params as struct'); end else params = []; end %@T ----------------------------------------------------------- % \subsection{Merging global parameters} % % The [[matfeap_globals]] variable is used to provide default % values for the fields in the [[params]] structure, if explicit % values are not otherwise provided. %@c global matfeap_globals; if isstruct(matfeap_globals) if isempty(params) params = matfeap_globals; else pnames = fieldnames(matfeap_globals); for k = 1:length(pnames) if ~isfield(params, pnames{k}) pvalue = getfield(matfeap_globals, pnames{k}); params = setfield(params, pnames{k}, pvalue); end end end end %@T ----------------------------------------------------------- % \subsection{Special parameters} % % The special parameters are % \begin{itemize} % \item [[verbose]]: if true, output all the stuff that FEAP sends % \item [[server]] and [[port]]: the server host name % (string) and port number (integer) % \item [[command]]: if defined, this string says how to % execute the extended FEAP directly from the command line. % Used as an alternative to opening a socket connection. % \item [[dir]]: the starting directory to change to after % connecting to the FEAP server. By default we use the % client's present working directory. % \end{itemize} % % At the same time we process these parameters, we remove them % from the [[param]] structure. That way, everything remaining % in the [[param]] structure after this step can be interpreted % as a FEAP input parameter. %@c verb = 0; % Are we in verbose mode? server = '127.0.0.1'; % Server where FEAP is located port = 3490; % Port where FEAP is located dir = pwd; % Base directory to use for rel paths command = []; % Command string to use with pipe interface sockname = []; % UNIX domain socket name if ~isempty(params) if isfield(params, 'verbose') verb = params.verbose; params = rmfield(params, 'verbose'); end if isfield(params, 'server') server = params.server; params = rmfield(params, 'server'); end if isfield(params, 'port') port = params.port; params = rmfield(params, 'port'); end if isfield(params, 'command') command = params.command; params = rmfield(params, 'command'); end if isfield(params, 'sockname') sockname = params.sockname; params = rmfield(params, 'sockname'); end if isfield(params, 'dir') dir = params.dir; params = rmfield(params, 'dir'); end end %@T ----------------------------------------------------------- % \subsection{Input deck directory} % % I assume that the file name does not contain any slashes or % backslashes; if those occur in the input deck name, then we'll % split the name argument into [[pathname]] and [[fname]]. %@c lastslash = max([strfind(fname, '/'), strfind(fname, '\')]); if ~isempty(lastslash) pathname = fname(1:lastslash-1); fname = fname(lastslash+1:end); else pathname = []; end %@T ----------------------------------------------------------- % \subsection{Opening FEAP} % % If [[sockname]] is nonempty, then the user has specified % a UNIX domain socket to connect to the FEAP server. Otherwise % if [[command]] is nonempty, then the user has specified the % name of a command to start the (extended) FEAP. This FEAP % executable has the same interface as the socket-based version, % but it communicates using the ordinary standard I/O streams, % which we will connect to a pipe. Otherwise, we'll try to % communicate with the server via TCP. We give the same generic error % message in the event of any error -- ``is the server there?'' % % Once a connection to the FEAP process has been established, % we save the relevant Java helper (or C handle) and the verbosity flag % together in a handle structure. This structure is the first argument % to all the high-level MATFEAP interface functions. %@c try if ~isempty(sockname) fd = sock_new(sockname); elseif ~isempty(command) fd = sock_new(command); else fd = sock_new(server, port); end catch fprintf('Could not open connection -- is the FEAP server running?\n'); error(lasterr); end p = []; p.fd = fd; p.verb = verb; %@T ----------------------------------------------------------- % \subsection{Passing parameters} % % The [[param]] command in the [[feapsrv]] interface allows the % user to send parameters to FEAP. Parameter assignments have the % form ``param var val''. Invalid assignments are (perhaps suboptimally) % simply ignored. %@c feapsrvp(p); if ~isempty(params) pnames = fieldnames(params); for k = 1:length(pnames) pvar = pnames{k}; pval = getfield(params, pnames{k}); if ~isnumeric(pval) fprintf('Ignoring non-numeric parameter %s\n', pvar); else sock_send(fd, sprintf('param %s %g', pvar, pval)); feapsrvp(p); end end end %@T ----------------------------------------------------------- % \subsection{Setting the current directory} % % If a home directory was specified via a [[dir]] special % argument, we first change to that directory (by default, we % change to the client's present working directory). If a path was % specified as part of the input deck name, we then change to that % directory. If both [[dir]] and [[pathname]] are non-empty % and the [[pathname]] specifies a relative path, we will end up % in the path relative to the specified base directory. % % The [[feapsrv]] command to change directories will return a % diagnostic message if for any reason the directory change doesn't % go through. We ignore said message. %@c if ~isempty(dir) sock_send(fd, ['cd ', dir]); feapsrvp(p); end if ~isempty(pathname) sock_send(fd, ['cd ', pathname]); feapsrvp(p); end %@T ----------------------------------------------------------- % \subsection{Sending the file names} % % Once we've set up the parameter string and changed to the proper % directory, we're ready to actually start processing an input % deck. The [[start]] command gets us out of the [[feapsrv]] % interface and into ordinary FEAP interactions. We now need to % send to FEAP: % \begin{enumerate} % \item % The name of the input deck. % \item % Blank lines to say ``we accept the default names for the % auxiliary files.'' The number of auxiliary files has changed % over time, which is why we don't use a counter -- we just send % a blank line at every synchronization message until we see a % string that indicates that we've entered all the desired file % names. % \item % A string ``y'' for when we're asked if the file names are % correct. % \end{enumerate} % % If an error occurs during entering the file name, we send the % ``quit'' string and get out of dodge. In response to a request % to quit, FEAP will go through the ordinary shutdown procedure, % so we'll wait for the last synchronization message before closing % the connection. %@c sock_send(fd, 'start'); feapsync(p); sock_send(fd, fname); doneflag = 0; while 1 s = sock_recv(fd); if strfind(s, '*ERROR*') p.verb = 1; feapsync(p); sock_send(fd, 'quit'); feapsync(p); sock_close(fd); p = []; return; elseif strfind(s, 'Files are set') feapdispv(p, s); feapsync(p); sock_send(fd, 'y') feapsync(p); return; elseif strfind(s, 'MATFEAP SYNC') sock_send(fd, ''); else feapdispv(p, s); end end
github
dbindel/matfeap-master
feapjsock.m
.m
matfeap-master/mlab/jsock/feapjsock.m
1,707
utf_8
a6ed7d43c262995619f84c9aac082663
function feapjsock; % @T ----------------------------------- % \section{Interface to the Java socket helper} % % The Java socket helper class is a thin layer that lets us use % Java stream descriptors and binary I/O routines. We use it to % establish socket connections, send an recieve lines of data, % etc. % % The socket routines are % \begin{itemize} % \item [[sock_new(hostname,port)]] - start a socket connection % \item [[sock_new(command)]] - start a pipe connection % \item [[sock_close(js)]] - close a socket % \item [[sock_recv(js)]] - read a line of data % \item [[sock_send(js)]] - send a line of data % \item [[sock_readdarray(js, len)]] - read [[len]] 64-bit doubles % into an array % \item [[sock_readiarray(js, len)]] - read [[len]] 32-bit integers % into an array % \item [[sock_senddarray(js, array)]] - send an array of 64-bit doubles % \item [[sock_sendiarray(js, array)]] - send an array of 32-bit integers % \end{itemize} %@o sock_new.m function p = sock_new(hostname, port) if nargin == 2 p.helper = FeapClientHelper(hostname, int32(port)); else p.helper = FeapClientHelper(hostname); end %@o %@o sock_close.m function sock_close(p) p.helper.close(); %@o %@o sock_recv.m function s = sock_recv(p) s = char(p.helper.readln()); %@o %@o sock_send.m function sock_send(p, msg) p.helper.send(msg); %@o %@o sock_recvdarray.m function val = sock_recvdarray(p, len) val = p.helper.getDarray(int32(len)); %@o %@o sock_recviarray.m function val = sock_recviarray(p, len) val = p.helper.getIarray(int32(len)); %@o %@o sock_senddarray.m function sock_senddarray(p, x) p.helper.setDarray(x); %@o %@o sock_sendiarray.m function sock_sendiarray(p, x) p.helper.setIarray(x); %@o
github
dbindel/matfeap-master
feaps.m
.m
matfeap-master/mlab/web/feaps.m
4,407
utf_8
1cd3632e19fb2425b5a1c1dca1081e1b
% @T =========================== % \section {Communication setup} % % These routines are used to specify which of the three communication modes % available to MATFEAP should be used. % % @q =========================== % @T ------------------------------------------------------------------- % \subsection{Setting up pipe communication} % % The [[feaps_pipe]] function tells MATFEAP to manage communication % over a bidirectional pipe managed by Java. This method is not % available in the C interface -- there the prefered connection method is % a UNIX-domain socket. % % The default location for the FEAP executable used by in pipe mode is % {\tt {\it MATFEAP}/srv/feapp}. The location of the [[feaps_pipe.m]] % file should be {\tt {\it MATFEAP}/srv/feaps\_pipe.m}. Since the latter % file is obviously on the MATLAB path, we can get the fully qualified % name from MATLAB and extract the location of the MATFEAP home directory % from it. %@o feaps_pipe.m % feaps_pipe(cmd) % % Tell MATFEAP to use a pipe to connect to FEAP. If cmd == [], turn off % MATFEAP pipe connection mode. If cmd is not provided, fill in a default % location based on the location of this mfile. %@c function feaps_pipe(cmd) global matfeap_globals matfeap_globals.sockname = []; matfeap_globals.server = []; matfeap_globals.port = []; if nargin < 1 s = which('feaps_pipe.m'); i = strfind(s, 'feaps_pipe.m')-length('mlab/'); matfeap_globals.command = [s(1:i-1), 'srv/feapp']; fprintf('Using FEAP in pipe mode: %s\n', matfeap_globals.command); elseif isempty(cmd) matfeap_globals.command = []; fprintf('Turning off FEAP pipe mode\n'); else matfeap_globals.command = cmd; end % @T -------------------------------------------------------------------- % \subsection{Setting up TCP socket communication} % % The [[feaps_tcp]] function tells MATFEAP to manage communication % over a TCP socket (which may be managed by Java or C). The default % location for the server is the local host on port 3490. %@o feaps_tcp.m % feaps_tcp(server, port) % % Tell MATFEAP to use a TCP socket to connect to FEAP. feaps_tcp([]) turns off % MATFEAP UNIX connection mode. Either the server or the port can be % omitted; the default server is 127.0.0.1, and the default port is 3490. %@c function feaps_tcp(server, port) global matfeap_globals matfeap_globals.command = []; matfeap_globals.sockname = []; matfeap_globals.server = []; matfeap_globals.port = []; if nargin < 1 matfeap_globals.server = '127.0.0.1'; matfeap_globals.port = 3490; elseif nargin == 1 if isempty(server) fprintf('Turning off FEAP TCP mode\n'); return; elseif isnumeric(server) matfeap_globals.server = '127.0.0.1'; matfeap_globals.port = server; else matfeap_globals.server = server; matfeap_globals.port = 3490; end else matfeap_globals.server = server; matfeap_globals.port = port; end fprintf('Using FEAP in TCP mode: %s:%d\n', ... matfeap_globals.server, matfeap_globals.port); % @T -------------------------------------------------------------------- % \subsection{Setting up UNIX socket communication} % % The [[feaps_unix]] function tells MATFEAP to manage communication % over a UNIX-domain socket. This option is only available with the C % interface. UNIX-domain sockets are identified by filesystem locations, % typically placed under [[/tmp]]. For MATFEAP, we use the default % name {\tt /tmp/feaps-{\it USER}}, where {\it USER} is the user name in % the current environment. Because MATLAB doesn't have direct access to % the environment, we fetch the default socket name through the wrapper % function [[sock_default_unix]]. %@o feaps_unix.m % feaps_unix(sockname) % % Tell MATFEAP to use a UNIX socket to connect to FEAP. If sockname == [], % turn off MATFEAP UNIX connection mode. If sockname is not provided, fill in % a default socket name based on the location of this mfile. %@c function feaps_unix(sockname) global matfeap_globals matfeap_globals.command = []; matfeap_globals.sockname = []; matfeap_globals.server = []; matfeap_globals.port = []; if nargin < 1 matfeap_globals.sockname = sock_default_unix; elseif nargin == 1 if isempty(sockname) fprintf('Turning off FEAP UNIX mode\n'); return; else matfeap_globals.sockname = sockname; end end fprintf('Using FEAP on UNIX socket: %s\n', matfeap_globals.sockname);
github
dbindel/matfeap-master
feaputil.m
.m
matfeap-master/mlab/web/feaputil.m
3,327
utf_8
cb927dcc4eeae6458daad5401522e6b7
function feaputil; % @T =========================== % \section {Utility commands} % % These are low-level routines that should generally be invisible % to the user. % % @q =========================== % @T -------------------------------------------- % \subsection{Waiting for synchronization} % % The [[feapsync]] command is used to wait for a synchronization % message sent by the server. For the moment, we don't use the % synchronization labels. %@o feapsync.m % feapsync(feap, barriernum) % % Synchronize on a MATFEAP SYNC string %@c function feapsync(p, barriernum) if nargin == 1, barriernum = 0; end while 1 s = sock_recv(p.fd); if strfind(s, 'MATFEAP SYNC') if barriernum == 0 break; elseif strcmp(s, sprintf('MATFEAP SYNC %d', barriernum)) break else feapdispv(p, 'Unexpected barrier'); feapdispv(p, s); end else feapdispv(p, s); end end %@o % @T -------------------------------------------- % \subsection{Waiting for {\tt FEAPSRV}} % % The [[feapsrvp]] command is used to wait for the server to send % a [[FEAPSRV]] prompt when using the [[feapsrv]] command % interface. %@o feapsrvp.m % s = feapsrvp(feap) % % Wait for the FEAPSRV prompt %@c function s = feapsrvp(p, prompt) while 1 s = sock_recv(p.fd); feapdispv(p, s); if strfind(s, 'FEAPSRV>'), break; end end %@o % @T -------------------------------------------- % \subsection{Verbose output} % % The [[feapdispv]] routine is used to write messages to the % standard output conditioned on the FEAP server being in verbose % mode. This is useful if you want to look at the output of FEAP % for debugging purposes. %@o feapdispv.m % feapdispv(feap, msg) % % Display the message if verbose is true %@c function feapdispv(p, msg) if p.verb if length(msg) == 0, msg = ' '; end disp(msg); end %@o % @T -------------------------------------------- % \subsection{Index mapping} % % The [[ID]] array in FEAP is used to keep track of which nodal % variables are active and which are determined by some boundary % condition. We return the relevant portion of the [[ID]] array % along with: % \begin{enumerate} % \item % The indices of all active degrees of freedom ([[full_id]]). % \item % The indices of all variables subject to BCs ([[bc_id]]). % \item % An array to map the indices of the active degrees of freedom % in the full vector to indices in a reduced vector ([[reduced_id]]). % \end{enumerate} %@o map2full.m % [full_id, bc_id, reduced_id, id] = map2full(feap) % % Get mapping from full to reduced dof set for current FEAP deck. % % Output: % full_id -- index of free variables in full dof vector % bc_id -- index of displacement BC variables % reduced_id -- index of free variables in reduced dof set % (a permutation) % id -- first part of FEAP index array %@c function [full_id, bc_id, reduced_id, id] = map2full(p) % Get mesh parameters nneq = feapget(p, 'nneq'); % Number of unreduced dof numnp = feapget(p, 'numnp'); % Number of dof ndf = feapget(p, 'ndf'); % Maximum dof per node % Get the index map id = feapgetm(p, 'id'); id = reshape(id(1:nneq), ndf, numnp); % Find the index set for free vars in full and reduced vectors full_id = find(id > 0); bc_id = find(id <= 0); reduced_id = id(full_id);
github
dbindel/matfeap-master
feapgetset.m
.m
matfeap-master/mlab/web/feapgetset.m
12,849
utf_8
e8d076c7e3aca7936adb76e7f2757911
function feapgetset; % @T =========================== % \section {Basic getter / setter interfaces} % % These are the MATLAB interface routines that get and set FEAP % matrices, arrays, and scalars. % % @q =========================== % @T -------------------------------------------- % \subsection{Getting scalar values} % % To get a scalar variable, we enter the [[feapsrv]] interface % and issue a {\tt get {it varname}} request. Either it succeeds, % in which case the variable is printed; or it fails, in which case % nothing is printed. We silently return an empty array to % indicate the latter case. After retrieving the variable, we % issue a [[start]] command to exit the [[feapsrv]] interface % and get back to the FEAP macro prompt. %@o feapget.m % val = feapget(feap, vname) % % Get a scalar value out of a FEAP common block entry % Ex: % neq = feapget(p, 'neq'); %@c function val = feapget(p, var) if nargin < 2, error('Missing required argument'); end if ~ischar(var), error('Variable name must be a string'); end sock_send(p.fd, 'serv'); feapsrvp(p); cmd = sprintf('get %s', lower(var)); feapdispv(p, cmd); sock_send(p.fd, cmd); val = []; resp = sock_recv(p.fd); if ~strcmp(resp, 'FEAPSRV> ') val = sscanf(resp, '%g'); feapdispv(p, resp); feapsrvp(p); end sock_send(p.fd, 'start'); feapsync(p); %@o % @T -------------------------------------------- % \subsection{Getting arrays} % % This routine implements the client side of the array fetch % protocol described in the [[feapsrv]] documentation. We enter % the [[feapsrv]] command interface, issue a request for a % matrix, read the server's description of the matrix size and % type, and then either start an appropriate binary data transfer % or bail if something looks malformed. After all this, we return % to the FEAP macro interface. %@o feapgetm.m % array_val = feapgetm(feap, array_name) % % Get a dynamically allocated FEAP array by name. array_val will be % a column vector -- use reshape to change it into a matrix if % appropriate. %@c function val = feapgetm(p, var) if nargin < 2, error('Missing required argument'); end if ~ischar(var), error('Variable name must be a string'); end sock_send(p.fd, 'serv'); feapsrvp(p); cmd = sprintf('getm %s', upper(var)); feapdispv(p, cmd); sock_send(p.fd, cmd); resp = sock_recv(p.fd); [s, resp] = strtok(resp); val = []; if strcmp(s, 'Send') [datatype, resp] = strtok(resp); % Data type (int | double) [len, resp] = strtok(resp); % Number of entries len = str2num(len); if strcmp(datatype, 'int') feapdispv(p, sprintf('Receive %d ints...', len)); sock_send(p.fd, 'binary') val = sock_recviarray(p.fd, len); elseif strcmp(datatype, 'double') feapdispv(p, sprintf('Receive %d doubles...', len)); sock_send(p.fd, 'binary') val = sock_recvdarray(p.fd, len); else feapdispv(p, 'Did not recognize response, bailing'); sock_send(p.fd, 'cancel') end end feapsrvp(p); sock_send(p.fd, 'start') feapsync(p); %@o % @T -------------------------------------------- % \subsection{Setting arrays} % % This routine implements the client side of the array set % protocol described in the [[feapsrv]] documentation. It is % exactly analogous to [[feapgetm]], except that now we have to % make sure that we're sending the right amount of data. We should % almost certainly advertize more clearly when we've exited because % the specified array was the wrong size. %@o feapsetm.m % feapsetm(feap, array_name, array_val) % % Set a dynamically allocated FEAP array's entries. Note that array_val % can be whatever shape is desired, so long as it has the correct number of % entries. %@c function feapsetm(p, var, val) sock_send(p.fd, 'serv'); feapsrvp(p); cmd = sprintf('setm %s', upper(var)); feapdispv(p, cmd); sock_send(p.fd, cmd); resp = sock_recv(p.fd); [s, resp] = strtok(resp); if strcmp(s, 'Recv') [datatype, resp] = strtok(resp); [len, resp] = strtok(resp); len = str2num(len); if len ~= prod(size(val)) feapdispv(p, sprintf('Expected size %d; bailing', len)); sock_send(p.fd, 'cancel'); elseif strcmp(datatype, 'int') feapdispv(p, sprintf('Sending %d ints...', len)); sock_send(p.fd, 'binary') sock_sendiarray(p.fd, val); elseif strcmp(datatype, 'double') feapdispv(p, sprintf('Sending %d doubles...', len)); sock_send(p.fd, 'binary') sock_senddarray(p.fd, val); else feapdispv(p, 'Did not recognize response, bailing'); sock_send(p.fd, 'cancel') end end feapsrvp(p); sock_send(p.fd, 'start') feapsync(p); %@o % @T -------------------------------------------- % \subsection{Getting sparse matrices} % % This routine implements the client side of the sparse matrix fetch % protocol described in the [[feapsrv]] documentation. We start % the [[feapsrv]] command interface, request the array, read the % number of nonzero entries, and either fetch a block of binary % data and convert it to a sparse matrix, or bail if we saw % something unexpected. %@o feapgetsparse.m % val = feapgetsparse(feap, vname) % % Get a sparse matrix value out of FEAP. Valid array names are % 'tang', 'utan', 'lmas', 'mass', 'cmas', 'umas', 'damp', 'cdam', 'udam' %@c function val = feapgetsparse(p, var) if nargin < 2, error('Wrong number of arguments'); end if ~ischar(var), error('Variable name must be a string'); end if length(var) < 1, error('Variable name must be at least one char'); end sock_send(p.fd, 'serv'); feapsrvp(p); cmd = sprintf('sparse binary %s', lower(var)); feapdispv(p, cmd); sock_send(p.fd, cmd); resp = sock_recv(p.fd); [s, resp] = strtok(resp); val = []; if strcmp(s, 'nnz') [len, resp] = strtok(resp); len = str2num(len); feapdispv(p, sprintf('Receive %d matrix entries...', len)); val = sock_recvdarray(p.fd, 3*len); val = reshape(val, 3, len); val = sparse(val(1,:), val(2,:), val(3,:)); end feapsrvp(p); sock_send(p.fd, 'start') feapsync(p); %@o % @T =========================== % \section {Getting stiffness, mass, and damping} % % These are the high-level interface routines that fetch or write % the main FEAP sparse matrices. % % @q =========================== % @T -------------------------------------------- % \subsection{Tangent matrix} % % The [[feaptang]] and [[feaputan]] routines call FEAP macros % to form the tangent stiffness matrix (symmetric or unsymmetric) % without factoring it, and then retrieve the matrix into MATLAB. %@o feaptang.m % K = feaptang(feap) % % Form and fetch the current FEAP tangent matrix %@c function K = feaptang(p) feapcmd(p, 'tang,,-1'); K = feapgetsparse(p, 'tang'); %@o % --- %@o feaputan.m % K = feaputan(feap) % % Form and fetch the FEAP current unsymmetric tangent matrix %@c function K = feaputan(p) feapcmd(p, 'utan,,-1'); K = feapgetsparse(p, 'utan'); %@o % @T -------------------------------------------- % \subsection{Mass matrix} % % The [[feapmass]] and [[feapumass]] routines call FEAP macros % to form the mass (symmetric or unsymmetric), and then retrieve % the matrix into MATLAB. This high-level interface only allows % you to get the consistent mass, and not the lumped mass. %@o feapmass.m % M = feapmass(feap) % % Get the current FEAP mass matrix %@c function M = feapmass(p) feapcmd(p, 'mass'); M = feapgetsparse(p, 'mass'); %@o % --- %@o feapumass.m % M = feapumass(feap) % % Get the current FEAP unsymmetric mass matrix %@c function M = feapumass(p) feapcmd(p, 'mass,unsy'); M = feapgetsparse(p, 'umas'); %@o % @T -------------------------------------------- % \subsection{Damping matrix} % % The [[feapdamp]] and [[feapudamp]] routines call FEAP macros % to form the damping (symmetric or unsymmetric), and then retrieve % the matrix into MATLAB. %@o feapdamp.m % D = feapdamp(feap) % % Get the current FEAP damping matrix %@c function D = feapdamp(p) feapcmd(p, 'damp'); D = feapgetsparse(p, 'damp'); %@o % --- %@o feapudamp.m % D = feapudamp(feap) % % Get the current FEAP unsymmetric damping matrix %@c function D = feapudamp(p) feapcmd(p, 'damp,unsy'); D = feapgetsparse(p, 'damp'); %@o % @T =========================== % \section {Getting and setting [[X]], [[U]], and [[F]] vectors} % % These are the high-level interface routines that fetch or write % the node position, displacement, and residual vectors. % % @q =========================== % @T -------------------------------------------- % \subsection{Getting the displacement} % % The [[feapgetu]] command retrieves the full displacement array % [[U]] and returns some subset of it. By default, we extract the % active degrees of freedom in the reduced order, using % [[map2full]] to retrieve the appropriate reindexing vector. %@o feapgetu.m % u = feapgetu(feap, id) % % Get the displacement vector from FEAP. The id argument is optional; % if it is ommitted, only active degrees of freedom are returned. %@c function u = feapgetu(p, id) if nargin < 2, id = map2full(p); end u = feapgetm(p, 'u'); u = u(id); %@o % @T -------------------------------------------- % \subsection{Setting the displacement} % % The [[feapsetu]] command sets some subset of the displacement % array [[U]] (by default, we set the active degrees of % freedom). If we don't provide a vector to write out, then the % assumption is that we want to clear the displacement vector to % zero, save for any essential boundary conditions (which FEAP % keeps in the second part of the [[F]] array). %@o feapsetu.m % feapsetu(feap, u, id) % % Set the displacement vector from FEAP. The id argument is optional; % if it is omitted, all active degrees of freedom are returned. %@c function feapsetu(p,u, id) if nargin < 3, [id, bc_id] = map2full(p); end u1 = feapgetm(p,'u'); if nargin < 2 nneq = feapget(p,'nneq'); f = feapgetm(p,'f'); u1(bc_id) = f(bc_id + nneq); end u1(id) = u; feapsetm(p, 'u', u1); %@o % @T -------------------------------------------- % \subsection{Getting the nodal positions} % % The [[feapgetx]] command gets the nodal position matrix [[X]] % and, optionally, a parallel matrix of displacements. These % displacements can be extracted from a displacement vector passed % in as an argument, or they can be retrieved from the FEAP [[U]] % array. %@o feapgetx.m % [xx, uu] = feapgetx(feap, u) % % Get the node positions (xx) and their displacements (uu). % Uses the reduced displacement vector u, or the reduced displacement % vector from FEAP if u is not provided. %@c function [xx, uu] = feapgetx(p,u) % Get mesh parameters nnp = feapget(p,'numnp'); % Number of nodal points nneq = feapget(p,'nneq'); % Number of unreduced dof neq = feapget(p,'neq'); % Number of dof ndm = feapget(p,'ndm'); % Number of spatial dimensions ndf = feapget(p,'ndf'); % Maximum dof per node % Get node coordinates from FEAP xx = feapgetm(p,'x'); xx = reshape(xx, ndm, length(xx)/ndm); if nargout > 1 % Extract u if not provided if nargin < 1, u = feapgetu(p); end % Find out how to map reduced to full dof set id = feapgetm(p,'id'); id = reshape(id(1:nneq), ndf, nnp); idnz = find(id > 0); % Get full dof set uu = zeros(ndf, nnp); uu(idnz) = u(id(idnz)); end %@o % @T -------------------------------------------- % \subsection{Getting the residual} % % The [[feapresid]] function forms the residual and fetches it % from FEAP memory. If the user provides a reduced displacement % vector [[u]] as an argument, then that vector will be written % to FEAP's array of nodal unknowns before evaluating the residual. % % The one thing that's a little tricky about [[feapresid]] has to do % with an optimization in FEAP. Usually, calls to the FEAP macro to % form the residual don't do anything unless there has been a solve % step since the previous request for a residual form. But when we % modify the displacements and boundary conditions behind FEAP's back, % we typically invalidate the current residual, whatever it may be. % So before requesting that FEAP form a new residual, we use the % [[feapsrv]] interface to clear the flag that says that the residual has % already been formed. %@o feapresid.m % R = feapresid(feap, u, id) % % Get the residual corresponding to a particular input vector. % Both the u (displacement vector) and id (variable index) arguments % can be ommitted: % % R = feapresid(p); % Get the current residual % R = feapresid(p,u); % Set FEAP's active displacements to u first % R = feapresid(p,u,id); % Set displacements (possibly not active) first %@c function R = feapresid(p, u, id) if nargin == 2 feapsetu(p,u); elseif nargin == 3 feapsetu(p,u, id); end sock_send(p.fd,'serv'); feapsrvp(p); feapdispv(p, 'clear_isformed'); sock_send(p.fd, 'clear_isformed'); feapsrvp(p); sock_send(p.fd, 'start'); feapsync(p); feapcmd(p,'form'); R = feapgetm(p,'dr'); R = R(1:feapget(p,'neq')); %@o
github
dbindel/matfeap-master
feapuser.m
.m
matfeap-master/mlab/web/feapuser.m
2,227
utf_8
af1bd30707611e6be7a5eae37954cff2
function feapuser; % @T =========================== % \section {User commands} % % These are the main routines in the interface used directly by MATFEAP % users. % % @q =========================== % @T -------------------------------------------- % \subsection{Invoking FEAP macro commands} % % The [[feapcmd]] routine is used to invoke FEAP macro routines. % It's up to the user to ensure that after the end of the last command % in the list, FEAP is back at a prompt involving a [[tinput]] % command (e.g. the macro prompt or a plot prompt). % % The [[feapcmd]] routine should not be used to quit FEAP; use % [[feapquit]] for that. %@o feapcmd.m % feapcmd(feap, c1, c2, c3, ...) % % Run the FEAP macro commands specified by strings c1, ... %@c function feapcmd(p, varargin) for k = 1:length(varargin) sock_send(p.fd, varargin{k}); feapsync(p); end %@o % @T -------------------------------------------- % \subsection{Exiting FEAP} % % The [[feapquit]] command invokes the quit command, says ``n'' % when asked whether we would like to continue, waits for the % sign-off synchronization message, and shuts down the connection. % This is the graceful way to exit from FEAP. In contrast, the % [[feapkill]] command should be treated as a last-ditch effort % to kill a misbehaving FEAP process. %@o feapquit.m % feapquit(feap) % % Gracefully exit from FEAP. %@c function feapquit(p) sock_send(p.fd, 'quit'); feapsync(p); sock_send(p.fd, 'n'); feapsync(p,1); sock_close(p.fd); %@o %@o feapkill.m % feapkill(feap) % % Force quit on FEAP process. %@c function feapkill(p) sock_close(p.fd); %@o % @T -------------------------------------------- % \subsection{Putting MATFEAP into verbose mode} % % In verbose mode, you can see all the interactions between MATFEAP % and FEAP. It's possible to switch to verbose mode by setting the % [[verbose]] field in the parameter structure for [[feapstart]], % or by setting the [[matfeap_globals]] structure directly; but % I find myself wanting to see verbose output fairly regularly, so % it seemed worthwhile to have a special method for it. %@o feaps_verb.m % Put MATFEAP into verbose mode. %@c function feaps_verb global matfeap_globals; matfeap_globals.verbose = 1;
github
seisgo/EllipseFit-master
funcEllipseFit_RBrown.m
.m
EllipseFit-master/matlab/funcEllipseFit_RBrown.m
12,164
utf_8
6a7540c4ea13825a717addd48ae2051a
function [z, a, b, alpha] = funcEllipseFit_RBrown(x, varargin) %FITELLIPSE least squares fit of ellipse to 2D data % http://www.mathworks.com/matlabcentral/fileexchange/15125-fitellipse-m % [Z, A, B, ALPHA] = FITELLIPSE(X) % Fit an ellipse to the 2D points in the 2xN array X. The ellipse is % returned in parametric form such that the equation of the ellipse % parameterised by 0 <= theta < 2*pi is: % X = Z + Q(ALPHA) * [A * cos(theta); B * sin(theta)] % where Q(ALPHA) is the rotation matrix % Q(ALPHA) = [cos(ALPHA), -sin(ALPHA); % sin(ALPHA), cos(ALPHA)] % % Fitting is performed by nonlinear least squares, optimising the % squared sum of orthogonal distances from the points to the fitted % ellipse. The initial guess is calculated by a linear least squares % routine, by default using the Bookstein constraint (see below) % % [...] = FITELLIPSE(X, 'linear') % Fit an ellipse using linear least squares. The conic to be fitted % is of the form % x'Ax + b'x + c = 0 % and the algebraic error is minimised by least squares with the % Bookstein constraint (lambda_1^2 + lambda_2^2 = 1, where % lambda_i are the eigenvalues of A) % % [...] = FITELLIPSE(..., 'Property', 'value', ...) % Specify property/value pairs to change problem parameters % Property Values % ================================= % 'constraint' {|'bookstein'|, 'trace'} % For the linear fit, the following % quadratic form is considered % x'Ax + b'x + c = 0. Different % constraints on the parameters yield % different fits. Both 'bookstein' and % 'trace' are Euclidean-invariant % constraints on the eigenvalues of A, % meaning the fit will be invariant % under Euclidean transformations % 'bookstein': lambda1^2 + lambda2^2 = 1 % 'trace' : lambda1 + lambda2 = 1 % % Nonlinear Fit Property Values % =============================== % 'maxits' positive integer, default 200 % Maximum number of iterations for the % Gauss Newton step % % 'tol' positive real, default 1e-5 % Relative step size tolerance % Example: % % A set of points % x = [1 2 5 7 9 6 3 8; % 7 6 8 7 5 7 2 4]; % % % Fit an ellipse using the Bookstein constraint % [zb, ab, bb, alphab] = fitellipse(x, 'linear'); % % % Find the least squares geometric estimate % [zg, ag, bg, alphag] = fitellipse(x); % % % Plot the results % plot(x(1,:), x(2,:), 'ro') % hold on % % plotellipse(zb, ab, bb, alphab, 'b--') % % plotellipse(zg, ag, bg, alphag, 'k') % % See also PLOTELLIPSE % Copyright Richard Brown, this code can be freely used and modified so % long as this line is retained error(nargchk(1, 5, nargin, 'struct')) % Default parameters params.fNonlinear = true; params.constraint = 'bookstein'; params.maxits = 200; params.tol = 1e-5; % Parse inputs [x, params] = parseinputs(x, params, varargin{:}); % Constraints are Euclidean-invariant, so improve conditioning by removing % centroid centroid = mean(x, 2); x = x - repmat(centroid, 1, size(x, 2)); % Obtain a linear estimate switch params.constraint % Bookstein constraint : lambda_1^2 + lambda_2^2 = 1 case 'bookstein' [z, a, b, alpha] = fitbookstein(x); % 'trace' constraint, lambda1 + lambda2 = trace(A) = 1 case 'trace' [z, a, b, alpha] = fitggk(x); end % switch % Minimise geometric error using nonlinear least squares if required if params.fNonlinear % Initial conditions z0 = z; a0 = a; b0 = b; alpha0 = alpha; % Apply the fit [z, a, b, alpha, fConverged] = ... fitnonlinear(x, z0, a0, b0, alpha0, params); % Return linear estimate if GN doesn't converge if ~fConverged warning('fitellipse:FailureToConverge', ...' 'Gauss-Newton did not converge, returning linear estimate'); z = z0; a = a0; b = b0; alpha = alpha0; end end % Add the centroid back on z = z + centroid; end % fitellipse % ----END MAIN FUNCTION-----------% function [z, a, b, alpha] = fitbookstein(x) %FITBOOKSTEIN Linear ellipse fit using bookstein constraint % lambda_1^2 + lambda_2^2 = 1, where lambda_i are the eigenvalues of A % Convenience variables m = size(x, 2); x1 = x(1, :)'; x2 = x(2, :)'; % Define the coefficient matrix B, such that we solve the system % B *[v; w] = 0, with the constraint norm(w) == 1 B = [x1, x2, ones(m, 1), x1.^2, sqrt(2) * x1 .* x2, x2.^2]; % To enforce the constraint, we need to take the QR decomposition [Q, R] = qr(B); % Decompose R into blocks R11 = R(1:3, 1:3); R12 = R(1:3, 4:6); R22 = R(4:6, 4:6); % Solve R22 * w = 0 subject to norm(w) == 1 [U, S, V] = svd(R22); w = V(:, 3); % Solve for the remaining variables v = -R11 \ R12 * w; % Fill in the quadratic form A = zeros(2); A(1) = w(1); A([2 3]) = 1 / sqrt(2) * w(2); A(4) = w(3); bv = v(1:2); c = v(3); % Find the parameters [z, a, b, alpha] = conic2parametric(A, bv, c); end % fitellipse function [z, a, b, alpha] = fitggk(x) % Linear least squares with the Euclidean-invariant constraint Trace(A) = 1 % Convenience variables m = size(x, 2); x1 = x(1, :)'; x2 = x(2, :)'; % Coefficient matrix B = [2 * x1 .* x2, x2.^2 - x1.^2, x1, x2, ones(m, 1)]; v = B \ -x1.^2; % For clarity, fill in the quadratic form variables A = zeros(2); A(1,1) = 1 - v(2); A([2 3]) = v(1); A(2,2) = v(2); bv = v(3:4); c = v(5); % find parameters [z, a, b, alpha] = conic2parametric(A, bv, c); end function [z, a, b, alpha, fConverged] = fitnonlinear(x, z0, a0, b0, alpha0, params) % Gauss-Newton least squares ellipse fit minimising geometric distance % Get initial rotation matrix Q0 = [cos(alpha0), -sin(alpha0); sin(alpha0) cos(alpha0)]; m = size(x, 2); % Get initial phase estimates phi0 = angle( [1 i] * Q0' * (x - repmat(z0, 1, m)) )'; u = [phi0; alpha0; a0; b0; z0]; % Iterate using Gauss Newton fConverged = false; for nIts = 1:params.maxits % Find the function and Jacobian [f, J] = sys(u); % Solve for the step and update u h = -J \ f; u = u + h; % Check for convergence delta = norm(h, inf) / norm(u, inf); if delta < params.tol fConverged = true; break end end alpha = u(end-4); a = u(end-3); b = u(end-2); z = u(end-1:end); function [f, J] = sys(u) % SYS : Define the system of nonlinear equations and Jacobian. Nested % function accesses X (but changeth it not) % from the FITELLIPSE workspace % Tolerance for whether it is a circle circTol = 1e-5; % Unpack parameters from u phi = u(1:end-5); alpha = u(end-4); a = u(end-3); b = u(end-2); z = u(end-1:end); % If it is a circle, the Jacobian will be singular, and the % Gauss-Newton step won't work. %TODO: This can be fixed by switching to a Levenberg-Marquardt %solver if abs(a - b) / (a + b) < circTol warning('fitellipse:CircleFound', ... 'Ellipse is near-circular - nonlinear fit may not succeed') end % Convenience trig variables c = cos(phi); s = sin(phi); ca = cos(alpha); sa = sin(alpha); % Rotation matrices Q = [ca, -sa; sa, ca]; Qdot = [-sa, -ca; ca, -sa]; % Preallocate function and Jacobian variables f = zeros(2 * m, 1); J = zeros(2 * m, m + 5); for i = 1:m rows = (2*i-1):(2*i); % Equation system - vector difference between point on ellipse % and data point f((2*i-1):(2*i)) = x(:, i) - z - Q * [a * cos(phi(i)); b * sin(phi(i))]; % Jacobian J(rows, i) = -Q * [-a * s(i); b * c(i)]; J(rows, (end-4:end)) = ... [-Qdot*[a*c(i); b*s(i)], -Q*[c(i); 0], -Q*[0; s(i)], [-1 0; 0 -1]]; end end end % fitnonlinear function [z, a, b, alpha] = conic2parametric(A, bv, c) % Diagonalise A - find Q, D such at A = Q' * D * Q [Q, D] = eig(A); Q = Q'; % If the determinant < 0, it's not an ellipse if prod(diag(D)) <= 0 error('fitellipse:NotEllipse', 'Linear fit did not produce an ellipse'); end % We have b_h' = 2 * t' * A + b' t = -0.5 * (A \ bv); c_h = t' * A * t + bv' * t + c; z = t; a = sqrt(-c_h / D(1,1)); b = sqrt(-c_h / D(2,2)); alpha = atan2(Q(1,2), Q(1,1)); end % conic2parametric function [x, params] = parseinputs(x, params, varargin) % PARSEINPUTS put x in the correct form, and parse user parameters % CHECK x % Make sure x is 2xN where N > 3 if size(x, 2) == 2 x = x'; end if size(x, 1) ~= 2 error('fitellipse:InvalidDimension', ... 'Input matrix must be two dimensional') end if size(x, 2) < 6 error('fitellipse:InsufficientPoints', ... 'At least 6 points required to compute fit') end % Determine whether we are solving for geometric (nonlinear) or algebraic % (linear) distance if ~isempty(varargin) && strncmpi(varargin{1}, 'linear', length(varargin{1})) params.fNonlinear = false; varargin(1) = []; else params.fNonlinear = true; end % Parse property/value pairs if rem(length(varargin), 2) ~= 0 error('fitellipse:InvalidInputArguments', ... 'Additional arguments must take the form of Property/Value pairs') end % Cell array of valid property names properties = {'constraint', 'maxits', 'tol'}; while length(varargin) ~= 0 % Pop pair off varargin property = varargin{1}; value = varargin{2}; varargin(1:2) = []; % If the property has been supplied in a shortened form, lengthen it iProperty = find(strncmpi(property, properties, length(property))); if isempty(iProperty) error('fitellipse:UnknownProperty', 'Unknown Property'); elseif length(iProperty) > 1 error('fitellipse:AmbiguousProperty', ... 'Supplied shortened property name is ambiguous'); end % Expand property to its full name property = properties{iProperty}; % Check for irrelevant property if ~params.fNonlinear && ismember(property, {'maxits', 'tol'}) warning('fitellipse:IrrelevantProperty', ... 'Supplied property has no effect on linear estimate, ignoring'); continue end % Check supplied property value switch property case 'maxits' if ~isnumeric(value) || value <= 0 error('fitcircle:InvalidMaxits', ... 'maxits must be an integer greater than 0') end params.maxits = value; case 'tol' if ~isnumeric(value) || value <= 0 error('fitcircle:InvalidTol', ... 'tol must be a positive real number') end params.tol = value; case 'constraint' switch lower(value) case 'bookstein' params.constraint = 'bookstein'; case 'trace' params.constraint = 'trace'; otherwise error('fitellipse:InvalidConstraint', ... 'Invalid constraint specified') end end % switch property end % while end % parseinputs
github
seisgo/EllipseFit-master
funcEllipseFit_nlinfit.m
.m
EllipseFit-master/matlab/funcEllipseFit_nlinfit.m
639
utf_8
634fb60894d1e5bdc3cd6eacd6c48943
% Ellipse Fitting using nlinfit function and adopting conic section as % nonlinear regression model function. % This function can be extended to other conic section fitting, like % circle, parabola and hyperbola. function [modelF,fitCoef]=funcEllipseFit_nlinfit(inMtrx) % Ellipse Function modelF=@(fitCoef,inMtrx)fitCoef(1)*inMtrx(:,1).^2 ..., +fitCoef(2)*inMtrx(:,1).*inMtrx(:,2) ..., +fitCoef(3)*inMtrx(:,2).^2 ..., +fitCoef(4)*inMtrx(:,1) ..., +fitCoef(5)*inMtrx(:,2) ..., +fitCoef(6); % Initial Coefficients coef=[1 1 1 1 1 1]; % Do Nonlinear Regression fitCoef=nlinfit(inMtrx,zeros(size(inMtrx,1),1),modelF,coef);
github
steventhornton/Newton-Fractal-master
int2rgb.m
.m
Newton-Fractal-master/src/int2rgb.m
2,257
utf_8
9e22059a3b65e4dc93a94404eac4f2fd
% ----------------------------------------------------------------------- % % AUTHOR .... Steven E. Thornton (Copyright (c) 2016) % % EMAIL ..... [email protected] % % UPDATED ... Sept. 8/2016 % % % % Apply a colormap to integer values by taking the integer values mod the % % number of colors and applying the appropriate color from the colormap % % % % INPUT % % img .... 2-dimensional array of integer values % % cmap ... m x 3 array where each row represents rgb values (in [0,1]) % % % % LICENSE % % This program is free software: you can redistribute it and/or modify % % it under the terms of the GNU General Public License as published by % % the Free Software Foundation, either version 3 of the License, or % % any later version. % % % % This program is distributed in the hope that it will be useful, % % but WITHOUT ANY WARRANTY; without even the implied warranty of % % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % % GNU General Public License for more details. % % % % You should have received a copy of the GNU General Public License % % along with this program. If not, see http://www.gnu.org/licenses/. % % ----------------------------------------------------------------------- % function rgb = int2rgb(img, cmap) [n,m] = size(img); % Convert to a vector s = img(:); % Reduce to the number of colors s = mod(s, size(cmap, 1)) + 1; % Get the colors rgb = cmap(s,:); rgb = reshape(rgb, [n, m, 3]); end
github
steventhornton/Newton-Fractal-master
iteration.m
.m
Newton-Fractal-master/src/iteration.m
4,046
utf_8
492f16e63e4dec5240a65553b6e34de5
% ----------------------------------------------------------------------- % % AUTHOR .... Steven E. Thornton (Copyright (c) 2016) % % EMAIL ..... [email protected] % % UPDATED ... Sept. 7/2016 % % % % Compute Newton's method on a grid of points. % % % % INPUT % % f .............. A function handle that takes a row vector as input % % and returns a matrix with the same number of columns % % as the number of elements in the input vector. The % % rows of the matrix represent the value of the % % function and subsequent derivatives. % % method .... A function handle that takes 3 values as input: % % f ... A function handle for evaluating a function and % % its derivatives % % x ... A vector of points to evaluate f at % % r ... Relaxation paramater % % options ... A struct of options. % % % % LICENSE % % This program is free software: you can redistribute it and/or modify % % it under the terms of the GNU General Public License as published by % % the Free Software Foundation, either version 3 of the License, or % % any later version. % % % % This program is distributed in the hope that it will be useful, % % but WITHOUT ANY WARRANTY; without even the implied warranty of % % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % % GNU General Public License for more details. % % % % You should have received a copy of the GNU General Public License % % along with this program. If not, see http://www.gnu.org/licenses/. % % ----------------------------------------------------------------------- % function s = iteration(f, method, options) % Get the options r = options.r; resolution = options.resolution; margin = options.margin; maxIter = options.maxIter; tol = options.tol; smoothing = options.smoothing; % Set up the complex grid grid = makeMesh(margin, resolution); % Convert to a row vector grid = grid(:)'; % Boolearn matrix, all false (same size as grid) inTol = false(size(grid)); % Vector that will be plotted (smooth count) s = zeros(size(grid)); k = 0; % Continue looping until either maximum number of iterations is reached % or all grid points have been computed to within the tolerance. while k < maxIter && ~all(inTol(:)) k = k + 1; % Get the values from the grid where the solution has not been % computed to within the tolerance yet gridCompute = grid(~inTol); % Evaluate the iteration method gNew = method(f, gridCompute, r); grid(~inTol) = gNew; t = gNew - gridCompute; if smoothing s(~inTol) = s(~inTol) + exp(-1./abs(t)); else s(~inTol) = s(~inTol) + 1; end % Update inTol vector fg = f(grid); inTol(abs(fg(1,:)) < tol) = true; end % Reshape back to a matrix s = reshape(s, [resolution.height, resolution.width]); end
github
steventhornton/Newton-Fractal-master
newtonFractal.m
.m
Newton-Fractal-master/src/newtonFractal.m
5,645
utf_8
ee449dd78b9840fb3a5c6513cbf226c2
% ----------------------------------------------------------------------- % % AUTHOR .... Steven E. Thornton (Copyright (c) 2016) % % EMAIL ..... [email protected] % % UPDATED ... Sept. 7/2016 % % % % INPUT % % f .............. Either a function handle or a symbolic expression. % % Function handle: Must take a row vector as input % % and returns a matrix with 2 % % rows and the same number of % % columns as the number of % % elements in the input row % % vector. The first row % % represents the value of the % % function evaluated at the input % % points, and the second row is % % the first derivative of the % % function evaluated at the input % % points. % % Symbolic expression: A symbolic expression in % % one variable. % % workingDirIn ... The directory to save output images. % % options ........ A struct containing the options % % % % OPTIONS % % Options should be a struct with the keys below % % margin ...... Default: (-1-1i, 1+i) % % Struct with keys: % % left ..... Left margin % % right .... Right margin % % bottom ... Bottom margin % % top ...... Top margin % % maxIter ..... Default: 50 % % Maximum number of iterations. % % tol ......... Default: 1e-6 % % Tolerance used for determining if an iteration has % % converged. % % height ...... Default: 250 (pixels) % % Height in pixels for the ouput image. The width is % % computed automatically based on the margin such that % % all pixels are squares. % % smoothing ... Default: false % % When true, exponential smoothing is used to provide a % % smooth transition in the colors between different % % number of iterations to convergence. % % r ........... Default: 1 % % A parameter used in the iterations: % % x_n+1 = x_n - r*f(x_n)/f'(x_n) % % cmap ........ Default: Matlab's hsv colormap % % % % LICENSE % % This program is free software: you can redistribute it and/or modify % % it under the terms of the GNU General Public License as published by % % the Free Software Foundation, either version 3 of the License, or % % any later version. % % % % This program is distributed in the hope that it will be useful, % % but WITHOUT ANY WARRANTY; without even the implied warranty of % % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % % GNU General Public License for more details. % % % % You should have received a copy of the GNU General Public License % % along with this program. If not, see http://www.gnu.org/licenses/. % % ----------------------------------------------------------------------- % function newtonFractal(f, workingDirIn, options) % Check the number of arguments narginchk(2, 3) if nargin < 3 options = struct(); end % Check/convert the input function if isa(f, 'function_handle') g = f; elseif isa(f, 'sym') % Convert symbolic expression to function handle with derivative h = matlabFunction(f); dh = matlabFunction(diff(f)); g = @(x) [ h(x); dh(x)]; else error('Input function must be a function handle or symbolic expression'); end % Function handle for Newton's method method = @(f, x, r) newtonsMethod(f, x, r); % Make the fractal makeFractal(g, method, workingDirIn, options); end
github
steventhornton/Newton-Fractal-master
halleyFractal.m
.m
Newton-Fractal-master/src/halleyFractal.m
6,042
utf_8
20638b73c41f44527c542e99dae833bd
% ----------------------------------------------------------------------- % % AUTHOR .... Steven E. Thornton (Copyright (c) 2016) % % EMAIL ..... [email protected] % % UPDATED ... Sept. 7/2016 % % % % INPUT % % f .............. Either a function handle or a symbolic expression. % % Function handle: Must take a row vector as input % % and returns a matrix with 3 % % rows and the same number of % % columns as the number of % % elements in the input row % % vector. The first row % % represents the value of the % % function evaluated at the input % % points, the second row is the % % first derivative of the % % function evaluated at the input % % points, and the third row is % % the second derivative of the % % function evaluated at the input % % points. % % Symbolic expression: A symbolic expression in % % one variable. % % workingDirIn ... The directory to save output images. % % options ........ A struct containing the options % % % % OPTIONS % % Options should be a struct with the keys below % % margin ...... Default: (-1-1i, 1+i) % % Struct with keys: % % left ..... Left margin % % right .... Right margin % % bottom ... Bottom margin % % top ...... Top margin % % maxIter ..... Default: 50 % % Maximum number of iterations. % % tol ......... Default: 1e-6 % % Tolerance used for determining if an iteration has % % converged. % % height ...... Default: 250 (pixels) % % Height in pixels for the ouput image. The width is % % computed automatically based on the margin such that % % all pixels are squares. % % smoothing ... Default: false % % When true, exponential smoothing is used to provide a % % smooth transition in the colors between different % % number of iterations to convergence. % % r ........... Default: 1 % % A parameter used in the iterations: % % x_n+1 = x_n - r*2*f(x_n)*f'(x_n)/(2*f'(x_n)^2 - % % f(x_n)f''(x_n)) % % cmap ........ Default: Matlab's hsv colormap % % % % LICENSE % % This program is free software: you can redistribute it and/or modify % % it under the terms of the GNU General Public License as published by % % the Free Software Foundation, either version 3 of the License, or % % any later version. % % % % This program is distributed in the hope that it will be useful, % % but WITHOUT ANY WARRANTY; without even the implied warranty of % % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % % GNU General Public License for more details. % % % % You should have received a copy of the GNU General Public License % % along with this program. If not, see http://www.gnu.org/licenses/. % % ----------------------------------------------------------------------- % function halleyFractal(f, workingDirIn, options) % Check the number of arguments narginchk(2, 3) if nargin < 3 options = struct(); end % Check/convert the input function if isa(f, 'function_handle') g = f; elseif isa(f, 'sym') % Convert symbolic expression to function handle with derivative h = matlabFunction(f); dh = matlabFunction(diff(f)); ddh = matlabFunction(diff(f,2)); g = @(x) [ h(x); dh(x); ddh(x)]; else error('Input function must be a function handle or symbolic expression'); end % Function handle for Halley's method method = @(f, x, r) halleysMethod(f, x, r); % Make the fractal makeFractal(g, method, workingDirIn, options); end
github
steventhornton/Newton-Fractal-master
makeMesh.m
.m
Newton-Fractal-master/src/makeMesh.m
3,029
utf_8
f1c98219c37f7ac66e320201aaa063fb
% ----------------------------------------------------------------------- % % AUTHOR .... Steven E. Thornton (Copyright (c) 2016) % % EMAIL ..... [email protected] % % UPDATED ... Sept. 6/2016 % % % % Create a matrix where the entries are complex values such that the % % entire matrix represents a grid in the complex plane. % % % % INPUT % % margin ....... Struct with keys: % % left ..... Left margin % % right .... Right margin % % bottom ... Bottom margin % % top ...... Top margin % % resolution ... Struct with keys: % % width .... number of columns in grid % % height ... number of rows in grid % % % % OUTPUT % % A 2D complex matrix of grid points in the complex plane % % % % LICENSE % % This program is free software: you can redistribute it and/or modify % % it under the terms of the GNU General Public License as published by % % the Free Software Foundation, either version 3 of the License, or % % any later version. % % % % This program is distributed in the hope that it will be useful, % % but WITHOUT ANY WARRANTY; without even the implied warranty of % % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % % GNU General Public License for more details. % % % % You should have received a copy of the GNU General Public License % % along with this program. If not, see http://www.gnu.org/licenses/. % % ----------------------------------------------------------------------- % function grid = makeMesh(margin, resolution) reMin = margin.left; reMax = margin.right; imMin = margin.bottom; imMax = margin.top; width = resolution.width; height = resolution.height; x = linspace(reMin, reMax, width); y = linspace(imMin, imMax, height); [x, y] = meshgrid(x, y); grid = x + 1i * y; end
github
steventhornton/Newton-Fractal-master
makeFractal.m
.m
Newton-Fractal-master/src/makeFractal.m
11,534
utf_8
54266b6d79424ced869e294678607c3c
% ----------------------------------------------------------------------- % % AUTHOR .... Steven E. Thornton (Copyright (c) 2016) % % EMAIL ..... [email protected] % % UPDATED ... Sept. 7/2016 % % % % Create a Newton or Halley fractal in the complex plane. % % % % INPUT % % f .............. A function handle that takes a row vector as input % % and returns a matrix with the same number of columns % % as the number of elements in the input vector. The % % rows of the matrix represent the value of the % % function and subsequent derivatives. % % method ......... A function handle that takes 3 values as input: % % f ... A function handle for evaluating a % % function and it's derivatives % % x ... A vector of points to evaluate f at % % r ... Relaxation paramater % % workingDirIn ... The directory to save output images. % % options ........ A struct containing the options % % % % OPTIONS % % Options should be a struct with the keys below % % margin ...... Default: (-1-1i, 1+i) % % Struct with keys: % % left ..... Left margin % % right .... Right margin % % bottom ... Bottom margin % % top ...... Top margin % % maxIter ..... Default: 50 % % Maximum number of iterations. % % tol ......... Default: 1e-6 % % Tolerance used for determining if an iteration has % % converged. % % height ...... Default: 250 (pixels) % % Height in pixels for the ouput image. The width is % % computed automatically based on the margin such that % % all pixels are squares. % % smoothing ... Default: false % % When true, exponential smoothing is used to provide a % % smooth transition in the colors between different % % number of iterations to convergence. % % r ........... Default: 1 % % A parameter used in the iterations: % % x_n+1 = x_n - r*method % % where method is dependent on the method used (f/df for % % Newtons' method). % % cmap ........ Default: Matlab's hsv colormap % % % % LICENSE % % This program is free software: you can redistribute it and/or modify % % it under the terms of the GNU General Public License as published by % % the Free Software Foundation, either version 3 of the License, or % % any later version. % % % % This program is distributed in the hope that it will be useful, % % but WITHOUT ANY WARRANTY; without even the implied warranty of % % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % % GNU General Public License for more details. % % % % You should have received a copy of the GNU General Public License % % along with this program. If not, see http://www.gnu.org/licenses/. % % ----------------------------------------------------------------------- % function makeFractal(f, method, workingDirIn, options) % Make working directory if it doesn't exit if workingDirIn(end) == filesep workingDir = workingDirIn; else workingDir = [workingDirIn, filesep]; end mkdir_if_not_exist(workingDir); % Process the options opts = processOptions(options); margin = opts.margin; maxIter = opts.maxIter; tol = opts.tol; height = opts.height; smoothing = opts.smoothing; r = opts.r; cmap = opts.cmap; % Get resolution resolution = getResolution(); opts.resolution = resolution; % Output filename outputFilename = makeOutputFilename(); % Make the fratal runIteration() % Write readme file writeReadMe(); % ===================================================================== % FUNCTIONS % ===================================================================== % --------------------------------------------------------------------- function runIteration() s = iteration(f, method, opts); if smoothing rgb = double2rgb(s, cmap); else rgb = int2rgb(s, cmap); end % Write the image to a file imwrite(rgb, [workingDir, outputFilename]); fprintf(['Image written to: ', outputFilename, '\n']); end % ------------------------------------------------------------------- % % getResolution % % % % Compute the resolution struct based on the height and margins. % % % % OUTPUT % % A struct resolution = {'width', w, 'height', h} % % ------------------------------------------------------------------- % function resolution = getResolution() % Check the margins and make the resolution structure if margin.bottom >= margin.top error 'Bottom margin must be less than top margin'; end if margin.left >= margin.right error 'Left margin must be less than top margin'; end width = getWidth(); resolution = struct('width', width, 'height', height); end % ------------------------------------------------------------------- % % getWidth % % % % Compute the width (in px) based on the height and the margins such % % that each grid point is a square % % % % OUTPUT % % A struct resolution = {'width', w, 'height', h} % % ------------------------------------------------------------------- % function width = getWidth() heightI = margin.top - margin.bottom; widthI = margin.right - margin.left; width = floor(widthI*height/heightI); end % ------------------------------------------------------------------- % % outputFilename % % % % Determine the name of the output file. % % % % OUTPUT % % A string of the form % % Image-(i) where i is a positive integer. % % ------------------------------------------------------------------- % function outputFilename = makeOutputFilename() outPrefix = 'Image-'; if exist([workingDir, outPrefix, '1.png']) == 2 i = 2; while exist([workingDir, outPrefix , num2str(i), '.png']) == 2 i = i + 1; end outputFilename = [outPrefix, num2str(i), '.png']; else outputFilename = [outPrefix, '1.png']; end end % ------------------------------------------------------------------- % % writeReadMe % % % % Write a readme file in the workingDir with information about % % when the data was created, what was used to create the data, etc. % % ------------------------------------------------------------------- % function writeReadMe() file = fopen([workingDir, 'README.txt'], 'a'); fprintf(file, [outputFilename, '\n']); % Date fprintf(file, ['\tCreated ...... ', datestr(now,'mmmm dd/yyyy HH:MM:SS AM'), '\n']); % Function fprintf(file, ['\tFunction ..... ', func2str(f), '\n']); % Method %fprintf(file, ['\tmethod ....... ', method, '\n']); % Margin fprintf(file, ['\tmargin ....... bottom: ', num2str(margin.bottom), '\n']); fprintf(file, ['\t top: ', num2str(margin.top), '\n']); fprintf(file, ['\t left: ', num2str(margin.left), '\n']); fprintf(file, ['\t right: ', num2str(margin.right), '\n']); % Resolution fprintf(file, ['\tresolution ... ', num2str(resolution.width), 'x', num2str(resolution.height), '\n']); % maxIter fprintf(file, ['\tmaxIter ...... ', num2str(maxIter), '\n']); % tol fprintf(file, ['\ttol .......... ', num2str(tol), '\n']); % smoothing if smoothing fprintf(file, '\tsmoothing .... true\n'); else fprintf(file, '\tsmoothing .... false\n'); end % r fprintf(file, ['\tr ............ ', num2str(r), '\n']); % cmap fprintf(file, [' cmap .............. ', ... num2str(cmap(1,1)), ', ', ... num2str(cmap(1,2)), ', ', ... num2str(cmap(1,3)), '\n']); for i=2:size(cmap, 1) fprintf(file, [' ', ... num2str(cmap(i,1)), ', ', ... num2str(cmap(i,2)), ', ', ... num2str(cmap(i,3)), '\n']); end fprintf(file, '\n\n\n'); fclose(file); end end
github
steventhornton/Newton-Fractal-master
double2rgb.m
.m
Newton-Fractal-master/src/double2rgb.m
3,569
utf_8
75aba98dfb19353cb6cf384524f0853b
% ----------------------------------------------------------------------- % % AUTHOR .... Steven E. Thornton (Copyright (c) 2016) % % EMAIL ..... [email protected] % % UPDATED ... Oct. 25/2016 % % % % Apply a colormap to floating point values by interpolating between % % points in the colormap. % % % % INPUT % % img .... 2-dimensional array of floating point values % % cmap ... m x 3 array where each row represents rgb values (in [0,1]) % % % % LICENSE % % This program is free software: you can redistribute it and/or modify % % it under the terms of the GNU General Public License as published by % % the Free Software Foundation, either version 3 of the License, or % % any later version. % % % % This program is distributed in the hope that it will be useful, % % but WITHOUT ANY WARRANTY; without even the implied warranty of % % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % % GNU General Public License for more details. % % % % You should have received a copy of the GNU General Public License % % along with this program. If not, see http://www.gnu.org/licenses/. % % ----------------------------------------------------------------------- % function rgb = double2rgb(img, cmap) % Background color bg = [0,0,0]; [n,m] = size(img); % Convert to a vector s = img(:); rVal = zeros(size(s)); gVal = zeros(size(s)); bVal = zeros(size(s)); % Only the valid points valid = isfinite(s); minVal = min(s(valid)); maxVal = max(s(valid)); % Fill in the non-valid points rVal(~valid) = bg(1); gVal(~valid) = bg(2); bVal(~valid) = bg(3); % Scale to a number between 0 and 1 s(valid) = (s(valid) - minVal)/(maxVal - minVal); % Scale to a number between 1 and size(cmap) s(valid) = s(valid)*(size(cmap, 1) - 1) + 1; tZero = valid & ((s - floor(s)) == 0); tNotZero = valid & ((s - floor(s)) ~= 0); tFrac = s - floor(s); idx1 = floor(s); % When tFrac == 0 rVal(tZero) = cmap(idx1(tZero), 1); gVal(tZero) = cmap(idx1(tZero), 2); bVal(tZero) = cmap(idx1(tZero), 3); % When tFrac ~= 0 rVal1 = cmap(idx1(tNotZero), 1); gVal1 = cmap(idx1(tNotZero), 2); bVal1 = cmap(idx1(tNotZero), 3); rVal2 = cmap(idx1(tNotZero) + 1, 1); gVal2 = cmap(idx1(tNotZero) + 1, 2); bVal2 = cmap(idx1(tNotZero) + 1, 3); rVal(tNotZero) = (rVal2 - rVal1).*tFrac(tNotZero) + rVal1; gVal(tNotZero) = (gVal2 - gVal1).*tFrac(tNotZero) + gVal1; bVal(tNotZero) = (bVal2 - bVal1).*tFrac(tNotZero) + bVal1; rVal = reshape(rVal, [n, m]); gVal = reshape(gVal, [n, m]); bVal = reshape(bVal, [n, m]); rgb = cat(3, rVal, gVal, bVal); end
github
steventhornton/Newton-Fractal-master
processOptions.m
.m
Newton-Fractal-master/src/processOptions.m
5,969
utf_8
ebb6ff0e936e57b2a3db455cd095d5d2
% ----------------------------------------------------------------------- % % AUTHOR .... Steven E. Thornton (Copyright (c) 2016) % % EMAIL ..... [email protected] % % UPDATED ... Sept. 6/2016 % % % % Process the options input options struct. If an option is not in the % % options struct the default value is used. % % % % INPUT % % options ... (struct) contains keys corresponding to the options % % % % OUTPUT % % A struct opts with keys % % margin ...... struct(left, right, bottom, top), double % % maxIter ..... posint % % tol ......... positive double (<1) % % height ...... posint % % smoothing ... bool % % r ........... double % % cmap ........ m x 3 array of doubles in [0,1] % % % % LICENSE % % This program is free software: you can redistribute it and/or modify % % it under the terms of the GNU General Public License as published by % % the Free Software Foundation, either version 3 of the License, or % % any later version. % % % % This program is distributed in the hope that it will be useful, % % but WITHOUT ANY WARRANTY; without even the implied warranty of % % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % % GNU General Public License for more details. % % % % You should have received a copy of the GNU General Public License % % along with this program. If not, see http://www.gnu.org/licenses/. % % ----------------------------------------------------------------------- % function opts = processOptions(options) % Check the number of input arguments if nargin ~= 1 error('processOptions:WrongNumberofArgs', ... 'processOptions expects one argument.'); end % Check that options is a struct if ~isstruct(options) error('processOptions:InvalidOptionsStruct', ... 'options argument must be a structured array'); end optNames = struct('margin', 'margin', ... 'maxIter', 'maxIter', ... 'tol', 'tol', ... 'height', 'height', ... 'smoothing', 'smoothing', ... 'r', 'r', ... 'cmap', 'cmap'); fnames = fieldnames(options); if ~all(ismember(fnames, fieldnames(optNames))) error('processOptions:InvalidOption', ... 'Invalid option provided'); end opts = struct(); % Default values opts.margin = struct('bottom', -1, ... 'top', 1, ... 'left', -1, ... 'right', 1); opts.maxIter = 50; opts.tol = 1e-6; opts.height = 250; opts.smoothing = false; opts.r = 1; opts.cmap = hsv; % margin --------------------------- if isfield(options, optNames.margin) opts.margin = options.margin; % TO DO: Add type checking (struct: left, right, bottom, top)) end % maxIter -------------------------- if isfield(options, optNames.maxIter) opts.maxIter = options.maxIter; % Check that maxIter is a positive integer if ~isposint(opts.maxIter) error('maxIter option must be a positive integer'); end end % tol --------------------------- if isfield(options, optNames.tol) opts.tol = options.tol; % Check that tol is in [0,1] if opts.tol < 0 || opts.tol > 1 error('tol option must be between 0 and 1'); end end % height --------------------------- if isfield(options, optNames.height) opts.height = options.height; if ~isposint(opts.height) error('height option must be a positive integer'); end end % smoothing --------------------------- if isfield(options, optNames.smoothing) opts.smoothing = options.smoothing; % TO DO: Add type checking (bool) end % r --------------------------- if isfield(options, optNames.r) opts.r = options.r; % TO DO: Add type checking (float) end % cmap ----------------------------- if isfield(options, optNames.cmap) opts.cmap = options.cmap; end % --------------------------------------------------------------------- % Type checking functions % --------------------------------------------------------------------- function b = isposint(x) b = logical(0); try b = logical((x > 0) & (~mod(x, 1))); end end end
github
steventhornton/Newton-Fractal-master
newtonsMethod.m
.m
Newton-Fractal-master/src/methods/newtonsMethod.m
2,528
utf_8
75fb2f00ad6efd1ae22fc5f06868030d
% ----------------------------------------------------------------------- % % AUTHOR .... Steven E. Thornton (Copyright (c) 2016) % % EMAIL ..... [email protected] % % UPDATED ... Sept. 7/2016 % % % % Compute Newton's method on a grid of points. % % xn = x - r*f(x)/f'(x) % % % % INPUT % % f ... A function handle that takes a row vector as input and returns % % a matrix with 2 rows and the same number of columns as the % % number of elements in the input row vector. The first row % % represents the value of the function evaluated at the input % % points, and the second row is the first derivative of the % % function evaluated at the input points. % % x ... Points to evaluate Newton's method at. % % r ... Relaxation parameter % % % % LICENSE % % This program is free software: you can redistribute it and/or modify % % it under the terms of the GNU General Public License as published by % % the Free Software Foundation, either version 3 of the License, or % % any later version. % % % % This program is distributed in the hope that it will be useful, % % but WITHOUT ANY WARRANTY; without even the implied warranty of % % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % % GNU General Public License for more details. % % % % You should have received a copy of the GNU General Public License % % along with this program. If not, see http://www.gnu.org/licenses/. % % ----------------------------------------------------------------------- % function xn = newtonsMethod(f, x, r) g = f(x); t = g(1,:)./g(2,:); xn = x - r*t; end
github
steventhornton/Newton-Fractal-master
halleysMethod.m
.m
Newton-Fractal-master/src/methods/halleysMethod.m
2,638
utf_8
2bc7c532b5459cd6ee000921beaece95
% ----------------------------------------------------------------------- % % AUTHOR .... Steven E. Thornton (Copyright (c) 2016) % % EMAIL ..... [email protected] % % UPDATED ... Sept. 7/2016 % % % % Compute Halley's method on a grid of points. % % xn = x - r*2*f(x)*f'(x)/(2*f'(x)^2 - f(x)*f''(x)) % % % % INPUT % % f ... A function handle that takes a row vector as input and returns % % a matrix with 3 rows and the same number of columns as the % % number of elements in the input row vector. The first row % % represents the value of the function evaluated at the input % % points, the second row is the first derivative of the function % % evaluated at the input points, and the third row is the second % % derivative of the function evaluated at the input points. % % x ... Points to evaluate Newton's method at. % % r ... Relaxation parameter % % % % LICENSE % % This program is free software: you can redistribute it and/or modify % % it under the terms of the GNU General Public License as published by % % the Free Software Foundation, either version 3 of the License, or % % any later version. % % % % This program is distributed in the hope that it will be useful, % % but WITHOUT ANY WARRANTY; without even the implied warranty of % % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % % GNU General Public License for more details. % % % % You should have received a copy of the GNU General Public License % % along with this program. If not, see http://www.gnu.org/licenses/. % % ----------------------------------------------------------------------- % function xn = halleysMethod(f, x, r) g = f(x); t = 2*g(1,:).*g(2,:)./(2*g(2,:).^2 - g(1,:).*g(3,:)); xn = x - r*t; end
github
DevLibraries/SmallLibraries-master
analyze_leafsize_stats.m
.m
SmallLibraries-master/Permissive/nanoflann/perf-tests/analyze_leafsize_stats.m
1,502
utf_8
5bcc7168b358ccc2a7e4345373d29a85
function [] = analyze_leafsize_stats() % Compute the stats from the result files of performance tests wrt % the max. leaf size close all; %D=load('LEAF_STATS.txt'); %D=load('LEAF_STATS_DOUBLE.txt'); D=load('LEAF_STATS_DATASET.txt'); MAXs = unique(D(:,2)); COLs = {'k','b','r','g'}; % Cell array of colros. figure(1); for i=1:length(MAXs), MaxLeaf = MAXs(i); idxs = find(D(:,2)==MaxLeaf); TBs = D(idxs,3); % Time of tree Builds TQs = D(idxs,4); % Time of tree Queries TBm = 1e3*mean(TBs); TQm = 1e6*mean(TQs); TBstd = 1e3*std(TBs); TQstd = 1e6*std(TQs); TBms(i)=TBm; TQms(i)=TQm; % Plot a 95% ellipse: my_plot_ellipse([TBm TQm],2*[TBstd TQstd], COLs{ 1+mod(i-1,length(COLs))} ); %plot(1e3*TBs,1e6*TQs,'.','color',COLs{ 1+mod(i-1,length(COLs))}); text(TBm,TQm+6*TQstd,sprintf('%i',MaxLeaf)); end plot(TBms,TQms,'color',[0.4 0.4 0.4],'LineWidth',2.5); set(gca,'YScale','log'); ylabel('Tree query time (us)'); xlabel('Tree build time (ms)'); title(sprintf('nanoflann performance vs. Leaf Max.Size (#points=%.01e)',D(1,1))); end function [] = my_plot_ellipse(Ms,STDs, COL ) angs=linspace(0,2*pi,200); xs= Ms(1) + cos(angs)*STDs(1); ys= Ms(2) + sin(angs)*STDs(2); h=plot(xs,ys,'color', COL,'LineWidth',2); hold on; end
github
DevLibraries/SmallLibraries-master
analyze_stats.m
.m
SmallLibraries-master/Permissive/nanoflann/perf-tests/analyze_stats.m
2,369
utf_8
b6d766f7cf55dee127cf6bb3085f2776
function [] = analyze_stats() % Compute the stats from the result files of flann & nanoflann performance tests % close all; [Nsf, Tf_M, Tf_STD] = analyze_file('stats_flann.txt'); [Nsnf, Tnf_M, Tnf_STD]= analyze_file('stats_nanoflann.txt'); titles={'Convert into Matrix<>', 'Build index', 'One 3D query'}; T_factors=[1e3, 1, 1e6]; t_titles={'Time (ms)','Time (s)','Time (\mu s)'}; for figs=1:3, figure(figs); % This is just to fix the legend: plot(0,0,'r'); hold on; plot(0,0,'b'); f = T_factors(figs); plotMeansAndStd( Nsf, f*Tf_M(:,figs), f*Tf_STD(:,figs), 'r', 2.0, 1, 10 ); plotMeansAndStd( Nsnf, f*Tnf_M(:,figs), f*Tnf_STD(:,figs), 'b', 2.0, 1, 10 ); set(gca,'XScale','Log') title(titles{figs}); xlabel('Size of point cloud'); ylabel(t_titles{figs}); legend('flann','nanoflann', 'Location', 'NorthWest'); end % Fig: time saved in building the index: figure(4); figs = 2; plotMeansAndStd( Nsf, 1e3*(Tf_M(:,1) + Tf_M(:,figs)-Tnf_M(:,figs)), 1e3*sqrt((Tf_STD(:,figs)+Tnf_STD(:,figs)).^2), 'k', 2.0, 1, 10 ); set(gca,'XScale','Log') title('Time saved in index building with nanoflann vs. flann (incl. the no matrix time)'); xlabel('Size of point cloud'); ylabel('Time (ms)'); end function [Ns, T_M, T_STD] = analyze_file(fil) D=load(fil); Ns = unique(D(:,1)); nCols = size(D,2)-1; for i=1:length(Ns), idxs = find(D(:,1)==Ns(i)); for j=1:nCols, T_M(i,j)=mean(D(idxs,j+1)); T_STD(i,j)=std(D(idxs,j+1)); end end end function [] = plotMeansAndStd( x, y_m, y_std, style, stdMult,doDrawMeanLine,smallSegmentSize) % ------------------------------------------------------------- % function [] = plotMeansAndStd( x, y_m, y_std, style, stdMult,doDrawMeanLine,smallSegmentSize) % % Plots a graph (x,y_m), plus the uncertainties "y_std" segments % % Jose Luis Blanco Claraco, 28-JUN-2006 % ------------------------------------------------------------- if (doDrawMeanLine), plot(x,y_m,style); end hold on; for i=1:length(x), y1 = y_m(i) - stdMult*y_std(i); y2 = y_m(i) + stdMult*y_std(i); plot([x(i)-smallSegmentSize x(i)+smallSegmentSize x(i) x(i) x(i)-smallSegmentSize x(i)+smallSegmentSize],[y1 y1 y1 y2 y2 y2],style); end end
github
hazirbas/light-field-toolbox-master
LFCalRectifyLF.m
.m
light-field-toolbox-master/LFToolbox0.4/LFCalRectifyLF.m
4,859
utf_8
58ca494191153d4b172d9f8d2408ca25
% LFCalRectifyLF - rectify a light field using a calibrated camera model, called as part of LFUtilDecodeLytroFolder % % Usage: % [LF, RectOptions] = LFCalRectifyLF( LF, CalInfo, RectOptions ) % [LF, RectOptions] = LFCalRectifyLF( LF, CalInfo ) % % This function is called by LFUtilDecodeLytroFolder to rectify a light field. It follows the % rectification procedure described in: % % D. G. Dansereau, O. Pizarro, and S. B. Williams, "Decoding, calibration and rectification for % lenslet-based plenoptic cameras," in Computer Vision and Pattern Recognition (CVPR), IEEE % Conference on. IEEE, Jun 2013. % % Minor differences from the paper: light field indices [i,j,k,l] are 1-based in this % implementation, and not 0-based as described in the paper. % % Note that a calibration should only be applied to a light field decoded using the same lenslet % grid model. This is because the lenslet grid model forms an implicit part of the calibration, % and changing it will invalidate the calibration. % % LFCalDispRectIntrinsics is useful for visualizing the sampling pattern associated with a requested % intrinsic matrix. % % Inputs: % % LF : The light field to rectify; should be floating point % % CalInfo struct contains a calibrated camera model, see LFUtilCalLensletCam: % .EstCamIntrinsicsH : 5x5 homogeneous matrix describing the lenslet camera intrinsics % .EstCamDistortionV : Estimated distortion parameters % % [optional] RectOptions struct (all fields are optional) : % .NInverse_Distortion_Iters : Number of iterations in inverse distortion estimation % .Precision : 'single' or 'double' % .RectCamIntrinsicsH : Requests a specific set of intrinsics for the rectified light % field. By default the rectified intrinsic matrix is % automatically constructed from the calibrated intrinsic % matrix, but this process can in some instances yield poor % results: excessive black space at the edges of the light field % sample space, or excessive loss of scene content off the edges % of the space. This parameters allows you to fine-tune the % desired rectified intrinsic matrix. % % Outputs : % % LF : The rectified light field % RectOptions : The rectification options as applied, including any default values employed. % % See also: LFCalDispRectIntrinsics, LFUtilCalLensletCam, LFUtilDecodeLytroFolder, LFUtilProcessWhiteImages % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [LF, RectOptions] = LFCalRectifyLF( LF, CalInfo, RectOptions ) %---Defaults--- RectOptions = LFDefaultField( 'RectOptions', 'Precision', 'single' ); RectOptions = LFDefaultField( 'RectOptions', 'NInverse_Distortion_Iters', 2 ); RectOptions = LFDefaultField( 'RectOptions', 'MaxUBlkSize', 32 ); LFSize = size(LF); RectOptions = LFDefaultField( 'RectOptions', 'RectCamIntrinsicsH', LFDefaultIntrinsics( LFSize, CalInfo ) ); %---Build interpolation indices--- fprintf('Generating interpolation indices...\n'); NChans = LFSize(5); LF = cast(LF, RectOptions.Precision); %---chop up the LF along u--- fprintf('Interpolating...'); UBlkSize = RectOptions.MaxUBlkSize; LFOut = LF; for( UStart = 1:UBlkSize:LFSize(4) ) UStop = UStart + UBlkSize - 1; UStop = min(UStop, LFSize(4)); t_in=cast(1:LFSize(1), 'uint16'); % saving some mem by using uint16 s_in=cast(1:LFSize(2), 'uint16'); v_in=cast(1:LFSize(3), 'uint16'); u_in=cast(UStart:UStop, 'uint16'); [tt,ss,vv,uu] = ndgrid(t_in,s_in,v_in,u_in); % InterpIdx initially holds the index of the desired ray, and is evolved through the application % of the inverse distortion model to eventually hold the continuous-domain index of the undistorted % ray, and passed to the interpolation step. InterpIdx = [ss(:)'; tt(:)'; uu(:)'; vv(:)'; ones(size(ss(:)'))]; DestSize = size(tt); clear tt ss vv uu InterpIdx = LFMapRectifiedToMeasured( InterpIdx, CalInfo, RectOptions ); for( ColChan = 1:NChans ) % todo[optimization]: use a weighted interpolation scheme to exploit the weight channel InterpSlice = interpn(squeeze(LF(:,:,:,:,ColChan)), InterpIdx(2,:),InterpIdx(1,:), InterpIdx(4,:),InterpIdx(3,:), 'linear'); InterpSlice = reshape(InterpSlice, DestSize); LFOut(:,:,:,UStart:UStop,ColChan) = InterpSlice; end fprintf('.') end LF = LFOut; clear LFOut; %---Clip interpolation result, which sometimes rings slightly out of range--- LF(isnan(LF)) = 0; LF = max(0, min(1, LF)); fprintf('\nDone\n'); end
github
hazirbas/light-field-toolbox-master
LFWriteMetadata.m
.m
light-field-toolbox-master/LFToolbox0.4/LFWriteMetadata.m
10,271
utf_8
18ac683694e04562a3249c7226bdde52
% LFWriteMetadata - saves variables to a file in JSON format % % Usage: % LFWriteMetadata( JsonFileFname, DataToSave ) % % This function saves data to a JSON file. % % Based on JSONlab by Qianqian Fang, % http://www.mathworks.com.au/matlabcentral/fileexchange/33381-jsonlab-a-toolbox-to-encodedecode-json-files-in-matlaboctave % % Minor modifications by Donald G. Dansereau, 2013, to simplify the interface as appropriate for use % in the Light Field Toolbox. % % See also: LFReadMetadata % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LFWriteMetadata( JsonFileFname, DataToSave ) rootname = []; varname=inputname(1); opt.FileName = JsonFileFname; opt.IsOctave=exist('OCTAVE_VERSION'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(DataToSave) || islogical(DataToSave) || ischar(DataToSave) || isstruct(DataToSave) || iscell(DataToSave)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(DataToSave) || iscell(DataToSave))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2json(rootname,DataToSave,rootlevel,opt); if(rootisarray) json=sprintf('%s\n',json); else json=sprintf('{\n%s\n}\n',json); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);\n',jsonp,json); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); len=numel(item); % let's handle 1D cell first padding1=repmat(sprintf('\t'),1,level-1); padding0=repmat(sprintf('\t'),1,level); if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [\n',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[\n',padding0); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": null',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%snull',padding0); end end for i=1:len txt=sprintf('%s%s%s',txt,padding1,obj2json(name,item{i},level+(len>1),varargin{:})); if(i<len) txt=sprintf('%s%s',txt,sprintf(',\n')); end end if(len>1) txt=sprintf('%s\n%s]',txt,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end len=numel(item); padding1=repmat(sprintf('\t'),1,level-1); padding0=repmat(sprintf('\t'),1,level); sep=','; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [\n',padding0,checkname(name,varargin{:})); end else if(len>1) txt=sprintf('%s[\n',padding0); end end for e=1:len names = fieldnames(item(e)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {\n',txt,repmat(sprintf('\t'),1,level+(len>1)), checkname(name,varargin{:})); else txt=sprintf('%s%s{\n',txt,repmat(sprintf('\t'),1,level+(len>1))); end if(~isempty(names)) for i=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{i},getfield(item(e),... names{i}),level+1+(len>1),varargin{:})); if(i<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,sprintf('\n')); end end txt=sprintf('%s%s}',txt,repmat(sprintf('\t'),1,level+(len>1))); if(e==len) sep=''; end if(e<len) txt=sprintf('%s%s',txt,sprintf(',\n')); end end if(len>1) txt=sprintf('%s\n%s]',txt,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); sep=sprintf(',\n'); padding1=repmat(sprintf('\t'),1,level); padding0=repmat(sprintf('\t'),1,level+1); if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [\n',padding1,checkname(name,varargin{:})); end else if(len>1) txt=sprintf('%s[\n',padding1); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end if(len==1) DataToSave=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) DataToSave=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,repmat(sprintf('\t'),1,level),DataToSave); else txt=sprintf('%s%s%s%s',txt,repmat(sprintf('\t'),1,level+1),['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s\n%s%s',txt,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end padding1=repmat(sprintf('\t'),1,level); padding0=repmat(sprintf('\t'),1,level+1); if(length(size(item))>2 || issparse(item) || ~isreal(item) || jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{\n%s"_ArrayType_": "%s",\n%s"_ArraySize_": %s,\n',... padding1,padding0,class(item),padding0,regexprep(mat2str(size(item)),'\s+',',') ); else txt=sprintf('%s"%s": {\n%s"_ArrayType_": "%s",\n%s"_ArraySize_": %s,\n',... padding1,checkname(name,varargin{:}),padding0,class(item),padding0,regexprep(mat2str(size(item)),'\s+',',') ); end else if(isempty(name)) txt=sprintf('%s%s',padding1,matdata2json(item,level+1,varargin{:})); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),matdata2json(item,level+1,varargin{:})); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sprintf(',\n')); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sprintf(',\n')); if(find(size(item)==1)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), sprintf('\n')); else txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), sprintf('\n')); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), sprintf('\n')); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sprintf(',\n')); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), sprintf('\n')); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[\n'); post=sprintf('\n%s]',repmat(sprintf('\t'),1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],\n')]]; if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(sprintf('\t'),1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-1:end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function val=jsonopt(key,default,varargin) val=default; if(nargin<=2) return; end opt=varargin{1}; if(isstruct(opt) && isfield(opt,key)) val=getfield(opt,key); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end
github
hazirbas/light-field-toolbox-master
LFBuild4DFreqDualFan.m
.m
light-field-toolbox-master/LFToolbox0.4/LFBuild4DFreqDualFan.m
4,955
utf_8
b925c1d38066faa9f44d0c51b8c68d91
% LFBuild4DFreqDualFan - construct a 4D dual-fan passband filter in the frequency domain % % Usage: % % [H, FiltOptions] = LFBuild4DFreqDualFan( LFSize, Slope, BW, FiltOptions ) % H = LFBuild4DFreqDualFan( LFSize, Slope, BW ) % % This file constructs a real-valued magnitude response in 4D, for which the passband is a dual-fan, % the intersection of 2 2D fans. % % Once constructed the filter must be applied to a light field, e.g. using LFFilt4DFFT. The % LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters. % % A more technical discussion, including the use of filters for denoising and volumetric focus, and % the inclusion of aliases components, is included in: % % [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field % Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015. % % Inputs: % % LFSize : Size of the frequency-domain filter. This should match or exceed the size of the % light field to be filtered. If it's larger than the input light field, the input is % zero-padded to match the filter's size by LFFilt4DFFT. % % Slope : The slope of the planar passband. If different slopes are desired in s,t and u,v, % the optional aspect parameter should be used. % % BW : 3-db Bandwidth of the planar passband. % % [optional] FiltOptions : struct controlling filter construction % SlopeMethod : 'Skew' or 'Rotate' default 'skew' % Precision : 'single' or 'double', default 'single' % Rolloff : 'Gaussian' or 'Butter', default 'Gaussian' % Order : controls the order of the filter when Rolloff is 'Butter', default 3 % Aspect4D : aspect ratio of the light field, default [1 1 1 1] % Window : Default false. By default the edges of the passband are sharp; this adds % a smooth rolloff at the edges when used in conjunction with Extent4D or % IncludeAliased. % Extent4D : controls where the edge of the passband occurs, the default [1 1 1 1] % is the edge of the Nyquist box. When less than 1, enabling windowing % introduces a rolloff after the edge of the passband. Can be greater % than 1 when using IncludeAliased. % IncludeAliased : default false; allows the passband to wrap around off the edge of the % Nyquist box; used in conjunction with Window and/or Extent4D. This can % increase processing time dramatically, e.g. Extent4D = [2,2,2,2] % requires a 2^4 = 16-fold increase in time to construct the filter. % Useful when passband content is aliased, see [2]. % % Outputs: % % H : real-valued frequency magnitude response % FiltOptions : The filter options including defaults, with an added PassbandInfo field % detailing the function and time of construction of the filter % % See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, % LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, % LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [H, FiltOptions] = LFBuild4DFreqDualFan( LFSize, Slope1, Slope2, BW, FiltOptions ) FiltOptions = LFDefaultField('FiltOptions', 'Aspect4D', 1); FiltOptions = LFDefaultField('FiltOptions', 'Extent4D', 1); if( length(LFSize) == 1 ) LFSize = LFSize .* [1,1,1,1]; end if( length(FiltOptions.Extent4D) == 1 ) FiltOptions.Extent4D = FiltOptions.Extent4D .* [1,1,1,1]; end if( length(FiltOptions.Aspect4D) == 1 ) FiltOptions.Aspect4D = FiltOptions.Aspect4D .* [1,1,1,1]; end FiltOptionsSU = FiltOptions; FiltOptionsSU.Aspect2D = FiltOptionsSU.Aspect4D([2,4]); FiltOptionsSU.Extent2D = FiltOptionsSU.Extent4D([2,4]); Hsu = LFBuild2DFreqFan( LFSize([2,4]), Slope1, Slope2, BW, FiltOptionsSU ); FiltOptionsTV = FiltOptions; FiltOptionsTV.Aspect2D = FiltOptionsSU.Aspect4D([1,3]); FiltOptionsTV.Extent2D = FiltOptionsSU.Extent4D([1,3]); [Htv, FiltOptionsTV] = LFBuild2DFreqFan( LFSize([1,3]), Slope1, Slope2, BW, FiltOptionsTV ); FiltOptions = FiltOptionsTV; FiltOptions = rmfield(FiltOptions, 'Aspect2D'); FiltOptions = rmfield(FiltOptions, 'Extent2D'); Hsu = reshape(Hsu, [1, size(Hsu,1), 1, size(Hsu,2)]); Hsu = repmat(Hsu, [LFSize(1),1,LFSize(3),1]); Htv = reshape(Htv, [size(Htv,1), 1, size(Htv,2), 1]); Htv = repmat(Htv, [1,LFSize(2),1,LFSize(4)]); H = Hsu .* Htv; TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
github
hazirbas/light-field-toolbox-master
LFBuild4DFreqHypercone.m
.m
light-field-toolbox-master/LFToolbox0.4/LFBuild4DFreqHypercone.m
4,501
utf_8
256d28a026711e06809d334c23db0633
% LFBuild4DFreqHypercone - construct a 4D hypercone passband filter in the frequency domain % % Usage: % % [H, FiltOptions] = LFBuild4DFreqHypercone( LFSize, Slope, BW, FiltOptions ) % H = LFBuild4DFreqHypercone( LFSize, Slope, BW ) % % This file constructs a real-valued magnitude response in 4D, for which the passband is a hypercone. % % Once constructed the filter must be applied to a light field, e.g. using LFFilt4DFFT. The % LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters. % % A more technical discussion, including the use of filters for denoising and volumetric focus, and % the inclusion of aliases components, is included in: % % [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field % Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015. % % Inputs: % % LFSize : Size of the frequency-domain filter. This should match or exceed the size of the % light field to be filtered. If it's larger than the input light field, the input is % zero-padded to match the filter's size by LFFilt4DFFT. % % Slope : The slope of the planar passband. If different slopes are desired in s,t and u,v, % the optional aspect parameter should be used. % % BW : 3-db Bandwidth of the planar passband. % % [optional] FiltOptions : struct controlling filter construction % SlopeMethod : 'Skew' or 'Rotate' default 'skew' % Precision : 'single' or 'double', default 'single' % Rolloff : 'Gaussian' or 'Butter', default 'Gaussian' % Order : controls the order of the filter when Rolloff is 'Butter', default 3 % Aspect4D : aspect ratio of the light field, default [1 1 1 1] % Window : Default false. By default the edges of the passband are sharp; this adds % a smooth rolloff at the edges when used in conjunction with Extent4D or % IncludeAliased. % Extent4D : controls where the edge of the passband occurs, the default [1 1 1 1] % is the edge of the Nyquist box. When less than 1, enabling windowing % introduces a rolloff after the edge of the passband. Can be greater % than 1 when using IncludeAliased. % IncludeAliased : default false; allows the passband to wrap around off the edge of the % Nyquist box; used in conjunction with Window and/or Extent4D. This can % increase processing time dramatically, e.g. Extent4D = [2,2,2,2] % requires a 2^4 = 16-fold increase in time to construct the filter. % Useful when passband content is aliased, see [2]. % % Outputs: % % H : real-valued frequency magnitude response % FiltOptions : The filter options including defaults, with an added PassbandInfo field % detailing the function and time of construction of the filter % % See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, % LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, % LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [H, FiltOptions] = LFBuild4DFreqHypercone( LFSize, BW, FiltOptions ) FiltOptions = LFDefaultField('FiltOptions', 'HyperconeMethod', 'Rotated'); % 'Direct', 'Rotated' DistFunc = @(P, FiltOptions) DistFunc_4DCone( P, FiltOptions ); [H, FiltOptions] = LFHelperBuild4DFreq( LFSize, BW, FiltOptions, DistFunc ); TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); end %----------------------------------------------------------------------------------------------------------------------- function Dist = DistFunc_4DCone( P, FiltOptions ) switch( lower(FiltOptions.HyperconeMethod )) case 'direct' Dist = (P(1,:).*P(4,:) - P(2,:).*P(3,:)).^2 * 4; case 'rotated' R = 1/sqrt(2) .* [1,0,0,1; 0,1,1,0; 0,1,-1,0; 1,0,0,-1]; P=R*P; Dist = (sqrt(P(1,:).^2 + P(3,:).^2) - sqrt(P(2,:).^2 + P(4,:).^2)).^2 /2; otherwise error('Unrecognized hypercone construction method'); end end
github
hazirbas/light-field-toolbox-master
LFUtilProcessWhiteImages.m
.m
light-field-toolbox-master/LFToolbox0.4/LFUtilProcessWhiteImages.m
12,517
utf_8
82b7183214df46d50702d31ad904317c
% LFUtilProcessWhiteImages - process a folder/tree of white images by fitting a grid model to each % % Usage: % % LFUtilProcessWhiteImages % LFUtilProcessWhiteImages( WhiteImagesPath ) % LFUtilProcessWhiteImages( WhiteImagesPath, FileOptions, GridModelOptions ) % LFUtilProcessWhiteImages( WhiteImagesPath, [], GridModelOptions ) % % All parameters are optional and take on default values as set in the "Defaults" section at the top % of the implementation. As such, this can be called as a function or run directly by editing the % code. When calling as a function, pass an empty array "[]" to omit a parameter. % % As released, the default values are set up to match the naming conventions associated with Lytro % files extracted using LFP Reader v2.0.0. % % Lytro cameras come loaded with a database of white images. These are taken through a diffuser, % and at different zoom and focus settings. They are useful for removing vignetting (darkening near % edges of images) and for locating lenslet centers in raw light field images. % % This function prepares a set of white images for use by the LF Toolbox. To do this, it fits a grid % model to each white image, using the function LFBuildLensletGridModel. It also builds a database % for use in selecting an appropriate white image for decoding a light field, as in the function % LFLytroDecodeImage / LFSelectFromDatabase. The default parameters are set up to deal with the % white images extracted from a Lytro camera. % % For each grid model fit, a display is generated allowing visual confirmation that the grid fit is % a good one. This displays each estimated grid center as a red dot over top the white image. If % the function was successful, each red dot should appear at the center of a lenslet -- i.e. near % the brightest spot on each white bump. It does not matter if there are a few rows of lenslets on % the edges of the image with no red markers. % % % Inputs -- all are optional, see code below for default values : % % WhiteImagesPath : Path to folder containing white images -- note the function operates % recursively, i.e. it will search sub-folders. The white image database will % be created at the top level of this path. A typical configuration is to % create a "Cameras" folder with a separate subfolder of white images for each % camera in use. The appropriate path to pass to this function is the top % level of the cameras folder. % % FileOptions : struct controlling file naming and saving % .SaveResult : Set to false to perform a "dry run" % .ForceRedo : By default, already-processed white images are skipped; set % this to true to force reprocessing of already-processed files % .WhiteImageDatabasePath : Name of file to which white image database is saved % .WhiteMetadataFilenamePattern : File search pattern for finding white image metadata files % .WhiteRawDataFnameExtension : File extension of raw white image files % .ProcessedWhiteImagenamePattern : Pattern defining the names of grid model files; must include % a %s which gets replaced by the white image base filename % .WhiteImageMinMeanIntensity : Images with mean intensities below this threshold are % discarded; this is necessary because some of the Lytro white % images include are very dark and not useful for grid modelling % % GridModelOptions : struct controlling grid construction by LFBuildLensletGridModel % .FilterDiskRadiusMult : Filter disk radius for prefiltering white image for locating % lenslets; expressed relative to lenslet spacing; e.g. a % value of 1/3 means a disk filte with a radius of 1/3 the % lenslet spacing % .CropAmt : Edge pixels to ignore when finding the grid % .SkipStep : As a speed optimization, not all lenslet centers contribute % to the grid estimate; <SkipStep> pixels are skipped between % the lenslet centers that get used; a value of 1 means use all % % Output takes the form of saved grid model files and a white image database. % % See also: LFBuildLensletGridModel, LFUtilDecodeLytroFolder, LFUtilProcessCalibrations % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LFUtilProcessWhiteImages( WhiteImagesPath, FileOptions, GridModelOptions ) %---Defaults--- WhiteImagesPath = LFDefaultVal( 'WhiteImagesPath', 'Cameras' ); FileOptions = LFDefaultField( 'FileOptions', 'SaveResult', true ); FileOptions = LFDefaultField( 'FileOptions', 'ForceRedo', false ); FileOptions = LFDefaultField( 'FileOptions', 'WhiteImageDatabasePath', 'WhiteImageDatabase.mat' ); FileOptions = LFDefaultField( 'FileOptions', 'WhiteMetadataFilenamePattern', '*MOD_*.TXT' ); FileOptions = LFDefaultField( 'FileOptions', 'WhiteRawDataFnameExtension', '.RAW' ); FileOptions = LFDefaultField( 'FileOptions', 'ProcessedWhiteImagenamePattern', '%s.grid.json' ); FileOptions = LFDefaultField( 'FileOptions', 'WhiteImageMinMeanIntensity', 500 ); GridModelOptions = LFDefaultField( 'GridModelOptions', 'Orientation', 'horz' ); GridModelOptions = LFDefaultField( 'GridModelOptions', 'FilterDiskRadiusMult', 1/3 ); GridModelOptions = LFDefaultField( 'GridModelOptions', 'CropAmt', 25 ); GridModelOptions = LFDefaultField( 'GridModelOptions', 'SkipStep', 250 ); DispSize_pix = 160; % size of windows for visual confirmation display DebugBuildGridModel = false; % additional debug display %---Load white image info--- fprintf('Building database of white files...\n'); WhiteImageInfo = LFGatherCamInfo( WhiteImagesPath, FileOptions.WhiteMetadataFilenamePattern ); % The Lytro F01 database has two exposures per zoom/focus setting -- this eliminates the darker ones F01Images = find(strcmp({WhiteImageInfo.CamModel}, 'F01')); IsF01Image = false(size(WhiteImageInfo)); IsF01Image(F01Images) = true; ExposureDuration = [WhiteImageInfo.ExposureDuration]; MeanDuration = mean(ExposureDuration(F01Images)); DarkF01Images = find(IsF01Image & (ExposureDuration < MeanDuration)); CamInfoValid = true(size(WhiteImageInfo)); CamInfoValid(DarkF01Images) = false; %---Tagged onto all saved files--- TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); %---Iterate through all white images--- fprintf('Processing each white file...\n'); fprintf('Visually confirm the estimated grid centers (red) are a good match to the lenslet centers...\n'); for( iFile = 1:length(WhiteImageInfo) ) [CurFnamePath, CurFnameBase] = fileparts( WhiteImageInfo(iFile).Fname ); fprintf('%s [File %d / %d]:\n', fullfile(CurFnamePath,CurFnameBase), iFile, length(WhiteImageInfo)); ProcessedWhiteFname = sprintf( FileOptions.ProcessedWhiteImagenamePattern, CurFnameBase ); ProcessedWhiteFname = fullfile(WhiteImagesPath, CurFnamePath, ProcessedWhiteFname); if( ~FileOptions.ForceRedo && exist(ProcessedWhiteFname, 'file') ) fprintf('Output file %s already exists, skipping.\n', ProcessedWhiteFname); % note that the file can still be added to the database, after the if/else/end, % unless it's a dark image as detected below else if( ~CamInfoValid(iFile) ) fprintf('Dark F01 image, skipping and not adding to database\n'); continue; end %---Load white image and white image metadata--- CurMetadataFname = fullfile(WhiteImagesPath, WhiteImageInfo(iFile).Fname); CurRawImageFname = LFFindLytroPartnerFile( CurMetadataFname, FileOptions.WhiteRawDataFnameExtension ); WhiteImageMetadata = LFReadMetadata( CurMetadataFname ); WhiteImageMetadata = WhiteImageMetadata.master.picture.frameArray.frame.metadata; ImgSize = [WhiteImageMetadata.image.width, WhiteImageMetadata.image.height]; switch( WhiteImageInfo(iFile).CamModel ) case 'F01' WhiteImage = LFReadRaw( CurRawImageFname, '12bit' ); %---Detect very dark images in F01 camera--- if( mean(WhiteImage(:)) < FileOptions.WhiteImageMinMeanIntensity ) fprintf('Detected dark image, skipping and not adding to database\n'); CamInfoValid(iFile) = false; continue end case 'B01' WhiteImage = LFReadRaw( CurRawImageFname, '10bit' ); otherwise error('Unrecognized camera model'); end %---Initialize grid finding parameters based on metadata--- GridModelOptions.ApproxLensletSpacing = ... WhiteImageMetadata.devices.mla.lensPitch / WhiteImageMetadata.devices.sensor.pixelPitch; %---Find grid params--- [LensletGridModel, GridCoords] = LFBuildLensletGridModel( WhiteImage, GridModelOptions, DebugBuildGridModel ); GridCoordsX = GridCoords(:,:,1); GridCoordsY = GridCoords(:,:,2); %---Visual confirmation--- if( strcmpi(GridModelOptions.Orientation, 'vert') ) WhiteImage = WhiteImage'; end ImgSize = size(WhiteImage); HPlotSamps = ceil(DispSize_pix/LensletGridModel.HSpacing); VPlotSamps = ceil(DispSize_pix/LensletGridModel.VSpacing); LFFigure(1); clf subplot(331); imagesc(WhiteImage(1:DispSize_pix,1:DispSize_pix)); hold on colormap gray plot(GridCoordsX(1:VPlotSamps,1:HPlotSamps), GridCoordsY(1:VPlotSamps,1:HPlotSamps), 'r.') axis off subplot(333); imagesc(WhiteImage(1:DispSize_pix, ImgSize(2)-DispSize_pix:ImgSize(2))); hold on colormap gray plot(-(ImgSize(2)-DispSize_pix)+1 + GridCoordsX(1:VPlotSamps, end-HPlotSamps:end), GridCoordsY(1:VPlotSamps, end-HPlotSamps:end), 'r.') axis off CenterStart = (ImgSize-DispSize_pix)/2; HCenterStartSamps = floor(CenterStart(2) / LensletGridModel.HSpacing); VCenterStartSamps = floor(CenterStart(1) / LensletGridModel.VSpacing); subplot(335); imagesc(WhiteImage(CenterStart(1):CenterStart(1)+DispSize_pix, CenterStart(2):CenterStart(2)+DispSize_pix)); hold on colormap gray plot(-CenterStart(2)+1 + GridCoordsX(VCenterStartSamps + (1:VPlotSamps), HCenterStartSamps + (1:HPlotSamps)), -CenterStart(1)+1 + GridCoordsY(VCenterStartSamps + (1:VPlotSamps), HCenterStartSamps + (1:HPlotSamps)),'r.'); axis off subplot(337); imagesc(WhiteImage(ImgSize(1)-DispSize_pix:ImgSize(1), 1:DispSize_pix)); hold on colormap gray plot(GridCoordsX(end-VPlotSamps:end,1:HPlotSamps), -(ImgSize(1)-DispSize_pix)+1 + GridCoordsY(end-VPlotSamps:end,1:HPlotSamps), 'r.') axis off subplot(339); imagesc(WhiteImage(ImgSize(1)-DispSize_pix:ImgSize(1),ImgSize(2)-DispSize_pix:ImgSize(2))); hold on colormap gray plot(-(ImgSize(2)-DispSize_pix)+1 + GridCoordsX(end-VPlotSamps:end, end-HPlotSamps:end), -(ImgSize(1)-DispSize_pix)+1 + GridCoordsY(end-VPlotSamps:end, end-HPlotSamps:end), 'r.') axis off truesize % bigger display drawnow %---Optionally save--- if( FileOptions.SaveResult ) fprintf('Saving to %s\n', ProcessedWhiteFname); CamInfo = WhiteImageInfo(iFile); LFWriteMetadata(ProcessedWhiteFname, LFVar2Struct(GeneratedByInfo, GridModelOptions, CamInfo, LensletGridModel)); end end end CamInfo = WhiteImageInfo(CamInfoValid); %---Optionally save the white file database--- if( FileOptions.SaveResult ) FileOptions.WhiteImageDatabasePath = fullfile(WhiteImagesPath, FileOptions.WhiteImageDatabasePath); fprintf('Saving to %s\n', FileOptions.WhiteImageDatabasePath); save(FileOptions.WhiteImageDatabasePath, 'GeneratedByInfo', 'CamInfo'); end fprintf('Done\n'); end
github
hazirbas/light-field-toolbox-master
LFCalDispEstPoses.m
.m
light-field-toolbox-master/LFToolbox0.4/LFCalDispEstPoses.m
2,604
utf_8
1f7d8e57212bcbb143d2c597e59038f3
% LFCalDispEstPoses - Visualize pose estimates associated with a calibration info file % % Usage: % LFCalDispEstPoses( InputPath, CalOptions, DrawFrameSizeMult, BaseColour ) % % Draws a set of frames, one for each camera pose, in the colour defined by BaseColour. All inputs % except InputPath are optional. Pass an empty array "[]" to omit a parameter. See % LFUtilCalLensletCam for example usage. % % Inputs: % % InputPath : Path to folder containing CalInfo file. % % [optional] CalOptions : struct controlling calibration parameters % .CalInfoFname : Name of the file containing calibration estimate; note that this % parameter is automatically set in the CalOptions struct returned % by LFCalInit % % [optional] DrawFrameSizeMult : Multiplier on the displayed frame sizes % % [optional] BaseColour : RGB triplet defining a base drawing colour, RGB values are in the % range 0-1 % % % See also: LFUtilCalLensletCam % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LFCalDispEstPoses( InputPath, CalOptions, DrawFrameSizeMult, BaseColour ) %---Defaults--- CalOptions = LFDefaultField( 'CalOptions', 'CalInfoFname', 'CalInfo.json' ); DrawFrameSizeMult = LFDefaultVal( 'DrawFrameSizeMult', 1 ); BaseColour = LFDefaultVal( 'BaseColour', [1,1,0] ); %--- Fname = fullfile(CalOptions.CalInfoFname); EstCamPosesV = LFStruct2Var( LFReadMetadata(fullfile(InputPath, Fname)), 'EstCamPosesV' ); % Establish an appropriate scale for the drawing AutoDrawScale = EstCamPosesV(:,1:3); AutoDrawScale = AutoDrawScale(:); AutoDrawScale = (max(AutoDrawScale) - min(AutoDrawScale))/10; %---Draw cameras--- BaseFrame = ([0 1 0 0 0 0; 0 0 0 1 0 0; 0 0 0 0 0 1]); DrawFrameMed = [AutoDrawScale * DrawFrameSizeMult * BaseFrame; ones(1,6)]; DrawFrameLong = [AutoDrawScale*3/2 * DrawFrameSizeMult * BaseFrame; ones(1,6)]; for( PoseIdx = 1:size(EstCamPosesV, 1) ) CurH = eye(4); CurH(1:3,1:3) = rodrigues( EstCamPosesV(PoseIdx,4:6) ); CurH(1:3,4) = EstCamPosesV(PoseIdx,1:3); CurH = CurH^-1; CamFrame = CurH * DrawFrameMed(:,1:4); plot3( CamFrame(1,:), CamFrame(2,:), CamFrame(3,:), '-', 'color', BaseColour.*0.5, 'LineWidth',2 ); hold on CamFrame = CurH * DrawFrameLong(:,5:6); plot3( CamFrame(1,:), CamFrame(2,:), CamFrame(3,:), '-', 'color', BaseColour, 'LineWidth',2 ); end axis equal grid on xlabel('x [m]'); ylabel('y [m]'); zlabel('z [m]'); title('Estimated camera poses');
github
hazirbas/light-field-toolbox-master
LFMatlabPathSetup.m
.m
light-field-toolbox-master/LFToolbox0.4/LFMatlabPathSetup.m
629
utf_8
09c19ebacb36d9e2d70336dd7f62bc9c
% LFMatlabPathSetup - convenience function to add the light field toolbox to matlab's path % % It may be convenient to add this to your startup.m file. % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LFMatlabPathSetup % Find the path to this script, and use it as the base path LFToolboxPath = fileparts(mfilename('fullpath')); fprintf('Adding paths for LF Toolbox '); addpath( fullfile(LFToolboxPath) ); addpath( fullfile(LFToolboxPath, 'SupportFunctions') ); addpath( fullfile(LFToolboxPath, 'SupportFunctions', 'CameraCal') ); fprintf('%s, done.\n', LFToolboxVersion);
github
hazirbas/light-field-toolbox-master
LFReadLFP.m
.m
light-field-toolbox-master/LFToolbox0.4/LFReadLFP.m
9,456
utf_8
12a412c0c96c3bd388028f4eb975749f
% LFReadLFP - Load a lytro LFP / LFR file % % Usage: % [LFP, ExtraSections] = LFReadLFP( Fname ) % % The Lytro LFP is a container format and may contain one of several types of data. The file extension varies based on % the source of the files, with exported files, on-camera files and image library files variously taking on the % extensions lfp, lfr, LFP and LFR. % % This function loads all the sections of an LFP and interprets those that it recognizes. Recognized sections include % thumbnails and focal stacks, raw light field and white images, metadata and serial data. If more than one section of % the same type appears, a cell array is constructed in the output struct -- this is the case for focal stacks, for % example. Files generated using Lytro Desktop 4.0 and 3.0 are supported. % % Additional output information includes the appropriate demosaic order for raw light field images, and the size of raw % images. % % Unrecognized sections are returned in the ExtraSections output argument. % % This function is based in part on Nirav Patel's lfpsplitter.c and Doug Kelley's read_lfp; Thanks to Michael Tao for % help and samples for decoding Illum imagery. % % Inputs : % Fname : path to an input LFP file % % Outputs: % LFP : Struct containing decoded LFP sections and supporting information, which may include one or more of % .Jpeg : Thumbnails, focal stacks -- see LFUtilExtractLFPThumbs for saving these to disk % .RawImg : Raw light field image % .WhiteImg : White image bundled into Illum LFP % .Metadata, .Serials : Information about the image and camera % .DemosaicOrder : The appropriate parameter to pass to Matlab's "demosaic" to debayer a RawImg % .ImgSize : Size of RawImg % % ExtraSections : Struct array containing unrecognized LFP sections % .Data : Buffer of chars containing the section's uninterpreted data block % .SectType : Descriptive name for the section, e.g. "hotPixelRef" % .Sha1 : Unique hash identifying the section % .SectHeader : Header bytes identifying the section as a table of contents or data % % See also: LFUtilExtractLFPThumbs, LFUtilUnpackLytroArchive, LFUtilDecodeLytroFolder % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [LFP, ExtraSections] = LFReadLFP( Fname ) %---Consts--- LFPConsts.LFPHeader = hex2dec({'89', '4C', '46', '50', '0D', '0A', '1A', '0A', '00', '00', '00', '01'}); % 12-byte LFPSections header LFPConsts.SectHeaderLFM = hex2dec({'89', '4C', '46', '4D', '0D', '0A', '1A', '0A'})'; % header for table of contents LFPConsts.SectHeaderLFC = hex2dec({'89', '4C', '46', '43', '0D', '0A', '1A', '0A'})'; % header for content section LFPConsts.SecHeaderPaddingLen = 4; LFPConsts.Sha1Length = 45; LFPConsts.ShaPaddingLen = 35; % Sha1 codes are followed by 35 null bytes %---Break out recognized sections--- KnownSectionTypes = { ... ... % Lytro Desktop 4 'Jpeg', 'picture.accelerationArray.vendorContent.imageArray.imageRef', 'jpeg'; ... 'Jpeg', 'thumbnails.imageRef', 'jpeg'; ... 'RawImg', 'frames.frame.imageRef', 'raw'; ... 'WhiteImg', 'frames.frame.modulationDataRef', 'raw';... 'Metadata', 'frames.frame.metadataRef', 'json'; ... 'Serials', 'frames.frame.privateMetadataRef', 'json'; ... ... % Earlier Lytro Desktop versions 'RawImg', 'picture.frameArray.frame.imageRef', 'raw'; ... 'Metadata', 'picture.frameArray.frame.metadataRef', 'json'; ... 'Serials', 'picture.frameArray.frame.privateMetadataRef', 'json'; ... }; %--- ExtraSections = []; LFP = []; InFile=fopen(Fname, 'rb'); %---Check for the magic header--- HeaderBytes = fread( InFile, length(LFPConsts.LFPHeader), 'uchar' ); if( (length(HeaderBytes)~=length(LFPConsts.LFPHeader)) || ~all( HeaderBytes == LFPConsts.LFPHeader ) ) fclose(InFile); fprintf( 'Unrecognized file type\n' ); return end %---Confirm headerlength bytes--- HeaderLength = fread(InFile,1,'uint32','ieee-be'); assert( HeaderLength == 0, 'Unexpected length at top-level header' ); %---Read each section--- NSections = 0; TOCIdx = []; while( ~feof(InFile) ) NSections = NSections+1; LFPSections( NSections ) = ReadSection( InFile, LFPConsts ); %---Mark the table of contents section--- if( all( LFPSections( NSections ).SectHeader == LFPConsts.SectHeaderLFM ) ) assert( isempty(TOCIdx), 'Found more than one LFM metadata section' ); TOCIdx = NSections; end end fclose( InFile ); %---Decode the table of contents--- assert( ~isempty(TOCIdx), 'Found no LFM metadata sections' ); TOC = LFReadMetadata( LFPSections(TOCIdx).Data ); LFPSections(TOCIdx).SectType = 'TOC'; %---find all sha1 refs in TOC--- TocData = LFPSections(TOCIdx).Data; ShaIdx = strfind( TocData, 'sha1-' ); SeparatorIdx = find( TocData == ':' ); EolIdx = find( TocData == 10 ); for( iSha = 1:length(ShaIdx) ) LabelStopIdx = SeparatorIdx( find( SeparatorIdx < ShaIdx(iSha), 1, 'last' ) ); LabelStartIdx = EolIdx( find( EolIdx < LabelStopIdx, 1, 'last' ) ); ShaEndIdx = EolIdx( find( EolIdx > ShaIdx(iSha), 1, 'first' ) ); CurLabel = TocData(LabelStartIdx:LabelStopIdx); CurSha = TocData(LabelStopIdx:ShaEndIdx); CurLabel = strsplit(CurLabel, '"'); CurSha = strsplit(CurSha, '"'); CurLabel = CurLabel{2}; CurSha = CurSha{2}; SectNames{iSha} = CurLabel; SectIDs{iSha} = CurSha; end %---Apply section labels--- for( iSect = 1:length(SectNames) ) CurSectSHA = SectIDs{iSect}; MatchingSectIdx = find( strcmp( CurSectSHA, {LFPSections.Sha1} ) ); if( ~isempty(MatchingSectIdx) ) LFPSections(MatchingSectIdx).SectType = SectNames{iSect}; end end for( iSect = 1:size(KnownSectionTypes,1) ) FoundField = true; while(FoundField) [LFP, LFPSections, TOC, FoundField] = ExtractNamedField(LFP, LFPSections, TOC, KnownSectionTypes(iSect,:) ); end end ExtraSections = LFPSections; %---unpack the image(s)--- if( isfield( LFP, 'RawImg') ) LFP.ImgSize = [LFP.Metadata.image.width, LFP.Metadata.image.height]; switch( LFP.Metadata.camera.model ) case 'F01' assert( LFP.Metadata.image.rawDetails.pixelPacking.bitsPerPixel == 12 ); assert( strcmp(LFP.Metadata.image.rawDetails.pixelPacking.endianness, 'big') ); LFP.RawImg = LFUnpackRawBuffer( LFP.RawImg, '12bit', LFP.ImgSize )'; LFP.DemosaicOrder = 'bggr'; case 'ILLUM' assert( LFP.Metadata.image.pixelPacking.bitsPerPixel == 10 ); assert( strcmp(LFP.Metadata.image.pixelPacking.endianness, 'little') ); LFP.RawImg = LFUnpackRawBuffer( LFP.RawImg, '10bit', LFP.ImgSize )'; if( isfield( LFP, 'WhiteImg' ) ) LFP.WhiteImg = LFUnpackRawBuffer( LFP.WhiteImg, '10bit', LFP.ImgSize )'; end LFP.DemosaicOrder = 'grbg'; otherwise warning('Unrecognized camera model'); return end end end % -------------------------------------------------------------------- function LFPSect = ReadSection( InFile, LFPConsts ) LFPSect.SectHeader = fread(InFile, length(LFPConsts.SectHeaderLFM), 'uchar')'; Padding = fread(InFile, LFPConsts.SecHeaderPaddingLen, 'uint8'); % skip padding SectLength = fread(InFile, 1, 'uint32', 'ieee-be'); LFPSect.Sha1 = char(fread(InFile, LFPConsts.Sha1Length, 'uchar')'); Padding = fread(InFile, LFPConsts.ShaPaddingLen, 'uint8'); % skip padding LFPSect.Data = char(fread(InFile, SectLength, 'uchar'))'; while( 1 ) Padding = fread(InFile, 1, 'uchar'); if( feof(InFile) || (Padding ~= 0) ) break; end end if ~feof(InFile) fseek( InFile, -1, 'cof'); % rewind one byte end end % -------------------------------------------------------------------- function [LFP, LFPSections, TOC, FoundField] = ExtractNamedField(LFP, LFPSections, TOC, FieldInfo) FoundField = false; FieldName = FieldInfo{1}; JsonName = FieldInfo{2}; FieldFormat = FieldInfo{3}; JsonTokens = strsplit(JsonName, '.'); TmpToc = TOC; if( ~iscell(JsonTokens) ) JsonTokens = {JsonTokens}; end for( i=1:length(JsonTokens) ) if( ~isfield(TmpToc, JsonTokens{i}) || isempty([TmpToc.(JsonTokens{i})]) ) return; end TmpToc = TmpToc.(JsonTokens{i}); % takes the first one in the case of an array end FieldIdx = find( strcmp( TmpToc, {LFPSections.Sha1} ) ); if( ~isempty(FieldIdx) ) SubField = struct('type','.','subs',FieldName); %--- detect image array and force progress by removing the currently-processed entry --- S = struct('type','.','subs',JsonTokens(1:end-1)); t = subsref( TOC, S ); ArrayLen = length(t); if( (isstruct(t) && ArrayLen>1) || isfield( LFP, FieldName ) ) S(end+1).type = '()'; S(end).subs = {1}; TOC = subsasgn( TOC, S, [] ); % Add an indexing subfield for image arrays SubField(end+1).type = '{}'; SubField(end).subs = {ArrayLen}; end %---Copy the data into the LFP struct--- LFP = subsasgn( LFP, SubField, LFPSections(FieldIdx).Data ); LFPSections = LFPSections([1:FieldIdx-1, FieldIdx+1:end]); %---Decode JSON-formatted sections--- switch( FieldFormat ) case 'json' LFP.(FieldName) = LFReadMetadata( LFP.(FieldName) ); end FoundField = true; end end
github
hazirbas/light-field-toolbox-master
LFBuild4DFreqHyperfan.m
.m
light-field-toolbox-master/LFToolbox0.4/LFBuild4DFreqHyperfan.m
4,676
utf_8
2bec28d4e5b0d48494ee457844595957
% LFBuild4DFreqHyperfan - construct a 4D hyperfan passband filter in the frequency domain % % Usage: % % [H, FiltOptions] = LFBuild4DFreqHyperfan( LFSize, Slope, BW, FiltOptions ) % H = LFBuild4DFreqHyperfan( LFSize, Slope, BW ) % % This file constructs a real-valued magnitude response in 4D, for which the passband is a hyperfan. % This is useful for selecting objects over a range of depths from a lightfield, i.e. volumetric % focus. % % Once constructed the filter must be applied to a light field, e.g. using LFFilt4DFFT. The % LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters. % % A more technical discussion, including the use of filters for denoising and volumetric focus, and % the inclusion of aliases components, is included in: % % [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field % Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015. % % Inputs: % % LFSize : Size of the frequency-domain filter. This should match or exceed the size of the % light field to be filtered. If it's larger than the input light field, the input is % zero-padded to match the filter's size by LFFilt4DFFT. % % Slope : The slope of the planar passband. If different slopes are desired in s,t and u,v, % the optional aspect parameter should be used. % % BW : 3-db Bandwidth of the planar passband. % % [optional] FiltOptions : struct controlling filter construction % SlopeMethod : 'Skew' or 'Rotate' default 'skew' % Precision : 'single' or 'double', default 'single' % Rolloff : 'Gaussian' or 'Butter', default 'Gaussian' % Order : controls the order of the filter when Rolloff is 'Butter', default 3 % Aspect4D : aspect ratio of the light field, default [1 1 1 1] % Window : Default false. By default the edges of the passband are sharp; this adds % a smooth rolloff at the edges when used in conjunction with Extent4D or % IncludeAliased. % Extent4D : controls where the edge of the passband occurs, the default [1 1 1 1] % is the edge of the Nyquist box. When less than 1, enabling windowing % introduces a rolloff after the edge of the passband. Can be greater % than 1 when using IncludeAliased. % IncludeAliased : default false; allows the passband to wrap around off the edge of the % Nyquist box; used in conjunction with Window and/or Extent4D. This can % increase processing time dramatically, e.g. Extent4D = [2,2,2,2] % requires a 2^4 = 16-fold increase in time to construct the filter. % Useful when passband content is aliased, see [2]. % % Outputs: % % H : real-valued frequency magnitude response % FiltOptions : The filter options including defaults, with an added PassbandInfo field % detailing the function and time of construction of the filter % % See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, % LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, % LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [H, FiltOptions] = LFBuild4DFreqHyperfan( LFSize, Slope1, Slope2, BW, FiltOptions ) FiltOptions = LFDefaultField('FiltOptions', 'HyperfanMethod', 'Direct'); % 'Direct', 'Sweep' switch( lower(FiltOptions.HyperfanMethod )) case 'sweep' FiltOptions = LFDefaultField('FiltOptions', 'SweepSteps', 5); SweepVec = linspace(Slope1, Slope2, FiltOptions.SweepSteps); [H, FiltOptions] = LFBuild4DFreqPlane( LFSize, SweepVec(1), BW, FiltOptions ); for( CurSlope = SweepVec(2:end) ) H = max(H, LFBuild4DFreqPlane( LFSize, CurSlope, BW, FiltOptions )); end case 'direct' FiltOptions = LFDefaultField('FiltOptions', 'HyperconeBW', BW); [H, FiltOptions] = LFBuild4DFreqHypercone( LFSize, FiltOptions.HyperconeBW, FiltOptions ); [Hdf, FiltOptions] = LFBuild4DFreqDualFan( LFSize, Slope1, Slope2, BW, FiltOptions ); H = H .* Hdf; otherwise error('Unrecognized hyperfan construction method'); end TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
github
hazirbas/light-field-toolbox-master
LFUtilProcessCalibrations.m
.m
light-field-toolbox-master/LFToolbox0.4/LFUtilProcessCalibrations.m
3,086
utf_8
b7ed374da00985b749186101dccbfc70
% LFUtilProcessCalibrations - process a folder/tree of camera calibrations % % Usage: % % LFUtilProcessCalibrations % LFUtilProcessCalibrations( CalibrationsPath ) % LFUtilProcessCalibrations( CalibrationsPath, FileOptions ) % LFUtilProcessCalibrations( [], FileOptions ) % % All parameters are optional and take on default values as set in the "Defaults" section at the top % of the implementation. As such, this can be called as a function or run directly by editing the % code. When calling as a function, pass an empty array "[]" to omit a parameter. % % This function recursively crawls through a folder identifying camera "calibration info" files and % building a database for use in selecting a calibration appropriate to a light field. An example % usage is in the image rectification code in LFUtilDecodeLytroFolder / LFSelectFromDatabase. % % Inputs -- all are optional, see code below for default values : % % CalibrationsPath : Path to folder containing calibrations -- note the function operates % recursively, i.e. it will search sub-folders. The calibration database will % be created at the top level of this path. A typical configuration is to % create a "Cameras" folder with a separate subfolder of calibrations for each % camera in use. The appropriate path to pass to this function is the top % level of that cameras folder. % % % FileOptions : struct controlling file naming and saving % .SaveResult : Set to false to perform a "dry run" % .CalibrationDatabaseFname : Name of file to which white image database is saved % .CalInfoFilenamePattern : File search pattern for finding calibrations % % Output takes the form of a saved calibration database. % % See also: LFUtilDecodeLytroFolder, LFCalRectifyLF, LFSelectFromDatabase, LFUtilCalLensletCam, % LFUtilProcessWhiteImages % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LFUtilProcessCalibrations( CalibrationsPath, FileOptions ) %---Defaults--- CalibrationsPath = LFDefaultVal( 'CalibrationsPath', 'Cameras' ); FileOptions = LFDefaultField( 'FileOptions', 'SaveResult', true ); FileOptions = LFDefaultField( 'FileOptions', 'CalibrationDatabaseFname', 'CalibrationDatabase.mat' ); FileOptions = LFDefaultField( 'FileOptions', 'CalInfoFilenamePattern', 'CalInfo*.json' ); %---Crawl folder structure locating calibrations--- fprintf('Building database of calibrations in %s\n', CalibrationsPath); CamInfo = LFGatherCamInfo( CalibrationsPath, FileOptions.CalInfoFilenamePattern ); %---Optionally save--- if( FileOptions.SaveResult ) SaveFpath = fullfile(CalibrationsPath, FileOptions.CalibrationDatabaseFname); fprintf('Saving to %s\n', SaveFpath); TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); save(SaveFpath, 'GeneratedByInfo', 'CamInfo'); end
github
hazirbas/light-field-toolbox-master
LFUtilExtractLFPThumbs.m
.m
light-field-toolbox-master/LFToolbox0.4/LFUtilExtractLFPThumbs.m
2,528
utf_8
bcf530be1d01e6c00268cf5bbf398fde
% LFUtilExtractLFPThumbs - extract thumbnails from LFP files and write to disk % % Usage: % % LFUtilExtractLFPThumbs % LFUtilExtractLFPThumbs( InputPath ) % % This extracts the thumbnail preview and focal stack images from LFR and LFP files, and is useful in providing a % preview, e.g. when copying files directly from an Illum camera. % % Inputs -- all are optional : % % InputPath : Path / filename pattern for locating LFP files. The function will move recursively through a tree, % matching one or more filename patterns. See LFFindFilesRecursive for a full description. % % The default input path is {'.', '*.LFP','*.LFR','*.lfp','*.lfr'}, i.e. the current folder, recursively searching % for all files matching uppercase and lowercase 'LFP' and 'LFR' extensions. % % Examples: % % LFUtilExtractLFPThumbs % % Will extract thumbnails from all LFP and LFR images in the current folder and its subfolders. % % The following are also valid, see LFFindFilesRecursive for more. % % LFUtilExtractLFPThumbs('Images') % LFUtilExtractLFPThumbs({'*.lfr','*.lfp'}) % LFUtilExtractLFPThumbs({'Images','*.lfr','*.lfp'}) % LFUtilExtractLFPThumbs('Images/*.lfr') % LFUtilExtractLFPThumbs('*.lfr') % LFUtilExtractLFPThumbs('Images/IMG_0001.LFR') % LFUtilExtractLFPThumbs('IMG_0001.LFR') % % See also: LFFindFilesRecursive % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LFUtilExtractLFPThumbs( InputPath ) %---Defaults--- InputPath = LFDefaultVal( 'InputPath','.' ); DefaultFileSpec = {'*.LFP','*.LFR','*.lfp','*.lfr'}; % gets overriden below, if a file spec is provided [FileList, BasePath] = LFFindFilesRecursive( InputPath, DefaultFileSpec ); fprintf('Found :\n'); disp(FileList) %---Process each file--- for( iFile = 1:length(FileList) ) CurFname = fullfile(BasePath, FileList{iFile}); fprintf('Processing [%d / %d] %s\n', iFile, length(FileList), CurFname); LFP = LFReadLFP( CurFname ); if( ~isfield(LFP, 'Jpeg') ) continue; end if( ~iscell(LFP.Jpeg) ) LFP.Jpeg = {LFP.Jpeg}; end for( i=1:length(LFP.Jpeg) ) OutFname = sprintf('%s-%03d.jpg', CurFname, i-1); fprintf('%s', OutFname); if( exist(OutFname,'file') ) fprintf(' Exists, skipping\n'); else OutFile = fopen(OutFname, 'wb'); fwrite(OutFile, LFP.Jpeg{i}); fclose(OutFile); fprintf('\n'); end end end
github
hazirbas/light-field-toolbox-master
LFFilt2DFFT.m
.m
light-field-toolbox-master/LFToolbox0.4/LFFilt2DFFT.m
4,344
utf_8
94c37a901f7a9a1271d469d23be351cc
% LFFilt2DFFT - Apply a 2D frequency-domain filter to a 4D light field using the FFT % % Usage: % % [LF, FiltOptions] = LFFilt2DFFT( LF, H, FiltDims, FiltOptions ) % LF = LFFilt2DFFT( LF, H, FiltDims ) % % % This filter works on 2D slices of the input light field, applying the 2D filter H to each in turn. It takes the FFT % of each slice of the input light field, multiplies by the provided magnitude response H, then calls the inverse FFT. % % The FiltDims input specifies the two dimensions along which H should be applied. The frequency-domain filter H should % match or exceed the size of the light field LF in these dimensions. If H is larger than the input light field, LF is % zero-padded to match the filter's size. If a weight channel is present in the light field it gets used during % normalization. % % See LFDemoBasicFiltLytro for example usage. % % % Inputs % % LF : The light field to be filtered % % H : The frequency-domain filter to apply, as constructed by one of the LFBuild4DFreq* functions % % FiltDims : The dimensions along which H should be applied % % [optional] FiltOptions : struct controlling filter operation % Precision : 'single' or 'double', default 'single' % Normalize : default true; when enabled the output is normalized so that darkening near image edges is % removed % MinWeight : during normalization, pixels for which the output value is not well defined (i.e. for % which the filtered weight is very low) get set to 0. MinWeight sets the threshold at which % this occurs, default is 10 * the numerical precision of the output, as returned by eps % % Outputs: % % LF : The filtered 4D light field % FiltOptions : The filter options including defaults, with an added FilterInfo field detailing the function and % time of filtering. % % See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, LFBuild2DFreqFan, LFBuild2DFreqLine, % LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, % LFFiltShiftSum % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [LF, FiltOptions] = LFFilt2DFFT( LF, H, FiltDims, FiltOptions ) FiltOptions = LFDefaultField('FiltOptions', 'Precision', 'single'); FiltOptions = LFDefaultField('FiltOptions', 'Normalize', true); FiltOptions = LFDefaultField('FiltOptions', 'MinWeight', 10*eps(FiltOptions.Precision)); %--- NColChans = size(LF,5); HasWeight = ( NColChans == 4 || NColChans == 2 ); if( HasWeight ) NColChans = NColChans-1; end %--- IterDims = 1:4; IterDims(FiltDims) = 0; IterDims = find(IterDims~=0); PermuteOrder = [IterDims, FiltDims, 5]; LF = permute(LF, PermuteOrder); LF = LFConvertToFloat(LF, FiltOptions.Precision); %--- LFSize = size(LF); SlicePaddedSize = size(H); for( IterDim1 = 1:LFSize(1) ) fprintf('.'); for( IterDim2 = 1:LFSize(2) ) CurSlice = squeeze(LF(IterDim1,IterDim2,:,:,:)); if( FiltOptions.Normalize ) if( HasWeight ) for( iColChan = 1:NColChans ) CurSlice(:,:,iColChan) = CurSlice(:,:,iColChan) .* CurSlice(:,:,end); end else % add a weight channel CurSlice(:,:,end+1) = ones(size(CurSlice(:,:,1)), FiltOptions.Precision); end end SliceSize = size(CurSlice); for( iColChan = 1:SliceSize(end) ) X = fftn(CurSlice(:,:,iColChan), SlicePaddedSize); X = X .* H; x = ifftn(X,'symmetric'); x = x(1:LFSize(3), 1:LFSize(4)); CurSlice(:,:,iColChan) = x; end if( FiltOptions.Normalize ) WeightChan = CurSlice(:,:,end); InvalidIdx = find(WeightChan < FiltOptions.MinWeight); ChanSize = numel(CurSlice(:,:,1)); for( iColChan = 1:NColChans ) CurSlice(:,:,iColChan) = CurSlice(:,:,iColChan) ./ WeightChan; CurSlice( InvalidIdx + ChanSize.*(iColChan-1) ) = 0; end end % record channel LF(IterDim1,IterDim2,:,:,:) = CurSlice(:,:,1:LFSize(5)); end end LF = max(0,LF); LF = min(1,LF); LF = ipermute(LF, PermuteOrder); %--- TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); FiltOptions.FilterInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); fprintf(' Done\n');
github
hazirbas/light-field-toolbox-master
LFBuild2DFreqLine.m
.m
light-field-toolbox-master/LFToolbox0.4/LFBuild2DFreqLine.m
4,431
utf_8
0dcc452b6b957958b7243b285453790b
% LFBuild2DFreqLine - construct a 2D line passband filter in the frequency domain % % Usage: % % [H, FiltOptions] = LFBuild2DFreqLine( LFSize, Slope, BW, FiltOptions ) % H = LFBuild2DFreqLine( LFSize, Slope, BW ) % % This file constructs a real-valued magnitude response in 2D, for which the passband is a line. The cascade of two line % filters, applied in s,u and in t,v, is identical to a 4D planar filter, e.g. that constructed by LFBuild4DFreqPlane. % % Once constructed the filter must be applied to a light field, e.g. using LFFilt2DFFT. The % LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters. % % A more technical discussion, including the use of filters for denoising and volumetric focus, and % the inclusion of aliases components, is included in: % % [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field % Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015. % % Inputs: % % LFSize : Size of the frequency-domain filter. This should match or exceed the size of the % light field to be filtered. If it's larger than the input light field, the input is % zero-padded to match the filter's size by LFFilt2DFFT. % % Slope : Slopes at the extents of the fan passband. % % BW : 3-db Bandwidth of the planar passband. % % [optional] FiltOptions : struct controlling filter construction % SlopeMethod : only 'Skew' is supported for now % Precision : 'single' or 'double', default 'single' % Rolloff : 'Gaussian' or 'Butter', default 'Gaussian' % Order : controls the order of the filter when Rolloff is 'Butter', default 3 % Aspect2D : aspect ratio of the light field, default [1 1] % Window : Default false. By default the edges of the passband are sharp; this adds % a smooth rolloff at the edges when used in conjunction with Extent2D or % IncludeAliased. % Extent2D : controls where the edge of the passband occurs, the default [1 1] % is the edge of the Nyquist box. When less than 1, enabling windowing % introduces a rolloff after the edge of the passband. Can be greater % than 1 when using IncludeAliased. % IncludeAliased : default false; allows the passband to wrap around off the edge of the % Nyquist box; used in conjunction with Window and/or Extent2D. This can % increase processing time dramatically, e.g. Extent2D = [2,2] % requires a 2^2 = 4-fold increase in time to construct the filter. % Useful when passband content is aliased, see [2]. % % Outputs: % % H : real-valued frequency magnitude response % FiltOptions : The filter options including defaults, with an added PassbandInfo field % detailing the function and time of construction of the filter % % See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, % LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, % LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [H, FiltOptions] = LFBuild2DFreqLine( LFSize, Slope, BW, FiltOptions ) FiltOptions = LFDefaultField('FiltOptions', 'SlopeMethod', 'Skew'); % 'Skew', 'Rotate' DistFunc = @(P, FiltOptions) DistFunc_2DLine( P, Slope, FiltOptions ); [H, FiltOptions] = LFHelperBuild2DFreq( LFSize, BW, FiltOptions, DistFunc ); TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); end %----------------------------------------------------------------------------------------------------------------------- function Dist = DistFunc_2DLine( P, Slope, FiltOptions ) switch( lower(FiltOptions.SlopeMethod) ) case 'skew' R = eye(2); R(1,2) = Slope; case 'rotate' Angle = -atan2(Slope,1); R = LFRotz( Angle ); R = R(1:2,1:2); otherwise error('Unrecognized slope method'); end P = R * P; Dist = P(1,:).^2; end
github
hazirbas/light-field-toolbox-master
LFColourCorrect.m
.m
light-field-toolbox-master/LFToolbox0.4/LFColourCorrect.m
1,999
utf_8
07c213f4b7fbcaa5ad2fae5e30c82edf
% LFColourCorrect - applies a colour correction matrix, balance vector, and gamma, called by LFUtilDecodeLytroFolder % % Usage: % LF = LFColourCorrect( LF, ColMatrix, ColBalance, Gamma ) % % This implementation deals with saturated input pixels by aggressively saturating output pixels. % % Inputs : % % LF : a light field or image to colour correct. It should be a floating point array, and % may be of any dimensinality so long as the last dimension has length 3. For example, a 2D % image of size [Nl,Nk,3], a 4D image of size [Nj,Ni,Nl,Nk,3], and a 1D list of size [N,3] % are all valid. % % ColMatrix : a 3x3 colour conversion matrix. This can be built from the metadata provided % with Lytro imagery using the command: % ColMatrix = reshape(cell2mat(LFMetadata.image.color.ccmRgbToSrgbArray), 3,3); % as demonstrated in LFUtilDecodeLytroFolder. % % ColBalance : 3-element vector containing a multiplicative colour balance. % % Gamma : rudimentary gamma correction is applied of the form LF = LF.^Gamma. % % Outputs : % % LF, of the same dimensionality as the input. % % % See also: LFHistEqualize, LFUtilDecodeLytroFolder % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LF = LFColourCorrect(LF, ColMatrix, ColBalance, Gamma) LFSize = size(LF); % Flatten input to a flat list of RGB triplets NDims = numel(LFSize); LF = reshape(LF, [prod(LFSize(1:NDims-1)), 3]); LF = bsxfun(@times, LF, ColBalance); LF = LF * ColMatrix; % Unflatten result LF = reshape(LF, [LFSize(1:NDims-1),3]); % Saturating eliminates some issues with clipped pixels, but is aggressive and loses information % todo[optimization]: find a better approach to dealing with saturated pixels SaturationLevel = ColBalance*ColMatrix; SaturationLevel = min(SaturationLevel); LF = min(SaturationLevel,max(0,LF)) ./ SaturationLevel; % Apply gamma LF = LF .^ Gamma;
github
hazirbas/light-field-toolbox-master
LFBuild4DFreqPlane.m
.m
light-field-toolbox-master/LFToolbox0.4/LFBuild4DFreqPlane.m
4,768
utf_8
44b35c86e926ed95961fbf34e0872ffb
% LFBuild4DFreqPlane - construct a 4D planar passband filter in the frequency domain % % Usage: % % [H, FiltOptions] = LFBuild4DFreqPlane( LFSize, Slope, BW, FiltOptions ) % H = LFBuild4DFreqPlane( LFSize, Slope, BW ) % % This file constructs a real-valued magnitude response in 4D, for which the passband is a plane. % This is useful for selecting objects at a single depth from a lightfield, and is similar in effect % to refocus using, for example, the shift sum filter LFFiltShiftSum. % % Once constructed the filter must be applied to a light field, e.g. using LFFilt4DFFT. The % LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters. % % A more technical discussion, including the use of filters for denoising and volumetric focus, and % the inclusion of aliases components, is included in: % % [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field % Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015. % % Inputs: % % LFSize : Size of the frequency-domain filter. This should match or exceed the size of the % light field to be filtered. If it's larger than the input light field, the input is % zero-padded to match the filter's size by LFFilt4DFFT. % % Slope : The slope of the planar passband. If different slopes are desired in s,t and u,v, % the optional aspect parameter should be used. % % BW : 3-db Bandwidth of the planar passband. % % [optional] FiltOptions : struct controlling filter construction % SlopeMethod : 'Skew' or 'Rotate' default 'skew' % Precision : 'single' or 'double', default 'single' % Rolloff : 'Gaussian' or 'Butter', default 'Gaussian' % Order : controls the order of the filter when Rolloff is 'Butter', default 3 % Aspect4D : aspect ratio of the light field, default [1 1 1 1] % Window : Default false. By default the edges of the passband are sharp; this adds % a smooth rolloff at the edges when used in conjunction with Extent4D or % IncludeAliased. % Extent4D : controls where the edge of the passband occurs, the default [1 1 1 1] % is the edge of the Nyquist box. When less than 1, enabling windowing % introduces a rolloff after the edge of the passband. Can be greater % than 1 when using IncludeAliased. % IncludeAliased : default false; allows the passband to wrap around off the edge of the % Nyquist box; used in conjunction with Window and/or Extent4D. This can % increase processing time dramatically, e.g. Extent4D = [2,2,2,2] % requires a 2^4 = 16-fold increase in time to construct the filter. % Useful when passband content is aliased, see [2]. % % Outputs: % % H : real-valued frequency magnitude response % FiltOptions : The filter options including defaults, with an added PassbandInfo field % detailing the function and time of construction of the filter % % See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, % LFBuild2DFreqFan, LFBuild2DFreqLine, LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, % LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, LFFiltShiftSum % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [H, FiltOptions] = LFBuild4DFreqPlane( LFSize, Slope, BW, FiltOptions ) FiltOptions = LFDefaultField('FiltOptions', 'SlopeMethod', 'Skew'); % 'Skew', 'Rotate' DistFunc = @(P, FiltOptions) DistFunc_4DPlane( P, Slope, FiltOptions ); [H, FiltOptions] = LFHelperBuild4DFreq( LFSize, BW, FiltOptions, DistFunc ); TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); end %----------------------------------------------------------------------------------------------------------------------- function Dist = DistFunc_4DPlane( P, Slope, FiltOptions ) switch( lower(FiltOptions.SlopeMethod) ) case 'skew' R = eye(4); R(1,3) = Slope; R(2,4) = Slope; case 'rotate' Angle = -atan2(Slope,1); R2D = LFRotz( Angle ); R = eye(4); R(1,1) = R2D(1,1); R(1,3) = R2D(1,2); R(3,1) = R2D(2,1); R(3,3) = R2D(2,2); R(2,2) = R2D(1,1); R(2,4) = R2D(1,2); R(4,2) = R2D(2,1); R(4,4) = R2D(2,2); otherwise error('Unrecognized slope method'); end P = R * P; Dist = P(2,:).^2 + P(1,:).^2; end
github
hazirbas/light-field-toolbox-master
LFFindFilesRecursive.m
.m
light-field-toolbox-master/LFToolbox0.4/LFFindFilesRecursive.m
3,789
utf_8
d7e26a587e0dd5460fb2f59371802d2e
% LFFindFilesRecursive - Recursively searches a folder for files matching one or more patterns % % Usage: % % [AllFiles, BasePath, FolderList, PerFolderFiles] = LFFindFilesRecursive( InputPath ) % % Inputs: % % InputPath: the folder to recursively search % % Outputs: % % Allfiles : A list of all files found % BasePath : Top of the searched tree, excluding wildcards % FolderList : A list of all the folders explored % PerFolderFiles : A list of files organied by folder -- e.g. PerFolderFiles{1} are all the files % found in FolderList{1} % % Examples: % % LFFindFilesRecursive('Images') % LFFindFilesRecursive({'*.lfr','*.lfp'}) % LFFindFilesRecursive({'Images','*.lfr','*.lfp'}) % LFFindFilesRecursive('Images/*.lfr') % LFFindFilesRecursive('*.lfr') % LFFindFilesRecursive('Images/IMG_0001.LFR') % LFFindFilesRecursive('IMG_0001.LFR') % % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [AllFiles, BasePath, FolderList, PerFolderFiles] = LFFindFilesRecursive( InputPath, DefaultFileSpec, DefaultPath ) PerFolderFiles = []; AllFiles = []; %---Defaults--- DefaultFileSpec = LFDefaultVal( 'DefaultFileSpec', {'*'} ); DefaultPath = LFDefaultVal( 'DefaultPath', '.' ); InputPath = LFDefaultVal( 'InputPath', '.' ); PathOnly = ''; if( ~iscell(InputPath) ) InputPath = {InputPath}; end if( ~iscell(DefaultFileSpec) ) DefaultFileSpec = {DefaultFileSpec}; end InputFileSpec = DefaultFileSpec; if( exist(InputPath{1}, 'dir') ) % try interpreting first param as a folder, if it exists, grab is as such PathOnly = InputPath{1}; InputPath(1) = []; end if( numel(InputPath) > 0 ) % interpret remaining elements as filespecs % Check if the filespec includes a folder name, and crack it out as part of the input path [MorePath, Stripped, Ext] = fileparts(InputPath{1}); PathOnly = fullfile(PathOnly, MorePath); InputPath{1} = [Stripped,Ext]; InputFileSpec = InputPath; end PathOnly = LFDefaultVal('PathOnly', DefaultPath); InputPath = PathOnly; % Clean up the inputpath to omit trailing slashes while( InputPath(end) == filesep ) InputPath = InputPath(1:end-1); end BasePath = InputPath; %---Crawl folder structure locating raw lenslet images--- fprintf('Searching for files [ '); fprintf('%s ', InputFileSpec{:}); fprintf('] in %s\n', InputPath); %--- FolderList = genpath(InputPath); if( isempty(FolderList) ) error(['Input path not found... are you running from the correct folder? ' ... 'Current folder: %s'], pwd); end FolderList = textscan(FolderList, '%s', 'Delimiter', pathsep); FolderList = FolderList{1}; %---Compile a list of all files--- PerFolderFiles = cell(length(FolderList),1); for( iFileSpec=1:length(InputFileSpec) ) FilePattern = InputFileSpec{iFileSpec}; for( iFolder = 1:length(FolderList) ) %---Search each subfolder for raw lenslet files--- CurFolder = FolderList{iFolder}; CurDirList = dir(fullfile(CurFolder, FilePattern)); CurDirList = CurDirList(~[CurDirList.isdir]); CurDirList = {CurDirList.name}; PerFolderFiles{iFolder} = [PerFolderFiles{iFolder}, CurDirList]; % Prepend the current folder name for a complete path to each file % but fist strip off the leading InputPath so that all files are expressed relative to InputPath CurFolder = CurFolder(length(InputPath)+1:end); while( ~isempty(CurFolder) && CurFolder(1) == filesep ) CurFolder = CurFolder(2:end); end CurDirList = cellfun(@(Fname) fullfile(CurFolder, Fname), CurDirList, 'UniformOutput',false); AllFiles = [AllFiles; CurDirList']; end end
github
hazirbas/light-field-toolbox-master
LFDispMousePan.m
.m
light-field-toolbox-master/LFToolbox0.4/LFDispMousePan.m
3,147
utf_8
19664da990653623f36d25770af65dec
% LFDispMousePan - visualize a 4D light field using the mouse to pan through two dimensions % % Usage: % FigureHandle = LFDispMousePan( LF ) % FigureHandle = LFDispMousePan( LF, ScaleFactor ) % % A figure is set up for high-performance display, with the tag 'LFDisplay'. Subsequent calls to % this function and LFDispVidCirc will reuse the same figure, rather than creating a new window on % each call. The window should be closed when changing ScaleFactor. % % Inputs: % % LF : a colour or single-channel light field, and can a floating point or integer format. For % display, it is converted to 8 bits per channel. If LF contains more than three colour % channels, as is the case when a weight channel is present, only the first three are used. % % Optional Inputs: % % ScaleFactor : Adjusts the size of the display -- 1 means no change, 2 means twice as big, etc. % Integer values are recommended to avoid scaling artifacts. Note that the scale % factor is only applied the first time a figure is created. To change the scale % factor, close the figure before calling LFDispMousePan. % % Outputs: % % FigureHandle % % % See also: LFDisp, LFDispVidCirc % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function FigureHandle = LFDispMousePan( LF, varargin ) %---Defaults--- MouseRateDivider = 30; %---Check for weight channel--- HasWeight = (size(LF,5) == 4); %---Discard weight channel--- if( HasWeight ) LF = LF(:,:,:,:,1:3); end %---Rescale for 8-bit display--- if( isfloat(LF) ) LF = uint8(LF ./ max(LF(:)) .* 255); else LF = uint8(LF.*(255 / double(intmax(class(LF))))); end %---Setup the display--- [ImageHandle,FigureHandle] = LFDispSetup( squeeze(LF(max(1,floor(end/2)),max(1,floor(end/2)),:,:,:)), varargin{:} ); BDH = @(varargin) ButtonDownCallback(FigureHandle, varargin); BUH = @(varargin) ButtonUpCallback(FigureHandle, varargin); set(FigureHandle, 'WindowButtonDownFcn', BDH ); set(FigureHandle, 'WindowButtonUpFcn', BUH ); [TSize,SSize, ~,~] = size(LF(:,:,:,:,1)); CurX = max(1,floor((SSize-1)/2+1)); CurY = max(1,floor((TSize-1)/2+1)); DragStart = 0; %---Update frame before first mouse drag--- LFRender = squeeze(LF(round(CurY), round(CurX), :,:,:)); set(ImageHandle,'cdata', LFRender); fprintf('Click and drag to shift perspective\n'); function ButtonDownCallback(FigureHandle,varargin) set(FigureHandle, 'WindowButtonMotionFcn', @ButtonMotionCallback); DragStart = get(gca,'CurrentPoint')'; DragStart = DragStart(1:2,1)'; end function ButtonUpCallback(FigureHandle, varargin) set(FigureHandle, 'WindowButtonMotionFcn', ''); end function ButtonMotionCallback(varargin) CurPoint = get(gca,'CurrentPoint'); CurPoint = CurPoint(1,1:2); RelPoint = CurPoint - DragStart; CurX = max(1,min(SSize, CurX - RelPoint(1)/MouseRateDivider)); CurY = max(1,min(TSize, CurY - RelPoint(2)/MouseRateDivider)); DragStart = CurPoint; LFRender = squeeze(LF(round(CurY), round(CurX), :,:,:)); set(ImageHandle,'cdata', LFRender); end end
github
hazirbas/light-field-toolbox-master
LFReadGantryArray.m
.m
light-field-toolbox-master/LFToolbox0.4/LFReadGantryArray.m
4,902
utf_8
80dc406ff9c8008ff8aa0877a0fcdb0f
% LFReadGantryArray - load gantry-style light field, e.g. the Stanford light fields at lightfield.stanford.edu % % Usage: % % LF = LFReadGantryArray( InputPath, DecodeOptions ) % % To use, download and unzip an image archive from the Stanford light field archive, and pass this function the path to % the unzipped files. All inputs are optional, by default the light field is loaded from the current directory. % DecodeOptions.UVScale and DecodeOptions.UVLimit allow the input images to be scaled, either by the constant factor % UVScale, or to achieve the maximum u,v image size specified by UVLimit. If both UVScale and UVLimit are specified, the % one resulting in smaller images is applied. % % The defaults are all set to load Stanford Lego Gantry light fields, and must be adjusted for differently sized or % ordered light fields. % % Inputs : % % InputPath : path to folder of image files, e.g. as obtained by decompressing a Stanford light field % % DecodeOptions : % UVScale : constant scaling factor applied to each input image; default: 1 % UVLimit : scale is adjusted to ensure a maximum image dimension of DecodeOptions.UVLimit % Order : 'RowMajor' or 'ColumnMajor', specifies the order in which images appear when sorted % alphabetically; default: 'RowMajor' % STSize : Size of the array of images; default: [17, 17] % FnamePattern : Pattern used to locate input file, using standard wildcards; default '*.png' % % Outputs: % % LF : 5D array containing a 3-channel (RGB) light field, indexed in the order [j,i,l,k, colour] % DecodeOptions : Reflects the parameters as applied, including the UVScale resulting from UVLimit % % % Example 1: % % After unzipping the LegoKnights Stanford light fields into '~/Data/Stanford/LegoKnights/rectified', the following % reads the light field at full resolution, yielding a 17 x 17 x 1024 x 1024 x 3 array, occupying 909 MBytes of RAM: % % LF = LFReadGantryArray('~/Data/Stanford/LegoKnights/rectified'); % % Example 2: % % As above, but scales each image to a maximum dimension of 256 pixels, yielding a 17 x 17 x 256 x 256 x 3 array. % LFDIspMousePan then displays the light field, click and pan around to view the light field. % % LF = LFReadGantryArray('~/Data/Stanford/LegoKnights/rectified', struct('UVLimit', 256)); % LFDispMousePan(LF) % % Example 3: % % A few of the Stanford "Gantry" (not "Lego Gantry") light fields follow a lawnmower pattern. These can be read and % adjusted as follows: % % LF = LFReadGantryArray('humvee-tree', struct('STSize', [16,16])); % LF(1:2:end,:,:,:,:) = LF(1:2:end,end:-1:1,:,:,:); % See also: LFDispMousePan, LFDispVidCirc % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [LF, DecodeOptions] = LFReadGantryArray( InputPath, DecodeOptions ) InputPath = LFDefaultVal('InputPath', '.'); DecodeOptions = LFDefaultField('DecodeOptions','UVScale', 1); DecodeOptions = LFDefaultField('DecodeOptions','UVLimit', []); DecodeOptions = LFDefaultField('DecodeOptions','STSize', [17,17]); DecodeOptions = LFDefaultField('DecodeOptions','FnamePattern', '*.png'); DecodeOptions = LFDefaultField('DecodeOptions','Order', 'RowMajor'); %---Gather info--- FList = dir(fullfile(InputPath, DecodeOptions.FnamePattern)); if( isempty(FList) ) error('No files found'); end NumImgs = length(FList); assert( NumImgs == prod(DecodeOptions.STSize), 'Unexpected image count: expected %d x %d = %d found %d', ... DecodeOptions.STSize(1), DecodeOptions.STSize(2), prod(DecodeOptions.STSize), NumImgs ); %---Get size, scaling info from first file, assuming all are same size--- Img = imread(fullfile(InputPath, FList(1).name)); ImgClass = class(Img); UVSizeIn = size(Img); if( ~isempty(DecodeOptions.UVLimit) ) UVMinScale = min(DecodeOptions.UVLimit ./ UVSizeIn(1:2)); DecodeOptions.UVScale = min(DecodeOptions.UVScale, UVMinScale); end Img = imresize(Img, DecodeOptions.UVScale); UVSize = size(Img); TSize = DecodeOptions.STSize(2); SSize = DecodeOptions.STSize(1); VSize = UVSize(1); USize = UVSize(2); %---Allocate mem--- LF = zeros(TSize, SSize, VSize,USize, 3, ImgClass); LF(1,1,:,:,:) = Img; switch( lower(DecodeOptions.Order) ) case 'rowmajor' [SIdx,TIdx] = ndgrid( 1:SSize, 1:TSize ); case 'columnmajor' [TIdx,SIdx] = ndgrid( 1:TSize, 1:SSize ); otherwise error( 'Unrecognized image order' ); end %---Load and scale images--- fprintf('Loading %d images', NumImgs); for(i=2:NumImgs) if( mod(i, ceil(length(FList)/10)) == 0 ) fprintf('.'); end Img = imread(fullfile(InputPath, FList(i).name)); Img = imresize(Img, DecodeOptions.UVScale); LF(TIdx(i),SIdx(i),:,:,:) = Img; end fprintf(' done\n');
github
hazirbas/light-field-toolbox-master
LFRecenterIntrinsics.m
.m
light-field-toolbox-master/LFToolbox0.4/LFRecenterIntrinsics.m
599
utf_8
95e4073ad162508fcaf1705124873fc5
% LFRecenterIntrinsics - Recenter a light field intrinsic matrix % % Usage: % H = LFRecenterIntrinsics( H, LFSize ) % % The recentering works by forcing the central sample in a light field of LFSize samples to % correspond to the ray [s,t,u,v] = 0. Note that 1-based indexing is assumed in [i,j,k,l]. % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function H = LFRecenterIntrinsics( H, LFSize ) CenterRay = [(LFSize([2,1,4,3])-1)/2 + 1, 1]'; % note indices start at 1 H(1:4,5) = 0; Decentering = H * CenterRay; H(1:4,5) = -Decentering(1:4); end
github
hazirbas/light-field-toolbox-master
LFCalDispRectIntrinsics.m
.m
light-field-toolbox-master/LFToolbox0.4/LFCalDispRectIntrinsics.m
3,804
utf_8
9881daba2d9060eef02a39e1c9ac81dd
% LFCalDispRectIntrinsics - Visualize sampling pattern resulting from a prescribed intrinsic matrix % % Usage: % RectOptions = LFCalDispRectIntrinsics( LF, LFMetadata, RectOptions, PaintColour ) % % During rectification, the matrix RectOptions.RectCamIntrinsicsH determines which subset of the light field gets % sampled into the rectified light field. LFCalDispRectIntrinsics visualizes the resulting sampling pattern. The % display is interactive, generated using LFDispMousePan, and can be explored by clicking and dragging the mouse. % % If no intrinsic matrix is provided, a default best-guess is constructed and returned in % RectOptions.RectCamIntrinsicsH. % % A typical usage pattern is to load a light field, call LFCalDispRectIntrinsics to set up the default intrinsic % matrix, manipulate the matrix, then visualize the manipulated sampling pattern prior to employing it in one or more % rectification calls. The function LFRecenterIntrinsics is useful in maintaining a centered sampling pattern. % % This function relies on the presence of a calibration file and associated database, see LFUtilCalLensletCam and % LFUtilDecodeLytroFolder. % % Inputs: % % LF : Light field to visualize % % LFMetadata : The light field's associated metadata - needed to locate the appropriate calibration file % % [optional] RectOptions : all fields are optional, see LFCalRectifyLF for all fields % .RectCamIntrinsicsH : The intrinsic matrix to visualize % % [optional] PaintColour : RGB triplet defining a base drawing colour, RGB values are in the range 0-1 % % Outputs: % % RectOptions : RectOptions updated with any defaults that were applied % LF : The light field with visualized sample pattern % % See also: LFCalRectifyLF, LFRecenterIntrinsics, LFUtilCalLensletCam, LFUtilDecodeLytroFolder % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [RectOptions, LF] = LFCalDispRectIntrinsics( LF, LFMetadata, RectOptions, PaintColour ) PaintColour = LFDefaultVal( 'PaintColour', [0.5,1,1] ); [CalInfo, RectOptions] = LFFindCalInfo( LFMetadata, RectOptions ); %---Discard weight channel--- HasWeight = (size(LF,5) == 4); if( HasWeight ) LF = LF(:,:,:,:,1:3); end LFSize = size(LF); RectOptions = LFDefaultField( 'RectOptions', 'Precision', 'single' ); RectOptions = LFDefaultField( 'RectOptions', 'NInverse_Distortion_Iters', 2 ); RectOptions = LFDefaultField( 'RectOptions', 'RectCamIntrinsicsH', LFDefaultIntrinsics( LFSize, CalInfo ) ); if( isempty( CalInfo ) ) warning('No suitable calibration found, skipping'); return; end %--- visualize image utilization--- t_in=cast(1:LFSize(1), 'uint16'); s_in=cast(1:LFSize(2), 'uint16'); v_in=cast(1:10:LFSize(3), 'uint16'); u_in=cast(1:10:LFSize(4), 'uint16'); [tt,ss,vv,uu] = ndgrid(t_in,s_in,v_in,u_in); InterpIdx = [ss(:)'; tt(:)'; uu(:)'; vv(:)'; ones(size(ss(:)'))]; InterpIdx = LFMapRectifiedToMeasured( InterpIdx, CalInfo, RectOptions ); InterpIdx = round(double(InterpIdx)); PaintVal = cast(double(max(LF(:))).*PaintColour, 'like', LF); LF = 0.7*LF; %---Clamp indices--- STUVChan = [2,1,4,3]; for( Chan=1:4 ) InterpIdx(Chan,:) = min(LFSize(STUVChan(Chan)), max(1,InterpIdx(Chan,:))); end %---Paint onto LF--- RInterpIdx = sub2ind( LFSize, InterpIdx(2,:), InterpIdx(1,:), InterpIdx(4,:), InterpIdx(3,:), 1*ones(size(InterpIdx(1,:)))); LF(RInterpIdx) = PaintVal(1); RInterpIdx = sub2ind( LFSize, InterpIdx(2,:), InterpIdx(1,:), InterpIdx(4,:), InterpIdx(3,:), 2*ones(size(InterpIdx(1,:)))); LF(RInterpIdx) = PaintVal(2); RInterpIdx = sub2ind( LFSize, InterpIdx(2,:), InterpIdx(1,:), InterpIdx(4,:), InterpIdx(3,:), 3*ones(size(InterpIdx(1,:)))); LF(RInterpIdx) = PaintVal(3); %---Display LF--- LFDispMousePan( LF );
github
hazirbas/light-field-toolbox-master
LFFiltShiftSum.m
.m
light-field-toolbox-master/LFToolbox0.4/LFFiltShiftSum.m
5,666
utf_8
08be7f6f27c502a03f85f49912ae8183
% LFFiltShiftSum - a spatial-domain depth-selective filter, with an effect similar to planar focus % % Usage: % % [ImgOut, FiltOptions, LF] = LFFiltShiftSum( LF, Slope, FiltOptions ) % ImgOut = LFFiltShiftSum( LF, Slope ) % % % This filter works by shifting all u,v slices of the light field to a common depth, then adding the slices together to % yield a single 2D output. The effect is very similar to planar focus, and by controlling the amount of shift one may % focus on different depths. If a weight channel is present in the light field it gets used during normalization. % % % See LFDemoBasicFiltLytro for example usage. % % % Inputs % % LF : The light field to be filtered % % Slope : The amount by which light field slices should be shifted, this encodes the depth at which the output will % be focused. The relationship between slope and depth depends on light field parameterization, but in % general a slope of 0 lies near the center of the captured depth of field. % % [optional] FiltOptions : struct controlling filter operation % Precision : 'single' or 'double', default 'single' % Aspect4D : aspect ratio of the light field, default [1 1 1 1] % Normalize : default true; when enabled the output is normalized so that darkening near image edges is % removed % FlattenMethod : 'Sum', 'Max' or 'Median', default 'Sum'; when the shifted light field slices are combined, % they are by default added together, but median and max can also yield useful results. % InterpMethod : default 'linear'; this is passed on to interpn to determine how shifted light field slices % are found; other useful settings are 'nearest', 'cubic' and 'spline' % ExtrapVal : default 0; when shifting light field slices, pixels falling outside the input light field % are set to this value % MinWeight : during normalization, pixels for which the output value is not well defined (i.e. for % which the filtered weight is very low) get set to 0. MinWeight sets the threshold at which % this occurs, default is 10 * the numerical precision of the output, as returned by eps % % Outputs: % % ImgOut : A 2D filtered image % FiltOptions : The filter options including defaults, with an added FilterInfo field detailing the function and % time of filtering. % LF : The 4D light field resulting from the shifting operation % % See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, LFBuild2DFreqFan, LFBuild2DFreqLine, % LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, % LFFiltShiftSum % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [ImgOut, FiltOptions, LF] = LFFiltShiftSum( LF, Slope, FiltOptions ) FiltOptions = LFDefaultField('FiltOptions', 'Precision', 'single'); FiltOptions = LFDefaultField('FiltOptions', 'Normalize', true); FiltOptions = LFDefaultField('FiltOptions', 'MinWeight', 10*eps(FiltOptions.Precision)); FiltOptions = LFDefaultField('FiltOptions', 'Aspect4D', 1); FiltOptions = LFDefaultField('FiltOptions', 'FlattenMethod', 'sum'); % 'Sum', 'Max', 'Median' FiltOptions = LFDefaultField('FiltOptions', 'InterpMethod', 'linear'); FiltOptions = LFDefaultField('FiltOptions', 'ExtrapVal', 0); if( length(FiltOptions.Aspect4D) == 1 ) FiltOptions.Aspect4D = FiltOptions.Aspect4D .* [1,1,1,1]; end LFSize = size(LF); NColChans = size(LF,5); HasWeight = ( NColChans == 4 || NColChans == 2 ); if( HasWeight ) NColChans = NColChans-1; end LF = LFConvertToFloat(LF, FiltOptions.Precision); %--- if( FiltOptions.Normalize ) if( HasWeight ) for( iColChan = 1:NColChans ) LF(:,:,:,:,iColChan) = LF(:,:,:,:,iColChan) .* LF(:,:,:,:,end); end else % add a weight channel LF(:,:,:,:,end+1) = ones(size(LF(:,:,:,:,1)), FiltOptions.Precision); end end %--- TVSlope = Slope * FiltOptions.Aspect4D(3) / FiltOptions.Aspect4D(1); SUSlope = Slope * FiltOptions.Aspect4D(4) / FiltOptions.Aspect4D(2); [vv, uu] = ndgrid(1:LFSize(3), 1:LFSize(4)); VVec = linspace(-0.5,0.5, LFSize(1)) * TVSlope*LFSize(1); UVec = linspace(-0.5,0.5, LFSize(2)) * SUSlope*LFSize(2); for( TIdx = 1:LFSize(1) ) VOffset = VVec(TIdx); for( SIdx = 1:LFSize(2) ) UOffset = UVec(SIdx); for( iChan=1:size(LF,5) ) CurSlice = squeeze(LF(TIdx, SIdx, :,:, iChan)); CurSlice = interpn(CurSlice, vv+VOffset, uu+UOffset, FiltOptions.InterpMethod, FiltOptions.ExtrapVal); LF(TIdx,SIdx, :,:, iChan) = CurSlice; end end fprintf('.'); end switch( lower(FiltOptions.FlattenMethod) ) case 'sum' ImgOut = squeeze(sum(sum(LF,1),2)); case 'max' ImgOut = squeeze(max(max(LF,[],1),[],2)); case 'median' t = reshape(LF, [prod(LFSize(1:2)), LFSize(3:end)]); ImgOut = squeeze(median(t)); otherwise error('Unrecognized method'); end %--- if( FiltOptions.Normalize ) WeightChan = ImgOut(:,:,end); InvalidIdx = find(WeightChan < FiltOptions.MinWeight); ChanSize = numel(ImgOut(:,:,1)); for( iColChan = 1:NColChans ) ImgOut(:,:,iColChan) = ImgOut(:,:,iColChan) ./ WeightChan; ImgOut( InvalidIdx + ChanSize.*(iColChan-1) ) = 0; end end TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); FiltOptions.FilterInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
github
hazirbas/light-field-toolbox-master
LFUtilUnpackLytroArchive.m
.m
light-field-toolbox-master/LFToolbox0.4/LFUtilUnpackLytroArchive.m
5,667
utf_8
0af0d42eaef631b6f44fbfc81dd81b3e
% LFUtilUnpackLytroArchive - extract white images and other files from a multi-volume Lytro archive % % Usage: % LFUtilUnpackLytroArchive % LFUtilUnpackLytroArchive( InputPath ) % LFUtilUnpackLytroArchive( InputPath, FirstVolumeFname ) % LFUtilUnpackLytroArchive( [], FirstVolumeFname ) % % This extracts all the files from all Lytro archives found in the requested path. Archives typically take on names like % data.C.0, data.C.1 and so forth, and contain white images, metadata and other information. % % The function searches for archives recursively, so if there are archives in multiple sub-folders, they will all be % expanded. The file LFToolbox.json is created to mark completion of the extraction in a folder. Already-expanded % archives are skipped; delete LFToolbox.json to force re-extraction in a folder. % % Based in part on Nirav Patel and Doug Kelley's LFP readers. Thanks to Michael Tao for help and samples for decoding % Illum imagery. % % Inputs -- all are optional : % % InputPath : Path to folder containing the archive, default 'Cameras' % FirstVolumeFname : Name of the first file in the archive, default 'data.C.0' % % Example: % % LFUtilUnpackLytroArchive % % Will extract the contents of all archives in all subfolders of the current folder. If you are working with % multiple cameras, place each multi-volume archve in its own sub-folder, then call this from the top-level folder % to expand them all. % % See also: LFUtilProcessWhiteImages, LFReadLFP, LFUtilExtractLFPThumbs % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LFUtilUnpackLytroArchive( InputPath, FirstVolumeFname ) %---Defaults--- InputPath = LFDefaultVal('InputPath','Cameras'); FirstVolumeFname = LFDefaultVal('FirstVolumeFname','data.C.0'); [AllVolumes, BasePath] = LFFindFilesRecursive(InputPath, FirstVolumeFname); fprintf('Found :\n'); disp(AllVolumes) %---Consts--- LFPConsts.LFPHeader = hex2dec({'89', '4C', '46', '50', '0D', '0A', '1A', '0A', '00', '00', '00', '01'}); % 12-byte LFPSections header LFPConsts.SectHeaderLFM = hex2dec({'89', '4C', '46', '4D', '0D', '0A', '1A', '0A'})'; % header for table of contents LFPConsts.SectHeaderLFC = hex2dec({'89', '4C', '46', '43', '0D', '0A', '1A', '0A'})'; % header for content section LFPConsts.SecHeaderPaddingLen = 4; LFPConsts.Sha1Length = 45; LFPConsts.ShaPaddingLen = 35; % Sha1 codes are followed by 35 null bytes LFToolboxInfoFname = 'LFToolbox.json'; %--- for( VolumeIdx = 1:length(AllVolumes) ) CurFile = fullfile(BasePath, AllVolumes{VolumeIdx}); OutPath = fileparts(CurFile); fprintf('Extracting files in "%s"...\n', OutPath); CurInfoFname = fullfile( OutPath, LFToolboxInfoFname ); if( exist(CurInfoFname, 'file') ) fprintf('Already done, skipping (delete "%s" to force redo)\n\n', CurInfoFname); continue; end while( 1 ) fprintf(' %s...\n', CurFile); InFile=fopen(CurFile, 'rb'); %---Check for the magic header--- HeaderBytes = fread( InFile, length(LFPConsts.LFPHeader), 'uchar' ); if( ~all( HeaderBytes == LFPConsts.LFPHeader ) ) fclose(InFile); fprintf( 'Unrecognized file type' ); return end %---Confirm headerlength bytes--- HeaderLength = fread(InFile,1,'uint32','ieee-be'); assert( HeaderLength == 0, 'Unexpected length at top-level header' ); %---Read each section--- % This implementation assumes the TOC appears first in each file clear TOC while( ~feof(InFile) ) CurSection = ReadSection( InFile, LFPConsts ); if( all( CurSection.SectHeader == LFPConsts.SectHeaderLFM ) ) TOC = LFReadMetadata( CurSection.Data ); else assert( exist('TOC','var')==1, 'Expected to find table of contents at top of file' ); MatchingSectIdx = find( strcmp( CurSection.Sha1, {TOC.files.dataRef} ) ); CurFname = TOC.files(MatchingSectIdx).name; CurFname = strrep( CurFname, 'C:\', '' ); CurFname = strrep( CurFname, '\', '__' ); OutFile = fopen( fullfile(OutPath, CurFname), 'wb' ); fwrite( OutFile, CurSection.Data ); fclose(OutFile); end end fclose( InFile ); if( isfield(TOC, 'nextFile') ) CurFile = fullfile(OutPath, TOC.nextFile); else break; end end TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); fprintf( 'Marking completion in "%s"\n\n', CurInfoFname ); LFWriteMetadata( CurInfoFname, GeneratedByInfo ); end fprintf('Done\n'); end % -------------------------------------------------------------------- function LFPSect = ReadSection( InFile, LFPConsts ) LFPSect.SectHeader = fread(InFile, length(LFPConsts.SectHeaderLFM), 'uchar')'; Padding = fread(InFile, LFPConsts.SecHeaderPaddingLen, 'uint8'); % skip padding SectLength = fread(InFile, 1, 'uint32', 'ieee-be'); LFPSect.Sha1 = char(fread(InFile, LFPConsts.Sha1Length, 'uchar')'); Padding = fread(InFile, LFPConsts.ShaPaddingLen, 'uint8'); % skip padding LFPSect.Data = char(fread(InFile, SectLength, 'uchar'))'; while( 1 ) Padding = fread(InFile, 1, 'uchar'); if( feof(InFile) || (Padding ~= 0) ) break; end end if ~feof(InFile) fseek( InFile, -1, 'cof'); % rewind one byte end end
github
hazirbas/light-field-toolbox-master
LFReadMetadata.m
.m
light-field-toolbox-master/LFToolbox0.4/LFReadMetadata.m
14,953
utf_8
98e987806e2f748e70644b1801d2bf95
% LFReadMetadata - reads the metadata files in the JSON file format, from a file or a char buffer % % Usage: % % Data = LFReadMetadata( JsonFileFname ) % % This function parses a JSON file and returns the data contained therein. If a char buffer is passed in, it's % interpreted directly. % % Based on code from JSONlab by Qianqian Fang, % http://www.mathworks.com.au/matlabcentral/fileexchange/33381-jsonlab-a-toolbox-to-encodedecode-json-files-in-matlaboctave % % Minor modifications by Donald G. Dansereau, 2013, to simplify the interface as appropriate for use % in the Light Field Toolbox, and to tolerate the sha keys appearing at the end of some Lytro JSON % files % % See also: LFWriteMetadata % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function data = LFReadMetadata( JsonFileFname ) global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(JsonFileFname,'[\{\}\]\[]','once')) string=JsonFileFname; elseif(exist(JsonFileFname,'file')) fid = fopen(JsonFileFname,'rt'); string = fscanf(fid,'%c'); fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt = []; % opt=varargin2struct(varargin{:}); jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise pos = len+1; continue; % error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); else ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; if next_char ~= ']' [endpos e1l e1r maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(find(arraystr==sprintf('\n')))=[]; arraystr(find(arraystr==sprintf('\r')))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(find(astr==sprintf('\n')))=[]; astr(find(astr==sprintf('\r')))=[]; astr(find(astr==' '))=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(find(astr==' '))=''; [obj count errmsg nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(find(astr=='['))=''; astr(find(astr==']'))=''; astr(find(astr==' '))=''; [obj count errmsg nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end try object=cell2mat(object')'; if(size(object,1)>1 && ndims(object)==2) object=object'; end catch end parse_char(']'); %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
hazirbas/light-field-toolbox-master
LFUtilDecodeLytroFolder.m
.m
light-field-toolbox-master/LFToolbox0.4/LFUtilDecodeLytroFolder.m
16,946
utf_8
6867204a9b31f8807a667ab1fe4fa420
% LFUtilDecodeLytroFolder - decode and optionally colour correct and rectify Lytro light fields % % Usage: % % LFUtilDecodeLytroFolder % LFUtilDecodeLytroFolder( InputPath ) % LFUtilDecodeLytroFolder( InputPath, FileOptions, DecodeOptions, RectOptions ) % LFUtilDecodeLytroFolder( InputPath, [], [], RectOptions ) % % All parameters are optional and take on default values as set in the "Defaults" section at the top % of the implementation. As such, this can be called as a function or run directly by editing the % code. When calling as a function, pass an empty array "[]" to omit a parameter. % % As released, the default values are set up to match the naming conventions of LFP Reader v2.0.0. % % This function demonstrates decoding and optionally colour-correction and rectification of 2D % lenslet images into 4D light fields. It recursively crawls through a prescribed folder and its % subfolders, operating on each light field. It can be used incrementally: previously-decoded light % fields can be subsequently colour-corected, rectified, or both. Previously-completed tasks will % not be re-applied. A filename pattern can be provided to work on individual files. All paths and % naming are configurable. % % Decoding and rectification follow the process described in: % % [1] D. G. Dansereau, O. Pizarro, and S. B. Williams, "Decoding, calibration and rectification for % lenslet-based plenoptic cameras," in Computer Vision and Pattern Recognition (CVPR), IEEE % Conference on. IEEE, Jun 2013. % % Decoding requires that an appropriate database of white images be created using % LFUtilProcessWhiteImages. Rectification similarly requires a calibration database be created using % LFUtilProcessCalibrations. % % To decode a single light field, it is simplest to include a file specification in InputPath (see % below). It is also possible to call LFLytroDecodeImage directly. % % Colour correction employs the metadata associated with each Lytro picture. It also applies % histogram-based contrast adjustment. It calls the functions LFColourCorrect and LFHistEqualize. % % Rectification employs a calibration info file to rectify the light field, correcting for lens % distortion, making pixels square, and yielding an intrinsics matrix which allows easy conversion % from a pixel index [i,j,k,l] to a ray [s,t,u,v]. A calibration info file is generated by % processing a series of checkeboard images, following the calibration procedure described in % LFToolbox.pdf. A calibration only applies to one specific camera at one specific zoom and focus % setting, and decoded using one specific lenslet grid model. The tool LFUtilProcessCalibrations is % used to build a database of rectifications, and LFSelectFromDatabase isused to select a % calibration appropriate to a given light field. % % This function was written to deal with Lytro imagery, but adapting it to operate with other % lenslet-based cameras should be straightforward. For more information on the decoding process, % refer to LFDecodeLensletImageSimple, [1], and LFToolbox.pdf. % % Some optional parameters are not used or documented at this level -- see each of LFCalRectifyLF, % LFLytroDecodeImage, LFDecodeLensletImageSimple, and LFColourCorrect for further information. % % % Inputs -- all are optional, see code below for default values : % % InputPath : Path to folder containing light fields, or to a specific light field, optionally including one or % more wildcard filename specifications. In case wildcards are used, this searches sub-folders recursively. See % LFFindFilesRecursive.m for more information and examples of how InputPath is interpreted. % % FileOptions : struct controlling file naming and saving % .SaveResult : Set to false to perform a "dry run" % .ForceRedo : If true previous results are ignored and decoding starts from scratch % .SaveFnamePattern : String defining the pattern used in generating the output filename; % sprintf is used to complete this pattern, such that %s gets replaced % with the base name of the input light field % .ThumbFnamePattern : As with SaveFnamePattern, defines the name of the output thumbnail % image % % DecodeOptions : struct controlling the decoding process, see LFDecodeLensletImageSimple for more info % .OptionalTasks : Cell array containing any combination of 'ColourCorrect' and % 'Rectify'; an empty array "{}" means no additional tasks are % requested; case sensitive % .LensletImageFnamePattern : Pattern used to locate input files -- the pattern %s stands in % for the base filename % .ColourHistThresh : Threshold used by LFHistEqualize in optional colour correction % .WhiteImageDatabasePath : Full path to the white images database, as created by % LFUtilProcessWhiteImages % .DoDehex : Controls whether hexagonal sampling is converted to rectangular, default true % .DoSquareST : Controls whether s,t dimensions are resampled to square pixels, default true % .ResampMethod : 'fast'(default) or 'triangulation' % .LevelLimits : a two-element vector defining the black and white levels % .Precision : 'single'(default) or 'double' % % RectOptions : struct controlling the optional rectification process % .CalibrationDatabaseFname : Full path to the calibration file database, as created by % LFUtilProcessCalibrations; % % Example: % % LFUtilDecodeLytroFolder % % Run from the top level of the 'Samples' folder will decode all the light fields in all the % sub-folders, with default settings as set up in the opening section of the code. The % calibration database created by LFUtilProcessWhiteImages is expected to be in % 'Cameras/CaliCalibrationDatabase.mat' by default. % % LFUtilDecodeLytroFolder('Images', [], struct('OptionalTasks', 'ColourCorrect')) % % Run from the top level of the 'Samples' folder will decode and colour correct all light fields in the Images % folder and its sub-folders. % % DecodeOptions.OptionalTasks = {'ColourCorrect', 'Rectify'}; % LFUtilDecodeLytroFolder([], [], DecodeOptions) % % Will perform both colour correction and rectification in the Images folder. % % LFUtilDecodeLytroFolder('Images/Illum/Lorikeet.lfp') % LFUtilDecodeLytroFolder('Lorikeet.lfp') % LFUtilDecodeLytroFolder({'Images', '*Hiding*', 'Jacaranda*'}) % LFUtilDecodeLytroFolder('*.raw') % LFUtilDecodeLytroFolder({'*0002*', '*0003*'}) % % Any of these, run from the top level of the 'Samples' folder, will decode the matching files. See % LFFindFilesRecursive. % % See also: LFUtilExtractLFPThumbs, LFUtilProcessWhiteImages, LFUtilProcessCalibrations, LFUtilCalLensletCam, % LFColourCorrect, LFHistEqualize, LFFindFilesRecursive, LFLytroDecodeImage, LFDecodeLensletImageSimple, % LFSelectFromDatabase % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LFUtilDecodeLytroFolder( InputPath, FileOptions, DecodeOptions, RectOptions ) %---Defaults--- InputPath = LFDefaultVal( 'InputPath', 'Images' ); FileOptions = LFDefaultField('FileOptions', 'SaveResult', true); FileOptions = LFDefaultField('FileOptions', 'ForceRedo', false); FileOptions = LFDefaultField('FileOptions', 'SaveFnamePattern', '%s__Decoded.mat'); FileOptions = LFDefaultField('FileOptions', 'ThumbFnamePattern', '%s__Decoded_Thumb.png'); DecodeOptions = LFDefaultField('DecodeOptions', 'OptionalTasks', {}); % 'ColourCorrect', 'Rectify' DecodeOptions = LFDefaultField('DecodeOptions', 'ColourHistThresh', 0.01); DecodeOptions = LFDefaultField(... 'DecodeOptions', 'WhiteImageDatabasePath', fullfile('Cameras','WhiteImageDatabase.mat')); RectOptions = LFDefaultField(... 'RectOptions', 'CalibrationDatabaseFname', fullfile('Cameras','CalibrationDatabase.mat')); % Used to decide if two lenslet grid models are "close enough"... if they're not a warning is raised RectOptions = LFDefaultField( 'RectOptions', 'MaxGridModelDiff', 1e-5 ); % Massage a single-element OptionalTasks list to behave as a cell array while( ~iscell(DecodeOptions.OptionalTasks) ) DecodeOptions.OptionalTasks = {DecodeOptions.OptionalTasks}; end %---Crawl folder structure locating raw lenslet images--- DefaultFileSpec = {'*.lfr', '*.lfp', '*.LFR', '*.raw'}; % gets overriden below, if a file spec is provided DefaultPath = 'Images'; [FileList, BasePath] = LFFindFilesRecursive( InputPath, DefaultFileSpec, DefaultPath ); fprintf('Found :\n'); disp(FileList) %---Process each raw lenslet file--- % Store options so we can reset them for each file OrigDecodeOptions = DecodeOptions; OrigRectOptions = RectOptions; for( iFile = 1:length(FileList) ) SaveRequired = false; %---Start from orig options, avoids values bleeding between iterations--- DecodeOptions = OrigDecodeOptions; RectOptions = OrigRectOptions; %---Find current / base filename--- CurFname = FileList{iFile}; CurFname = fullfile(BasePath, CurFname); % Build filename base without extension, auto-remove '__frame' for legacy .raw format LFFnameBase = CurFname; [~,~,Extension] = fileparts(LFFnameBase); LFFnameBase = LFFnameBase(1:end-length(Extension)); CullIdx = strfind(LFFnameBase, '__frame'); if( ~isempty(CullIdx) ) LFFnameBase = LFFnameBase(1:CullIdx-1); end fprintf('\n---%s [%d / %d]...\n', CurFname, iFile, length(FileList)); %---Decode--- fprintf('Decoding...\n'); % First check if a decoded file already exists [SDecoded, FileExists, CompletedTasks, TasksRemaining, SaveFname] = CheckIfExists( ... LFFnameBase, DecodeOptions, FileOptions.SaveFnamePattern, FileOptions.ForceRedo ); if( ~FileExists ) % No previous result, decode [LF, LFMetadata, WhiteImageMetadata, LensletGridModel, DecodeOptions] = ... LFLytroDecodeImage( CurFname, DecodeOptions ); if( isempty(LF) ) continue; end fprintf('Decode complete\n'); SaveRequired = true; elseif( isempty(TasksRemaining) ) % File exists, and nothing more to do continue; else % File exists and tasks remain: unpack previous decoding results [LF, LFMetadata, WhiteImageMetadata, LensletGridModel, DecodeOptions] = LFStruct2Var( ... SDecoded, 'LF', 'LFMetadata', 'WhiteImageMetadata', 'LensletGridModel', 'DecodeOptions' ); clear SDecoded end %---Display thumbnail--- Thumb = DispThumb(LF, CurFname, CompletedTasks); %---Optionally colour correct--- if( ismember( 'ColourCorrect', TasksRemaining ) ) LF = ColourCorrect( LF, LFMetadata, DecodeOptions ); CompletedTasks = [CompletedTasks, 'ColourCorrect']; SaveRequired = true; fprintf('Done\n'); %---Display thumbnail--- Thumb = DispThumb(LF, CurFname, CompletedTasks); end %---Optionally rectify--- if( ismember( 'Rectify', TasksRemaining ) ) [LF, RectOptions, Success] = Rectify( LF, LFMetadata, DecodeOptions, RectOptions, LensletGridModel ); if( Success ) CompletedTasks = [CompletedTasks, 'Rectify']; SaveRequired = true; end %---Display thumbnail--- Thumb = DispThumb(LF, CurFname, CompletedTasks); end %---Check that all tasks are completed--- UncompletedTaskIdx = find(~ismember(TasksRemaining, CompletedTasks)); if( ~isempty(UncompletedTaskIdx) ) UncompletedTasks = []; for( i=UncompletedTaskIdx ) UncompletedTasks = [UncompletedTasks, ' ', TasksRemaining{UncompletedTaskIdx}]; end warning(['Could not complete all tasks requested in DecodeOptions.OptionalTasks: ', UncompletedTasks]); end DecodeOptions.OptionalTasks = CompletedTasks; %---Optionally save--- if( SaveRequired && FileOptions.SaveResult ) if( isfloat(LF) ) LF = uint16( LF .* double(intmax('uint16')) ); end ThumbFname = sprintf(FileOptions.ThumbFnamePattern, LFFnameBase); fprintf('Saving to:\n\t%s,\n\t%s...\n', SaveFname, ThumbFname); TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); save('-v7.3', SaveFname, 'GeneratedByInfo', 'LF', 'LFMetadata', 'WhiteImageMetadata', 'LensletGridModel', 'DecodeOptions', 'RectOptions'); imwrite(Thumb, ThumbFname); end end end %--------------------------------------------------------------------------------------------------- function [SDecoded, FileExists, CompletedTasks, TasksRemaining, SaveFname] = ... CheckIfExists( LFFnameBase, DecodeOptions, SaveFnamePattern, ForceRedo ) SDecoded = []; FileExists = false; SaveFname = sprintf(SaveFnamePattern, LFFnameBase); if( ~ForceRedo && exist(SaveFname, 'file') ) %---Task previously completed, check if there's more to do--- FileExists = true; fprintf( ' %s already exists\n', SaveFname ); PrevDecodeOptions = load( SaveFname, 'DecodeOptions' ); PrevOptionalTasks = PrevDecodeOptions.DecodeOptions.OptionalTasks; CompletedTasks = PrevOptionalTasks; TasksRemaining = find(~ismember(DecodeOptions.OptionalTasks, PrevOptionalTasks)); if( ~isempty(TasksRemaining) ) %---Additional tasks remain--- TasksRemaining = {DecodeOptions.OptionalTasks{TasksRemaining}}; % by name fprintf(' Additional tasks remain, loading existing file...\n'); SDecoded = load( SaveFname ); AllTasks = [SDecoded.DecodeOptions.OptionalTasks, TasksRemaining]; SDecoded.DecodeOptions.OptionalTasks = AllTasks; %---Convert to float as this is what subsequent operations require--- OrigClass = class(SDecoded.LF); SDecoded.LF = cast( SDecoded.LF, SDecoded.DecodeOptions.Precision ) ./ ... cast( intmax(OrigClass), SDecoded.DecodeOptions.Precision ); fprintf('Done\n'); else %---No further tasks... move on--- fprintf( ' No further tasks requested\n'); TasksRemaining = {}; end else %---File doesn't exist, all tasks remain--- TasksRemaining = DecodeOptions.OptionalTasks; CompletedTasks = {}; end end %--------------------------------------------------------------------------------------------------- function Thumb = DispThumb( LF, CurFname, CompletedTasks) Thumb = squeeze(LF(floor(end/2),floor(end/2),:,:,:)); % including weight channel for hist equalize Thumb = uint8(LFHistEqualize(Thumb).*double(intmax('uint8'))); Thumb = Thumb(:,:,1:3); % strip off weight channel LFDispSetup(Thumb); Title = CurFname; for( i=1:length(CompletedTasks) ) Title = [Title, ', ', CompletedTasks{i}]; end title(Title, 'Interpreter', 'none'); drawnow end %--------------------------------------------------------------------------------------------------- function LF = ColourCorrect( LF, LFMetadata, DecodeOptions ) fprintf('Applying colour correction... '); %---Weight channel is not used by colour correction, so strip it out--- LFWeight = LF(:,:,:,:,4); LF = LF(:,:,:,:,1:3); %---Apply the color conversion and saturate--- LF = LFColourCorrect( LF, DecodeOptions.ColourMatrix, DecodeOptions.ColourBalance, DecodeOptions.Gamma ); %---Put the weight channel back--- LF(:,:,:,:,4) = LFWeight; end %--------------------------------------------------------------------------------------------------- function [LF, RectOptions, Success] = Rectify( LF, LFMetadata, DecodeOptions, RectOptions, LensletGridModel ) Success = false; fprintf('Applying rectification... '); %---Load cal info--- fprintf('Selecting calibration...\n'); [CalInfo, RectOptions] = LFFindCalInfo( LFMetadata, RectOptions ); if( isempty( CalInfo ) ) warning('No suitable calibration found, skipping'); return; end %---Compare structs a = CalInfo.LensletGridModel; b = LensletGridModel; a.Orientation = strcmp(a.Orientation, 'horz'); b.Orientation = strcmp(b.Orientation, 'horz'); FractionalDiff = abs( (struct2array(a) - struct2array(b)) ./ struct2array(a) ); if( ~all( FractionalDiff < RectOptions.MaxGridModelDiff ) ) warning(['Lenslet grid models differ -- ideally the same grid model and white image are ' ... ' used to decode during calibration and rectification']); end %---Perform rectification--- [LF, RectOptions] = LFCalRectifyLF( LF, CalInfo, RectOptions ); Success = true; end
github
hazirbas/light-field-toolbox-master
LFFilt4DFFT.m
.m
light-field-toolbox-master/LFToolbox0.4/LFFilt4DFFT.m
3,622
utf_8
bb1d9662c072ab5fb38568d45f44bd28
% LFFilt4DFFT -Applies a 4D frequency-domain filter using the FFT % % Usage: % % [LF, FiltOptions] = LFFilt4DFFT( LF, H, FiltOptions ) % LF = LFFilt4DFFT( LF, H ) % % % This filter works by taking the FFT of the input light field, multiplying by the provided magnitude response H, then % calling the inverse FFT. The frequency-domain filter H should match or exceed the size of the light field LF. If H is % larger than the input light field, LF is zero-padded to match the filter's size. If a weight channel is present in % the light field it gets used during normalization. % % See LFDemoBasicFiltLytro for example usage. % % % Inputs % % LF : The light field to be filtered % % H : The frequency-domain filter to apply, as constructed by one of the LFBuild4DFreq* functions % % [optional] FiltOptions : struct controlling filter operation % Precision : 'single' or 'double', default 'single' % Normalize : default true; when enabled the output is normalized so that darkening near image edges is % removed % MinWeight : during normalization, pixels for which the output value is not well defined (i.e. for % which the filtered weight is very low) get set to 0. MinWeight sets the threshold at which % this occurs, default is 10 * the numerical precision of the output, as returned by eps % % Outputs: % % LF : The filtered 4D light field % FiltOptions : The filter options including defaults, with an added FilterInfo field detailing the function and % time of filtering. % % See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, LFBuild2DFreqFan, LFBuild2DFreqLine, % LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, % LFFiltShiftSum % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [LF, FiltOptions] = LFFilt4DFFT( LF, H, FiltOptions ) FiltOptions = LFDefaultField('FiltOptions', 'Precision', 'single'); FiltOptions = LFDefaultField('FiltOptions', 'Normalize', true); FiltOptions = LFDefaultField('FiltOptions', 'MinWeight', 10*eps(FiltOptions.Precision)); %--- NColChans = size(LF,5); HasWeight = ( NColChans == 4 || NColChans == 2 ); HasColour = ( NColChans == 4 || NColChans == 3 ); if( HasWeight ) NColChans = NColChans-1; end %--- LFSize = size(LF); LFPaddedSize = size(H); LF = LFConvertToFloat(LF, FiltOptions.Precision); if( FiltOptions.Normalize ) if( HasWeight ) for( iColChan = 1:NColChans ) LF(:,:,:,:,iColChan) = LF(:,:,:,:,iColChan) .* LF(:,:,:,:,end); end else % add a weight channel LF(:,:,:,:,end+1) = ones(size(LF(:,:,:,:,1)), FiltOptions.Precision); end end SliceSize = size(LF); for( iColChan = 1:SliceSize(end) ) fprintf('.'); X = fftn(LF(:,:,:,:,iColChan), LFPaddedSize); X = X .* H; x = ifftn(X,'symmetric'); x = x(1:LFSize(1), 1:LFSize(2), 1:LFSize(3), 1:LFSize(4)); LF(:,:,:,:,iColChan) = x; end if( FiltOptions.Normalize ) WeightChan = LF(:,:,:,:,end); InvalidIdx = find(WeightChan <= FiltOptions.MinWeight); ChanSize = numel(LF(:,:,:,:,1)); for( iColChan = 1:NColChans ) LF(:,:,:,:,iColChan) = LF(:,:,:,:,iColChan) ./ WeightChan; LF( InvalidIdx + ChanSize.*(iColChan-1) ) = 0; end end LF = max(0,LF); LF = min(1,LF); %--- TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); FiltOptions.FilterInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); fprintf(' Done\n');
github
hazirbas/light-field-toolbox-master
LFUtilCalLensletCam.m
.m
light-field-toolbox-master/LFToolbox0.4/LFUtilCalLensletCam.m
8,438
utf_8
56382b29c1b601dbae1ec2d6763a51b0
% LFUtilCalLensletCam - calibrate a lenslet-based light field camera % % Usage: % % LFUtilCalLensletCam % LFUtilCalLensletCam( Inputpath ) % LFUtilCalLensletCam( InputPath, CalOptions ) % LFUtilProcessCalibrations( [], CalOptions ) % % All parameters are optional and take on default values as set in the "Defaults" section at the top % of the implementation. As such, this can be called as a function or run directly by editing the % code. When calling as a function, pass an empty array "[]" to omit a parameter. % % This function recursively crawls through a folder identifying decoded light field images and % performing a calibration based on those images. It follows the calibration procedure described in: % % D. G. Dansereau, O. Pizarro, and S. B. Williams, "Decoding, calibration and rectification for % lenslet-based plenoptic cameras," in Computer Vision and Pattern Recognition (CVPR), IEEE % Conference on. IEEE, Jun 2013. % % Minor differences from the paper: camera parameters are automatically initialized, so no prior % knowledge of the camera's parameters is required; the free intrinsic parameters have been reduced % by two: H(3:4,5) were previously redundant with the camera's extrinsics, and are now automatically % centered; and the light field indices [i,j,k,l] are 1-based in this implementation, and not % 0-based as described in the paper. % % The calibration produced by this process is saved in a JSON file, by default named 'CalInfo.json', % in the top-level folder of the calibration images. The calibration includes a 5x5 homogeneous % intrinsic matrix EstCamIntrinsicsH, a 5-element vector EstCamDistortionV describing its distortion % parameters, and the lenslet grid model formed from the white image used to decode the % checkerboard images. Taken together, these relate light field indices [i,j,k,l] to spatial rays % [s,t,u,v], and can be utilized to rectify light fields, as demonstrated in LFUtilDecodeLytroFolder % / LFCalRectifyLF. % % The input light fields are ideally of a small checkerboard (order mm per square), taken at close % range, and over a diverse set of poses to maximize the quality of the calibration. The % checkerboard light field images should be decoded without rectification, and colour correction is % not required. % % Calibration is described in more detail in LFToolbox.pdf, including links to example datasets and % a walkthrough of a calibration process. % % Inputs -- all are optional, see code below for default values : % % InputPath : Path to folder containing decoded checkerboard images -- note the function % operates recursively, i.e. it will search sub-folders. % % CalOptions : struct controlling calibration parameters % .ExpectedCheckerSize : Number of checkerboard corners, as recognized by the automatic % corner detector; edge corners are not recognized, so a standard % 8x8-square chess board yields 7x7 corners % .ExpectedCheckerSpacing_m : Physical extents of the checkerboard, in meters % .LensletBorderSize : Number of pixels to skip around the edges of lenslets; a low % value of 1 or 0 is generally appropriate, as invalid pixels are % automatically skipped % .SaveResult : Set to false to perform a "dry run" % .ShowDisplay : Enables various displays throughout the calibration process % .ForceRedoCornerFinding : Forces the corner finding procedure to run, overwriting existing % results % .ForceRedoInit : Forces the parameter initialization step to run, overwriting % existing results % .OptTolX : Determines when the optimization process terminates. When the % estimted parameter values change by less than this amount, the % optimization terminates. See the Matlab documentation on lsqnonlin, % option `TolX' for more information. The default value of 5e-5 is set % within the LFCalRefine function; a value of 0 means the optimization % never terminates based on this criterion. % .OptTolFun : Similar to OptTolX, except this tolerance deals with the error value. % This corresponds to Matlab's lsqnonlin option `TolFun'. The default % value of 0 is set within the LFCalRefine function, and means the % optimization never terminates based on this criterion. % % Output takes the form of saved checkerboard info and calibration files. % % Example : % % LFUtilCalLensletCam('.', ... % struct('ExpectedCheckerSize', [8,6], 'ExpectedCheckerSpacing_m', 1e-3*[35.1, 35.0])) % % Run from within the top-level path of a set of decoded calibration images of an 8x6 checkerboard % of dimensions 35.1x35.0 mm, will carry out all the stages of a calibration. See the toolbox % documentation for a more complete example. % % See also: LFCalFindCheckerCorners, LFCalInit, LFCalRefine, LFUtilDecodeLytroFolder, LFSelectFromDatabase % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LFUtilCalLensletCam( InputPath, CalOptions ) %---Tweakables--- InputPath = LFDefaultVal('InputPath', '.'); CalOptions = LFDefaultField( 'CalOptions', 'ExpectedCheckerSize', [19, 19] ); CalOptions = LFDefaultField( 'CalOptions', 'ExpectedCheckerSpacing_m', [3.61, 3.61] * 1e-3 ); CalOptions = LFDefaultField( 'CalOptions', 'LensletBorderSize', 1 ); CalOptions = LFDefaultField( 'CalOptions', 'SaveResult', true ); CalOptions = LFDefaultField( 'CalOptions', 'ForceRedoCornerFinding', false ); CalOptions = LFDefaultField( 'CalOptions', 'ForceRedoInit', false ); CalOptions = LFDefaultField( 'CalOptions', 'ShowDisplay', true ); CalOptions = LFDefaultField( 'CalOptions', 'CalInfoFname', 'CalInfo.json' ); %---Check for previously started calibration--- CalInfoFname = fullfile(InputPath, CalOptions.CalInfoFname); if( ~CalOptions.ForceRedoInit && exist(CalInfoFname, 'file') ) fprintf('---File %s already exists\n Loading calibration state and options\n', CalInfoFname); CalOptions = LFStruct2Var( LFReadMetadata(CalInfoFname), 'CalOptions' ); else CalOptions.Phase = 'Start'; end RefineComplete = false; % always at least refine once %---Step through the calibration phases--- while( ~strcmp(CalOptions.Phase, 'Refine') || ~RefineComplete ) switch( CalOptions.Phase ) case 'Start' %---Find checkerboard corners--- CalOptions.Phase = 'Corners'; CalOptions = LFCalFindCheckerCorners( InputPath, CalOptions ); case 'Corners' %---Initialize calibration process--- CalOptions.Phase = 'Init'; CalOptions = LFCalInit( InputPath, CalOptions ); if( CalOptions.ShowDisplay ) LFFigure(2); clf LFCalDispEstPoses( InputPath, CalOptions, [], [0.7,0.7,0.7] ); end case 'Init' %---First step of optimization process will exclude distortion--- CalOptions.Phase = 'NoDistort'; CalOptions = LFCalRefine( InputPath, CalOptions ); if( CalOptions.ShowDisplay ) LFFigure(2); LFCalDispEstPoses( InputPath, CalOptions, [], [0,0.7,0] ); end case 'NoDistort' %---Next step of optimization process adds distortion--- CalOptions.Phase = 'WithDistort'; CalOptions = LFCalRefine( InputPath, CalOptions ); if( CalOptions.ShowDisplay ) LFFigure(2); LFCalDispEstPoses( InputPath, CalOptions, [], [0,0,1] ); end otherwise %---Subsequent calls refine the estimate--- CalOptions.Phase = 'Refine'; CalOptions = LFCalRefine( InputPath, CalOptions ); RefineComplete = true; if( CalOptions.ShowDisplay ) LFFigure(2); LFCalDispEstPoses( InputPath, CalOptions, [], [1,0,0] ); end end end
github
hazirbas/light-field-toolbox-master
LFHistEqualize.m
.m
light-field-toolbox-master/LFToolbox0.4/LFHistEqualize.m
6,002
utf_8
aaaa0313c7b80ba9ccf5524a24026bdb
% LFHistEqualize - histogram-based contrast adjustment % % Usage: % % LF = LFHistEqualize( LF ) % [LF, LowerBound, UpperBound] = LFHistEqualize( LF, Cutoff_percent ) % LF = LFHistEqualize( LF, [], LowerBound, UpperBound ) % LF = LFHistEqualize(LF, Cutoff_percent, [], [], Precision) % % This function performs contrast adjustment on images based on a histogram of intensity. Colour % images are handled by building a histogram of the `value' channel in the HSV colour space. % Saturation points are computed based on a desired percentage of saturated white / black pixels. % % All parameters except LF are optional. Pass an empty array "[]" to omit a parameter. % % Inputs: % % LF : a light field or image to adjust. Integer formats are automatically converted to floating % point. The default precision is 'single', though this is controllable via the optional % Precision parameter. The function can handle most input dimensionalities as well as % colour and monochrome inputs. For example, a colour 2D image of size [Nl,Nk,3], a mono 2D % image of size [Nl,Nk], a colour 4D image of size [Nj,Ni,Nl,Nk,3], and a mono 4D image of % size [Nj,Ni,Nl,Nk] are all valid. % % Including a weight channel will result in zero-weight pixels being ignored. Weight should % be included as a fourth colour channel -- e.g. an image of size [Nl,Nk,4]. % % Optional inputs: % % Cutoff_percent : controls how much of the histogram gets saturated on both the high % and lower ends. Higher values result in more saturated black and % white pixels. The default value is 0.1%. % % LowerBound, UpperBound : bypass the histogram computation and instead directly saturate the % input image at the prescribed limits. If no bounds are provided, they % are computed from the histogram. % % Precision : 'single' or 'double' % % % Outputs: % % LF : the contrast-adjusted image, in floating point values scaled between % 0 and 1. % % LowerBound, UpperBound : the saturation points used, on the intensity scale of the input after % converting to the requested floating point precision. These are % useful in applying the same contrast adjustment to a number of light % fields, by saving and passing these bounds on subsequent function % calls. % % Example: % % load('Images/F01/IMG_0002__Decoded.mat', 'LF'); % LF = LFHistEqualize(LF); % LFDispMousePan(LF, 2); % % Run from the top level of the light field samples will load the decoded sample, apply histogram % equalization, then display the result in a shifting-perspective display with x2 magnification. % LFUtilProcessWhiteImages and LFUtilDecodeLytroFolder must be run to decode the light field. % % See also: LFUtilDecodeLytroFolder, LFUtilProcessWhiteImages, LFColourCorrect % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [LF, LowerBound, UpperBound] = ... LFHistEqualize(LF, Cutoff_percent, LowerBound, UpperBound, Precision) %---Defaults--- Cutoff_percent = LFDefaultVal( 'Cutoff_percent', 0.1 ); Precision = LFDefaultVal( 'Precision', 'single' ); MaxBlkSize = LFDefaultVal( 'MaxBlkSize', 10e6 ); % slice up to limit memory utilization %---Make sure LF is floating point, as required by hist function--- if( ~strcmp(class(LF), Precision) ) LF = cast(LF, Precision); end %---Flatten to a single list of N x NChans entries--- LFSize = size(LF); NDims = numel(LFSize); NChans = LFSize(end); LF = reshape(LF, [prod(LFSize(1:NDims-1)), NChans]); %---Strip out and use the weight channel if it's present--- if( NChans == 4 ) % Weight channel found, strip it out and use it LFW = LF(:,4); LF = LF(:,1:3); ValidIdx = find(LFW > 0); else LFW = []; ValidIdx = ':'; end %---Convert colour images to HSV, and operate on value only--- if( size(LF,2) == 3 ) LF = LF - min(LF(ValidIdx)); LF = LF ./ max(LF(ValidIdx)); LF = max(0,min(1,LF)); fprintf('Converting to HSV...'); for( UStart = 1:MaxBlkSize:size(LF,1) ) UStop = UStart + MaxBlkSize - 1; UStop = min(UStop, size(LF,1)); % matlab 2014b's rgb2hsv requires doubles LF(UStart:UStop,:) = cast(rgb2hsv( double(LF(UStart:UStop,:)) ), Precision); fprintf('.') end LF_hsv = LF(:,1:2); LF = LF(:,3); % operate on value channel only else LF_hsv = []; end fprintf(' Equalizing...'); %---Compute bounds from histogram--- if( ~exist('LowerBound','var') || ~exist('UpperBound','var') || ... isempty(LowerBound) || isempty(UpperBound)) [ha,xa] = hist(LF(ValidIdx), 2^16); ha = cumsum(ha); ha = ha ./ max(ha(:)); Cutoff = Cutoff_percent / 100; LowerBound = xa(find(ha >= Cutoff, 1, 'first')); UpperBound = xa(find(ha <= 1-Cutoff, 1, 'last')); end if( isempty(UpperBound) ) UpperBound = max(LF(ValidIdx)); end if( isempty(LowerBound) ) LowerBound = min(LF(ValidIdx)); end clear ValidIdx %---Apply bounds and rescale to 0-1 range--- LF = max(LowerBound, min(UpperBound, LF)); LF = (LF - LowerBound) ./ (UpperBound - LowerBound); %---Rebuild hsv, then rgb colour light field--- if( ~isempty(LF_hsv) ) LF = cat(2,LF_hsv,LF); clear LF_hsv fprintf(' Converting to RGB...'); for( UStart = 1:MaxBlkSize:size(LF,1) ) UStop = UStart + MaxBlkSize - 1; UStop = min(UStop, size(LF,1)); LF(UStart:UStop,:) = hsv2rgb(LF(UStart:UStop,:)); fprintf('.'); end end %---Return the weight channel--- if( ~isempty(LFW) ) LF(:,4) = LFW; end %---Unflatten--- LF = reshape(LF, [LFSize(1:NDims-1),NChans]); fprintf(' Done.\n');
github
hazirbas/light-field-toolbox-master
LFReadRaw.m
.m
light-field-toolbox-master/LFToolbox0.4/LFReadRaw.m
2,387
utf_8
f61af2a213353cf523d8d47f5fd665aa
% LFReadRaw - Reads 8, 10, 12 and 16-bit raw image files % % Usage: % % Img = LFReadRaw( Fname ) % Img = LFReadRaw( Fname, BitPacking, ImgSize ) % Img = LFReadRaw( Fname, [], ImgSize ) % % There is no universal `RAW' file format. This function reads a few variants, including the 12-bit and 10-bit files % commonly employed in Lytro cameras, and the 16-bit files produced by some third-party LFP extraction tools. The output % is always an array of type uint16, except for 8-bit files which produce an 8-bit output. % % Raw images may be converted to more portable formats, including .png, using an external tool such as the % cross-platform ImageMagick tool. % % Inputs : % % Fname : path to raw file to read % % [optional] BitPacking : one of '12bit', '10bit' or '16bit'; default is '12bit' % % [optional] ImgSize : a 2D vector defining the size of the image, in pixels. The default value varies according to % the value of 'BitPacking', to correspond to commonly-found Lytro file formats: 12 bit images are employed by the % Lytro F01, producing images of size 3280x3280, while 10-bit images are produced by the Illum at a resolutio of % 7728x5368; 16-bit images default to 3280x3280. % % Outputs: % % Img : an array of uint16 gray levels. No demosaicing (decoding Bayer pattern) is performed. % % See also: LFReadLFP, LFDecodeLensletImageSimple, demosaic % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function Img = LFReadRaw( Fname, BitPacking, ImgSize ) %---Defaults--- BitPacking = LFDefaultVal( 'BitPacking', '12bit' ); switch( BitPacking ) case '8bit' ImgSize = LFDefaultVal( 'ImgSize', [3280,3280] ); BuffSize = prod(ImgSize); case '12bit' ImgSize = LFDefaultVal( 'ImgSize', [3280,3280] ); BuffSize = prod(ImgSize) * 12/8; case '10bit' ImgSize = LFDefaultVal( 'ImgSize', [7728, 5368] ); BuffSize = prod(ImgSize) * 10/8; case '16bit' ImgSize = LFDefaultVal( 'ImgSize', [3280,3280] ); BuffSize = prod(ImgSize) * 16/8; otherwise error('Unrecognized bit packing format'); end %---Read and unpack--- f = fopen( Fname ); Img = fread( f, BuffSize, 'uchar' ); Img = LFUnpackRawBuffer( Img, BitPacking, ImgSize )'; % note the ' is necessary to get the rotation right fclose( f );
github
hazirbas/light-field-toolbox-master
LFDispVidCirc.m
.m
light-field-toolbox-master/LFToolbox0.4/LFDispVidCirc.m
3,251
utf_8
7f29b601b697f1bf5daf1621b54fe7b0
% LFDispVidCirc - visualize a 4D light field animating a circular path through two dimensions % % Usage: % % FigureHandle = LFDispVidCirc( LF ) % FigureHandle = LFDispVidCirc( LF, PathRadius_percent, FrameDelay ) % FigureHandle = LFDispVidCirc( LF, PathRadius_percent, FrameDelay, ScaleFactor ) % FigureHandle = LFDispVidCirc( LF, [], [], ScaleFactor ) % % % A figure is set up for high-performance display, with the tag 'LFDisplay'. Subsequent calls to % this function and LFDispVidCirc will reuse the same figure, rather than creating a new window on % each call. All parameters except LF are optional -- pass an empty array "[]" to omit an optional % parameter. % % % Inputs: % % LF : a colour or single-channel light field, and can a floating point or integer format. For % display, it is converted to 8 bits per channel. If LF contains more than three colour % channels, as is the case when a weight channel is present, only the first three are used. % % Optional Inputs: % % PathRadius_percent : radius of the circular path taken by the viewpoint. Values that are too % high can result in collision with the edges of the lenslet image, while % values that are too small result in a less impressive visualization. The % default value is 60%. % % FrameDelay : sets the delay between frames, in seconds. The default value is 1/60th of % a second. % % ScaleFactor : Adjusts the size of the display -- 1 means no change, 2 means twice as % big, etc. Integer values are recommended to avoid scaling artifacts. Note % that the scale factor is only applied the first time a figure is created. % To change the scale factor, close the figure before calling % LFDispMousePan. % % Outputs: % % FigureHandle % % % See also: LFDisp, LFDispMousePan % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function FigureHandle = LFDispVidCirc( LF, PathRadius_percent, FrameDelay, varargin ) %---Defaults--- PathRadius_percent = LFDefaultVal( 'PathRadius_percent', 60 ); FrameDelay = LFDefaultVal( 'FrameDelay', 1/60 ); %---Check for mono and clip off the weight channel if present--- Mono = (ndims(LF) == 4); if( ~Mono ) LF = LF(:,:,:,:,1:3); end %---Rescale for 8-bit display--- if( isfloat(LF) ) LF = uint8(LF ./ max(LF(:)) .* 255); else LF = uint8(LF.*(255 / double(intmax(class(LF))))); end %---Setup the display--- [ImageHandle,FigureHandle] = LFDispSetup( squeeze(LF(floor(end/2),floor(end/2),:,:,:)), varargin{:} ); %---Setup the motion path--- [TSize,SSize, ~,~] = size(LF(:,:,:,:,1)); TCent = (TSize-1)/2 + 1; SCent = (SSize-1)/2 + 1; t = 0; RotRate = 0.05; RotRad = TCent*PathRadius_percent/100; while(1) TVal = TCent + RotRad * cos( 2*pi*RotRate * t ); SVal = SCent + RotRad * sin( 2*pi*RotRate * t ); SIdx = round(SVal); TIdx = round(TVal); CurFrame = squeeze(LF( TIdx, SIdx, :,:,: )); set(ImageHandle,'cdata', CurFrame ); pause(FrameDelay) t = t + 1; end
github
hazirbas/light-field-toolbox-master
LFDisp.m
.m
light-field-toolbox-master/LFToolbox0.4/LFDisp.m
1,447
utf_8
e7dcaf88325fd23f136fac4a166709e5
% LFDisp - Convenience function to display a 2D slice of a light field % % Usage: % LFSlice = LFDispMousePan( LF ) % LFDispMousePan( LF ) % % % The centermost image is taken in s and t. Also works with 3D arrays of images. If an output argument is included, no % display is generated, but the extracted slice is returned instead. % % Inputs: % % LF : a colour or single-channel light field, and can a floating point or integer format. For % display, it is scaled as in imagesc. If LF contains more than three colour % channels, as is the case when a weight channel is present, only the first three are used. % % % Outputs: % % LFSlice : if an output argument is used, no display is generated, but the extracted slice is returned. % % % See also: LFDispVidCirc, LFDispMousePan % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function ImgOut = LFDisp( LF ) LF = squeeze(LF); LFSize = size(LF); HasWeight = (ndims(LF)>2 && LFSize(end)==2 || LFSize(end)==4); HasColor = (ndims(LF)>2 && (LFSize(end)==3 || LFSize(end)==4) ); HasMonoAndWeight = (ndims(LF)>2 && LFSize(end)==2); if( HasColor || HasMonoAndWeight ) GoalDims = 3; else GoalDims = 2; end while( ndims(LF) > GoalDims ) LF = squeeze(LF(round(end/2),:,:,:,:,:,:)); end if( HasWeight ) LF = squeeze(LF(:,:,1:end-1)); end if( nargout > 0 ) ImgOut = LF; else imagesc(LF); end
github
hazirbas/light-field-toolbox-master
LFBuild2DFreqFan.m
.m
light-field-toolbox-master/LFToolbox0.4/LFBuild2DFreqFan.m
4,507
utf_8
d3bc64badf14c750b5f1f2a996936c1f
% LFBuild2DFreqFan - construct a 2D fan passband filter in the frequency domain % % Usage: % % [H, FiltOptions] = LFBuild2DFreqFan( LFSize, Slope1, Slope2, BW, FiltOptions ) % H = LFBuild2DFreqFan( LFSize, Slope, BW ) % % This file constructs a real-valued magnitude response in 2D, for which the passband is a fan. % % Once constructed the filter must be applied to a light field, e.g. using LFFilt2DFFT. The % LFDemoBasicFilt* files demonstrate how to contruct and apply frequency-domain filters. % % A more technical discussion, including the use of filters for denoising and volumetric focus, and % the inclusion of aliases components, is included in: % % [2] D.G. Dansereau, O. Pizarro, and S. B. Williams, "Linear Volumetric Focus for Light Field % Cameras," to appear in ACM Transactions on Graphics (TOG), vol. 34, no. 2, 2015. % % Inputs: % % LFSize : Size of the frequency-domain filter. This should match or exceed the size of the % light field to be filtered. If it's larger than the input light field, the input is % zero-padded to match the filter's size by LFFilt2DFFT. % % Slope1, Slope2 : Slopes at the extents of the fan passband. % % BW : 3-db Bandwidth of the planar passband. % % [optional] FiltOptions : struct controlling filter construction % SlopeMethod : only 'Skew' is supported for now % Precision : 'single' or 'double', default 'single' % Rolloff : 'Gaussian' or 'Butter', default 'Gaussian' % Order : controls the order of the filter when Rolloff is 'Butter', default 3 % Aspect2D : aspect ratio of the light field, default [1 1] % Window : Default false. By default the edges of the passband are sharp; this adds % a smooth rolloff at the edges when used in conjunction with Extent2D or % IncludeAliased. % Extent2D : controls where the edge of the passband occurs, the default [1 1] % is the edge of the Nyquist box. When less than 1, enabling windowing % introduces a rolloff after the edge of the passband. Can be greater % than 1 when using IncludeAliased. % IncludeAliased : default false; allows the passband to wrap around off the edge of the % Nyquist box; used in conjunction with Window and/or Extent2D. This can % increase processing time dramatically, e.g. Extent2D = [2,2] % requires a 2^2 = 4-fold increase in time to construct the filter. % Useful when passband content is aliased, see [2]. % % Outputs: % % H : real-valued frequency magnitude response % FiltOptions : The filter options including defaults, with an added PassbandInfo field % detailing the function and time of construction of the filter % % See also: LFDemoBasicFiltGantry, LFDemoBasicFiltIllum, LFDemoBasicFiltLytroF01, LFBuild2DFreqFan, LFBuild2DFreqLine, % LFBuild4DFreqDualFan, LFBuild4DFreqHypercone, LFBuild4DFreqHyperfan, LFBuild4DFreqPlane, LFFilt2DFFT, LFFilt4DFFT, % LFFiltShiftSum % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [H, FiltOptions] = LFBuild2DFreqFan( LFSize, Slope1, Slope2, BW, FiltOptions ) FiltOptions = LFDefaultField('FiltOptions', 'SlopeMethod', 'Skew'); % 'Skew' only for now DistFunc = @(P, FiltOptions) DistFunc_2DFan( P, Slope1, Slope2, FiltOptions ); [H, FiltOptions] = LFHelperBuild2DFreq( LFSize, BW, FiltOptions, DistFunc ); TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); FiltOptions.PassbandInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); end %----------------------------------------------------------------------------------------------------------------------- function Dist = DistFunc_2DFan( P, Slope1, Slope2, FiltOptions ) switch( lower(FiltOptions.SlopeMethod) ) case 'skew' if( Slope2 < Slope1 ) t = Slope1; Slope1 = Slope2; Slope2 = t; end R1 = eye(2); R2 = R1; R1(1,2) = Slope1; R2(1,2) = Slope2; otherwise error('Unrecognized slope method'); end P1 = R1 * P; P2 = R2 * P; TransitionPt = LFSign(P1(2,:)); CurDist1 = max(0, TransitionPt .* P1(1,:)); CurDist2 = max(0,-TransitionPt .* P2(1,:)); Dist = max(CurDist1, CurDist2).^2; end
github
hazirbas/light-field-toolbox-master
LFLytroDecodeImage.m
.m
light-field-toolbox-master/LFToolbox0.4/LFLytroDecodeImage.m
9,163
utf_8
cc50d3baf7583157ad9f352a8774b14f
% LFLytroDecodeImage - decode a Lytro light field from a raw lenslet image, called by LFUtilDecodeLytroFolder % % Usage: % [LF, LFMetadata, WhiteImageMetadata, LensletGridModel, DecodeOptions] = ... % LFLytroDecodeImage( InputFname, DecodeOptions ) % [LF, LFMetadata, WhiteImageMetadata, LensletGridModel, DecodeOptions] = ... % LFLytroDecodeImage( InputFname ) % % This function decodes a raw lenslet image into a 4D light field. Its purpose is to tailor the core lenslet decoding % function, LFDecodeLensletImageSimple, for use with Lytro data. It is envisioned that other camera formats will be % supported by similar functions in future. % % Supported file formats include Lytro LFP files and extracted .raw files accompanied by metadata, as extracted by using % LFP Reader v2.0.0, for example. See LFToolbox.pdf for more information. % % The white image appropriate to a light field is selected based on a white image database, and so % LFUtilProcessWhiteImages must be run before this function. % % LFUtilDecodeLytroFolder is useful for decoding multiple images. % % The optional DecodeOptions argument includes several fields defining filename patterns. These are % combined with the input LFFnameBase to build complete filenames. Filename patterns include the % placeholder '%s' to signify the position of the base filename. For example, the defualt filename % pattern for a raw input file, LensletImageFnamePattern, is '%s__frame.raw'. So a call of the % form LFLytroDecodeImage('IMG_0001') will look for the raw input file 'IMG_0001__frame.raw'. % % Inputs: % % InputFname : Filename of the input light field -- the extension is used to detect LFP or raw input. % % [optinal] DecodeOptions : all fields are optional, defaults are for LFP Reader v2.0.0 naming % .WhiteProcDataFnameExtension : Grid model from LFUtilProcessWhiteImages, default 'grid.json' % .WhiteRawDataFnameExtension : White image file extension, default '.RAW' % .WhiteImageDatabasePath : White image database, default 'Cameras/WhiteImageDatabase.mat' % % For compatibility with extracted .raw and .json files: % .MetadataFnamePattern : JSON file containing light field metadata, default '_metadata.json' % .SerialdataFnamePattern : JSON file containing serial numbers, default '_private_metadata.json' % % Outputs: % % LF : 5D array containing a 4-channel (RGB + Weight) light field, indexed in % the order [j,i,l,k, channel] % LFMetadata : Contents of the metadata and serial metadata files % WhiteImageMetadata : Conents of the white image metadata file % LensletGridModel : Lenslet grid model used to decode the light field, as constructed from % the white image by LFUtilProcessWhiteImages / LFBuildLensletGridModel % DecodeOptions : The options as applied, including any default values omitted in the input % % % Example: % % LF = LFLytroDecodeImage('Images/F01/IMG_0001__frame.raw'); % or % LF = LFLytroDecodeImage('Images/Illum/LorikeetHiding.lfp'); % % Run from the top level of the light field samples will decode the respective raw or lfp light fields. % LFUtilProcessWhiteImages must be run before decoding will work. % % See also: LFUtilDecodeLytroFolder, LFUtilProcessWhiteImages, LFDecodeLensletImageSimple, LFSelectFromDatabase % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [LF, LFMetadata, WhiteImageMetadata, LensletGridModel, DecodeOptions] = ... LFLytroDecodeImage( InputFname, DecodeOptions ) %---Defaults--- DecodeOptions = LFDefaultField( 'DecodeOptions', 'WhiteProcDataFnameExtension', '.grid.json' ); DecodeOptions = LFDefaultField( 'DecodeOptions', 'WhiteRawDataFnameExtension', '.RAW' ); DecodeOptions = LFDefaultField( 'DecodeOptions', 'WhiteImageDatabasePath', fullfile('Cameras','WhiteImageDatabase.mat')); % Compatibility: for loading extracted raw / json files DecodeOptions = LFDefaultField( 'DecodeOptions', 'MetadataFnamePattern', '_metadata.json' ); DecodeOptions = LFDefaultField( 'DecodeOptions', 'SerialdataFnamePattern', '_private_metadata.json' ); %--- LF = []; LFMetadata = []; WhiteImageMetadata = []; LensletGridModel = []; %---Read the LFP or raw file + external metadata--- FileExtension = InputFname(end-2:end); switch( lower(FileExtension) ) case 'raw' %---Load raw light field and metadata--- FNameBase = InputFname(1:end-4); MetadataFname = [FNameBase, DecodeOptions.MetadataFnamePattern]; SerialdataFname = [FNameBase, DecodeOptions.SerialdataFnamePattern]; fprintf('Loading lenslet image and metadata:\n\t%s\n', InputFname); LFMetadata = LFReadMetadata(MetadataFname); LFMetadata.SerialData = LFReadMetadata(SerialdataFname); switch( LFMetadata.camera.model ) case 'F01' BitPacking = '12bit'; DecodeOptions.DemosaicOrder = 'bggr'; case 'B01' BitPacking = '10bit'; DecodeOptions.DemosaicOrder = 'grbg'; end LensletImage = LFReadRaw(InputFname, BitPacking); otherwise %---Load Lytro LFP format--- fprintf('Loading LFP %s\n', InputFname ); LFP = LFReadLFP( InputFname ); if( ~isfield(LFP, 'RawImg') ) fprintf('No light field image found, skipping...\n'); return end LFMetadata = LFP.Metadata; LFMetadata.SerialData = LFP.Serials; LensletImage = LFP.RawImg; DecodeOptions.DemosaicOrder = LFP.DemosaicOrder; end %---Select appropriate white image--- DesiredCam = struct('CamSerial', LFMetadata.SerialData.camera.serialNumber, ... 'ZoomStep', LFMetadata.devices.lens.zoomStep, ... 'FocusStep', LFMetadata.devices.lens.focusStep ); DecodeOptions.WhiteImageInfo = LFSelectFromDatabase( DesiredCam, DecodeOptions.WhiteImageDatabasePath ); PathToDatabase = fileparts( DecodeOptions.WhiteImageDatabasePath ); if( isempty(DecodeOptions.WhiteImageInfo) || ~strcmp(DecodeOptions.WhiteImageInfo.CamSerial, DesiredCam.CamSerial) ) fprintf('No appropriate white image found, skipping...\n'); return end %---Display image info--- %---Check serial number--- fprintf('\nWhite image / LF Picture:\n'); fprintf('%s, %s\n', DecodeOptions.WhiteImageInfo.Fname, InputFname); fprintf('Serial:\t%s\t%s\n', DecodeOptions.WhiteImageInfo.CamSerial, DesiredCam.CamSerial); fprintf('Zoom:\t%d\t\t%d\n', DecodeOptions.WhiteImageInfo.ZoomStep, DesiredCam.ZoomStep); fprintf('Focus:\t%d\t\t%d\n\n', DecodeOptions.WhiteImageInfo.FocusStep, DesiredCam.FocusStep); %---Load white image, white image metadata, and lenslet grid parameters--- WhiteMetadataFname = fullfile(PathToDatabase, DecodeOptions.WhiteImageInfo.Fname); WhiteProcFname = LFFindLytroPartnerFile(WhiteMetadataFname, DecodeOptions.WhiteProcDataFnameExtension); WhiteRawFname = LFFindLytroPartnerFile(WhiteMetadataFname, DecodeOptions.WhiteRawDataFnameExtension); fprintf('Loading white image and metadata...\n'); LensletGridModel = LFStruct2Var(LFReadMetadata(WhiteProcFname), 'LensletGridModel'); WhiteImageMetadataWhole = LFReadMetadata( WhiteMetadataFname ); WhiteImageMetadata = WhiteImageMetadataWhole.master.picture.frameArray.frame.metadata; WhiteImageMetadata.SerialData = WhiteImageMetadataWhole.master.picture.frameArray.frame.privateMetadata; switch( WhiteImageMetadata.camera.model ) case 'F01' assert( WhiteImageMetadata.image.rawDetails.pixelPacking.bitsPerPixel == 12 ); assert( strcmp(WhiteImageMetadata.image.rawDetails.pixelPacking.endianness, 'big') ); DecodeOptions.LevelLimits = [LFMetadata.image.rawDetails.pixelFormat.black.gr, LFMetadata.image.rawDetails.pixelFormat.white.gr]; DecodeOptions.ColourMatrix = reshape(LFMetadata.image.color.ccmRgbToSrgbArray, 3,3); DecodeOptions.ColourBalance = [... LFMetadata.image.color.whiteBalanceGain.r, ... LFMetadata.image.color.whiteBalanceGain.gb, ... LFMetadata.image.color.whiteBalanceGain.b ]; DecodeOptions.Gamma = LFMetadata.image.color.gamma^0.5; BitPacking = '12bit'; case 'B01' assert( WhiteImageMetadata.image.rawDetails.pixelPacking.bitsPerPixel == 10 ); assert( strcmp(WhiteImageMetadata.image.rawDetails.pixelPacking.endianness, 'little') ); DecodeOptions.LevelLimits = [LFMetadata.image.pixelFormat.black.gr, LFMetadata.image.pixelFormat.white.gr]; DecodeOptions.ColourMatrix = reshape(LFMetadata.image.color.ccm, 3,3); DecodeOptions.ColourBalance = [1,1,1]; DecodeOptions.Gamma = 1; BitPacking = '10bit'; otherwise fprintf('Unrecognized camera model, skipping...\'); return end WhiteImage = LFReadRaw( WhiteRawFname, BitPacking ); %---Decode--- fprintf('Decoding lenslet image :'); [LF, LFWeight, DecodeOptions] = LFDecodeLensletImageSimple( LensletImage, WhiteImage, LensletGridModel, DecodeOptions ); LF(:,:,:,:,4) = LFWeight;
github
hazirbas/light-field-toolbox-master
LFDefaultIntrinsics.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFDefaultIntrinsics.m
2,030
utf_8
948ce39fff4f94ed954e090033778c04
% LFDefaultIntrinsics - Initializes a set of intrinsics for use in rectifying light fields % % Usage: % % RectCamIntrinsicsH = LFDefaultIntrinsics( LFSize, CalInfo ) % % This gets called by LFCalDispRectIntrinsics to set up a default set of intrinsics for rectification. Based on the % calibration information and the dimensions of the light field, a set of intrinsics is selected which yields square % pixels in ST and UV. Ideally the values will use the hypercube-shaped light field space efficiently, leaving few black % pixels at the edges, and bumping as little information /outside/ the hypercube as possible. % % The sampling pattern yielded by the resulting intrinsics can be visualized using LFCalDispRectIntrinsics. % % Inputs : % % LFSize : Size of the light field to rectify % % CalInfo : Calibration info as loaded by LFFindCalInfo, for example. % % Outputs: % % RectCamIntrinsicsH : The resulting intrinsics. % % See also: LFCalDispRectIntrinsics, LFRecenterIntrinsics, LFFindCalInfo, LFUtilDecodeLytroFolder % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function RectCamIntrinsicsH = LFDefaultIntrinsics( LFSize, CalInfo ) RectCamIntrinsicsH = CalInfo.EstCamIntrinsicsH; ST_ST_Slope = mean([CalInfo.EstCamIntrinsicsH(1,1), CalInfo.EstCamIntrinsicsH(2,2)]); ST_UV_Slope = mean([CalInfo.EstCamIntrinsicsH(1,3), CalInfo.EstCamIntrinsicsH(2,4)]); UV_ST_Slope = mean([CalInfo.EstCamIntrinsicsH(3,1), CalInfo.EstCamIntrinsicsH(4,2)]); UV_UV_Slope = mean([CalInfo.EstCamIntrinsicsH(3,3), CalInfo.EstCamIntrinsicsH(4,4)]); RectCamIntrinsicsH(1,1) = ST_ST_Slope; RectCamIntrinsicsH(2,2) = ST_ST_Slope; RectCamIntrinsicsH(1,3) = ST_UV_Slope; RectCamIntrinsicsH(2,4) = ST_UV_Slope; RectCamIntrinsicsH(3,1) = UV_ST_Slope; RectCamIntrinsicsH(4,2) = UV_ST_Slope; RectCamIntrinsicsH(3,3) = UV_UV_Slope; RectCamIntrinsicsH(4,4) = UV_UV_Slope; %---force s,t translation to CENTER--- RectCamIntrinsicsH = LFRecenterIntrinsics( RectCamIntrinsicsH, LFSize );
github
hazirbas/light-field-toolbox-master
LFDefaultField.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFDefaultField.m
1,979
utf_8
485dfac0b4aba775cf4d1d20f537f0f7
% LFDefaultField - Convenience function to set up structs with default field values % % Usage: % % ParentStruct = LFDefaultField( ParentStruct, FieldName, DefaultVal ) % % This provides an elegant way to establish default field values in a struct. See LFDefaultValue for % setting up non-struct variables with default values. % % Inputs: % % ParentStruct: string giving the name of the struct; the struct need not already exist % FieldName: string giving the name of the field % DefaultVal: default value for the field % % Outputs: % % ParentStruct: if the named struct and field already existed, the output matches the struct's % original value; otherwise the output is a struct with an additional field taking % on the specified default value % % Example: % % clearvars % ExistingStruct.ExistingField = 42; % ExistingStruct = LFDefaultField( 'ExistingStruct', 'ExistingField', 3 ) % ExistingStruct = LFDefaultField( 'ExistingStruct', 'NewField', 36 ) % OtherStruct = LFDefaultField( 'OtherStruct', 'Cheese', 'Indeed' ) % % % Results in : % ExistingStruct = % ExistingField: 42 % NewField: 36 % OtherStruct = % Cheese: 'Indeed' % % Usage for setting up default function arguments is demonstrated in most of the LF Toolbox % functions. % % See also: LFDefaultVal % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function ParentStruct = LFDefaultField( ParentStruct, FieldName, DefaultVal ) %---First make sure the struct exists--- CheckIfExists = sprintf('exist(''%s'', ''var'') && ~isempty(%s)', ParentStruct, ParentStruct); VarExists = evalin( 'caller', CheckIfExists ); if( ~VarExists ) ParentStruct = []; else ParentStruct = evalin( 'caller', ParentStruct ); end %---Now make sure the field exists--- if( ~isfield( ParentStruct, FieldName ) ) ParentStruct.(FieldName) = DefaultVal; end end
github
hazirbas/light-field-toolbox-master
LFSign.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFSign.m
225
utf_8
901dea01bff401571d8125711feeffad
% LFSign - Like Matlab's sign, but never returns 0, treating 0 as positive % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function s = LFSign(i) s = ones(size(i)); s(i<0) = -1;
github
hazirbas/light-field-toolbox-master
LFRotz.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFRotz.m
306
utf_8
2a4fc216ff9e1b6b35762c010ebe50f2
% LFRotz - simple 3D rotation matrix, rotation about z % % Usage: % R = LFRotz( psi ) % % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function R = LFRotz(psi) c = cos(psi); s = sin(psi); R = [ c, -s, 0; ... s, c, 0; ... 0, 0, 1 ];
github
hazirbas/light-field-toolbox-master
LFHelperBuild4DFreq.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFHelperBuild4DFreq.m
4,143
utf_8
5cefe44f63c8fd80b66ad5e267298bff
% LFHelperBuild4DFreq - Helper function used to construct 4D frequency-domain filters % % Much of the complexity in constructing MD frequency-domain filters, especially around including aliased components and % controlling the filter rolloff, is common between filter shapes. This function wraps much of this complexity. % % This gets called by the LFBuild4DFreq* functions. % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [H, FiltOptions] = LFHelperBuild4DFreq( LFSize, BW, FiltOptions, DistFunc ) FiltOptions = LFDefaultField('FiltOptions', 'Precision', 'single'); FiltOptions = LFDefaultField('FiltOptions', 'Rolloff', 'Gaussian'); %Gaussian or Butter FiltOptions = LFDefaultField('FiltOptions', 'Aspect4D', 1); FiltOptions = LFDefaultField('FiltOptions', 'Window', false); FiltOptions = LFDefaultField('FiltOptions', 'Extent4D', 1.0); FiltOptions = LFDefaultField('FiltOptions', 'IncludeAliased', false); FiltOptions.Extent4D = cast(FiltOptions.Extent4D, FiltOptions.Precision); % avoid rounding error during comparisons FiltOptions.Aspect4D = cast(FiltOptions.Aspect4D, FiltOptions.Precision); % avoid rounding error during comparisons if( length(LFSize) == 1 ) LFSize = LFSize .* [1,1,1,1]; end if( length(LFSize) == 5 ) LFSize = LFSize(1:4); end if( length(FiltOptions.Extent4D) == 1 ) FiltOptions.Extent4D = FiltOptions.Extent4D .* [1,1,1,1]; end if( length(FiltOptions.Aspect4D) == 1 ) FiltOptions.Aspect4D = FiltOptions.Aspect4D .* [1,1,1,1]; end ExtentWithAspect = FiltOptions.Extent4D.*FiltOptions.Aspect4D / 2; t = LFNormalizedFreqAxis( LFSize(1), FiltOptions.Precision ) .* FiltOptions.Aspect4D(1); s = LFNormalizedFreqAxis( LFSize(2), FiltOptions.Precision ) .* FiltOptions.Aspect4D(2); v = LFNormalizedFreqAxis( LFSize(3), FiltOptions.Precision ) .* FiltOptions.Aspect4D(3); u = LFNormalizedFreqAxis( LFSize(4), FiltOptions.Precision ) .* FiltOptions.Aspect4D(4); [tt,ss,vv,uu] = ndgrid(cast(t,FiltOptions.Precision),cast(s,FiltOptions.Precision),cast(v,FiltOptions.Precision),cast(u,FiltOptions.Precision)); P = [tt(:),ss(:),vv(:),uu(:)]'; clear s t u v ss tt uu vv if( ~FiltOptions.IncludeAliased ) Tiles = [0,0,0,0]; else Tiles = ceil(ExtentWithAspect); end if( FiltOptions.IncludeAliased ) AADist = inf(LFSize, FiltOptions.Precision); end WinDist = 0; % Tiling proceeds only in positive directions, symmetry is enforced afterward, saving some computation overall for( TTile = 0:Tiles(1) ) for( STile = 0:Tiles(2) ) for( VTile = 0:Tiles(3) ) for( UTile = 0:Tiles(4) ) Dist = inf(LFSize, FiltOptions.Precision); if( FiltOptions.Window ) ValidIdx = ':'; WinDist = bsxfun(@minus, abs(P)', ExtentWithAspect); WinDist = sum(max(0,WinDist).^2, 2); WinDist = reshape(WinDist, LFSize); else ValidIdx = find(all(bsxfun(@le, abs(P), ExtentWithAspect'))); end Dist(ValidIdx) = DistFunc(P(:,ValidIdx), FiltOptions); Dist = Dist + WinDist; if( FiltOptions.IncludeAliased ) AADist(:) = min(AADist(:), Dist(:)); end P(4,:) = P(4,:) + FiltOptions.Aspect4D(4); end P(4,:) = P(4,:) - (Tiles(4)+1) .* FiltOptions.Aspect4D(4); P(3,:) = P(3,:) + FiltOptions.Aspect4D(3); end P(3,:) = P(3,:) - (Tiles(3)+1) .* FiltOptions.Aspect4D(3); P(2,:) = P(2,:) + FiltOptions.Aspect4D(2); end P(2,:) = P(2,:) - (Tiles(2)+1) .* FiltOptions.Aspect4D(2); P(1,:) = P(1,:) + FiltOptions.Aspect4D(1); end if( FiltOptions.IncludeAliased ) Dist = AADist; clear AADist end H = zeros(LFSize, FiltOptions.Precision); switch lower(FiltOptions.Rolloff) case 'gaussian' BW = BW.^2 / log(sqrt(2)); H(:) = exp( -Dist / BW ); % Gaussian rolloff case 'butter' FiltOptions = LFDefaultField('FiltOptions', 'Order', 3); Dist = sqrt(Dist) ./ BW; H(:) = sqrt( 1.0 ./ (1.0 + Dist.^(2*FiltOptions.Order)) ); % Butterworth-like rolloff otherwise error('unrecognized rolloff method'); end H = ifftshift(H); % force symmetric H = max(H, H(mod(LFSize(1):-1:1,LFSize(1))+1, mod(LFSize(2):-1:1,LFSize(2))+1,mod(LFSize(3):-1:1,LFSize(3))+1,mod(LFSize(4):-1:1,LFSize(4))+1));
github
hazirbas/light-field-toolbox-master
LFCalInit.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFCalInit.m
12,108
utf_8
c694e604e6425b97a908bce5ea738134
% LFCalInit - initialize calibration estimate, called by LFUtilCalLensletCam % % Usage: % CalOptions = LFCalInit( InputPath, CalOptions ) % CalOptions = LFCalInit( InputPath ) % % This function is called by LFUtilCalLensletCam to initialize a pose and camera model estimate % given a set of extracted checkerboard corners. % % Inputs: % % InputPath : Path to folder containing processed checkerboard images. Checkerboard corners must % be identified prior to calling this function, by running LFCalFindCheckerCorners % for example. This is demonstrated by LFUtilCalLensletCam. % % [optional] CalOptions : struct controlling calibration parameters, all fields are optional % .SaveResult : Set to false to perform a "dry run" % .CheckerCornersFnamePattern : Pattern for finding checkerboard corner files, as generated by % LFCalFindCheckerCorners; %s is a placeholder for the base filename % .CheckerInfoFname : Name of the output file containing the summarized checkerboard % information % .CalInfoFname : Name of the file containing an initial estimate, to be refined. % Note that this parameter is automatically set in the CalOptions % struct returned by LFCalInit % .ForceRedoInit : Forces the function to overwrite existing results % % Outputs : % % CalOptions struct as applied, including any default values as set up by the function. % % The checkerboard info file and calibration info file are the key outputs of this function. % % See also: LFUtilCalLensletCam, LFCalFindCheckerCorners, LFCalRefine % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function CalOptions = LFCalInit( InputPath, CalOptions ) %---Defaults--- CalOptions = LFDefaultField( 'CalOptions', 'SaveResult', true ); CalOptions = LFDefaultField( 'CalOptions', 'CheckerCornersFnamePattern', '%s__CheckerCorners.mat' ); CalOptions = LFDefaultField( 'CalOptions', 'CheckerInfoFname', 'CheckerboardCorners.mat' ); CalOptions = LFDefaultField( 'CalOptions', 'CalInfoFname', 'CalInfo.json' ); CalOptions = LFDefaultField( 'CalOptions', 'ForceRedoInit', false ); %---Start by checking if this step has already been completed--- fprintf('\n===Initializing calibration process===\n'); CalInfoSaveFname = fullfile(InputPath, CalOptions.CalInfoFname); if( ~CalOptions.ForceRedoInit && exist(CalInfoSaveFname, 'file') ) fprintf(' ---File %s already exists, skipping---\n', CalInfoSaveFname); return; end %---Compute ideal checkerboard geometry - order matters--- IdealCheckerX = CalOptions.ExpectedCheckerSpacing_m(1) .* (0:CalOptions.ExpectedCheckerSize(1)-1); IdealCheckerY = CalOptions.ExpectedCheckerSpacing_m(2) .* (0:CalOptions.ExpectedCheckerSize(2)-1); [IdealCheckerY, IdealCheckerX] = ndgrid(IdealCheckerY, IdealCheckerX); IdealChecker = cat(3,IdealCheckerX, IdealCheckerY, zeros(size(IdealCheckerX))); IdealChecker = reshape(IdealChecker, [], 3)'; %---Crawl folder structure locating corner info files--- fprintf('\n===Locating checkerboard corner files in %s===\n', InputPath); [CalOptions.FileList, BasePath] = LFFindFilesRecursive( InputPath, sprintf(CalOptions.CheckerCornersFnamePattern, '*') ); fprintf('Found :\n'); disp(CalOptions.FileList) %---Initial estimate of focal length--- fprintf('Initial estimate of focal length...\n'); SkippedFileCount = 0; ValidSuperPoseCount = 0; ValidCheckerCount = 0; %---Process each checkerboard corner file--- for( iFile = 1:length(CalOptions.FileList) ) ValidSuperPoseCount = ValidSuperPoseCount + 1; CurFname = CalOptions.FileList{iFile}; [~,ShortFname] = fileparts(CurFname); fprintf('---%s [%3d / %3d]...', ShortFname, ValidSuperPoseCount+SkippedFileCount, length(CalOptions.FileList)); load(fullfile(BasePath, CurFname), 'CheckerCorners', 'LFSize', 'CamInfo', 'LensletGridModel', 'DecodeOptions'); PerImageValidCount = 0; for( TIdx = 1:size(CheckerCorners,1) ) for( SIdx = 1:size(CheckerCorners,2) ) CurChecker = CheckerCorners{TIdx, SIdx}'; CurSize = size(CurChecker); CurValid = (CurSize(2) == prod(CalOptions.ExpectedCheckerSize)); CheckerValid(ValidSuperPoseCount, TIdx, SIdx) = CurValid; %---For valid poses (having expected corner count), compute a homography--- if( CurValid ) ValidCheckerCount = ValidCheckerCount + 1; PerImageValidCount = PerImageValidCount + 1; % %--- reorient to expected --- % Centroid = mean( CurChecker,2 ); % IsTopLeft = all(CurChecker(:,1) < Centroid); % IsTopRight = (CurChecker(1,1) > Centroid(1) && CurChecker(2,1) < Centroid(2)); % if( IsTopRight ) % CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]); % CurChecker = CurChecker(:, end:-1:1, :); % CurChecker = permute(CurChecker, [1,3,2]); % CurChecker = reshape(CurChecker, 2, []); % end % IsTopLeft = all(CurChecker(:,1) < Centroid); % assert( IsTopLeft, 'Error: unexpected point order from detectCheckerboardPoints' ); %--- reorient to expected --- Centroid = mean( CurChecker,2 ); IsTopLeft = all(CurChecker(:,1) < Centroid); IsTopRight = (CurChecker(1,1) > Centroid(1) && CurChecker(2,1) < Centroid(2)); IsBotLeft = (CurChecker(1,1) < Centroid(1) && CurChecker(2,1) > Centroid(2)); IsBotRight = all(CurChecker(:,1) > Centroid); if( IsTopRight ) CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]); CurChecker = CurChecker(:, end:-1:1, :); CurChecker = permute(CurChecker, [1,3,2]); CurChecker = reshape(CurChecker, 2, []); elseif( IsBotLeft ) CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]); CurChecker = CurChecker(:, :, end:-1:1); CurChecker = permute(CurChecker, [1,3,2]); CurChecker = reshape(CurChecker, 2, []); elseif( IsBotRight ) % untested case CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]); CurChecker = CurChecker(:, end:-1:1, end:-1:1); CurChecker = permute(CurChecker, [1,3,2]); CurChecker = reshape(CurChecker, 2, []); end IsTopLeft = all(CurChecker(:,1) < Centroid); assert( IsTopLeft, 'Error: unexpected point order from detectCheckerboardPoints' ); CheckerObs{ValidSuperPoseCount, TIdx, SIdx} = CurChecker; %---Compute homography for each subcam pose--- CurH = compute_homography( CurChecker, IdealChecker(1:2,:) ); H(ValidCheckerCount, :,:) = CurH; end end end CalOptions.ValidSubimageCount(iFile) = PerImageValidCount; fprintf(' %d / %d valid.\n', PerImageValidCount, prod(LFSize(1:2))); end A = []; b = []; %---Initialize principal point at the center of the image--- % This section of code is based heavily on code from the Camera Calibration Toolbox for Matlab by % Jean-Yves Bouguet CInit = LFSize([4,3])'/2 - 0.5; RecenterH = [1, 0, -CInit(1); 0, 1, -CInit(2); 0, 0, 1]; for iHomography = 1:size(H,1) CurH = squeeze(H(iHomography,:,:)); CurH = RecenterH * CurH; %---Extract vanishing points (direct and diagonal)--- V_hori_pix = CurH(:,1); V_vert_pix = CurH(:,2); V_diag1_pix = (CurH(:,1)+CurH(:,2))/2; V_diag2_pix = (CurH(:,1)-CurH(:,2))/2; V_hori_pix = V_hori_pix/norm(V_hori_pix); V_vert_pix = V_vert_pix/norm(V_vert_pix); V_diag1_pix = V_diag1_pix/norm(V_diag1_pix); V_diag2_pix = V_diag2_pix/norm(V_diag2_pix); a1 = V_hori_pix(1); b1 = V_hori_pix(2); c1 = V_hori_pix(3); a2 = V_vert_pix(1); b2 = V_vert_pix(2); c2 = V_vert_pix(3); a3 = V_diag1_pix(1); b3 = V_diag1_pix(2); c3 = V_diag1_pix(3); a4 = V_diag2_pix(1); b4 = V_diag2_pix(2); c4 = V_diag2_pix(3); CurA = [a1*a2, b1*b2; a3*a4, b3*b4]; CurB = -[c1*c2; c3*c4]; if( isempty(find(isnan(CurA), 1)) && isempty(find(isnan(CurB), 1)) ) A = [A; CurA]; b = [b; CurB]; end end FocInit = sqrt(b'*(sum(A')') / (b'*b)) * ones(2,1); fprintf('Init focal length est: %.2f, %.2f\n', FocInit); %---Initial estimate of extrinsics--- fprintf('\nInitial estimate of extrinsics...\n'); for( iSuperPoseIdx = 1:ValidSuperPoseCount ) fprintf('---[%d / %d]', iSuperPoseIdx, ValidSuperPoseCount); for( TIdx = 1:size(CheckerCorners,1) ) fprintf('.'); for( SIdx = 1:size(CheckerCorners,2) ) if( ~CheckerValid(iSuperPoseIdx, TIdx, SIdx) ) continue; end CurChecker = CheckerObs{iSuperPoseIdx, TIdx, SIdx}; [CurRot, CurTrans] = compute_extrinsic_init(CurChecker, IdealChecker, FocInit, CInit, zeros(1,5), 0); [CurRot, CurTrans] = compute_extrinsic_refine(CurRot, CurTrans, CurChecker, IdealChecker, FocInit, CInit, zeros(1,5), 0,20,1000000); RotVals{iSuperPoseIdx, TIdx, SIdx} = CurRot; TransVals{iSuperPoseIdx, TIdx, SIdx} = CurTrans; end end %---Approximate each superpose as the median of its sub-poses--- % note the approximation in finding the mean orientation: mean of rodrigues... works because all % sub-orientations within a superpose are nearly identical. MeanRotVals(iSuperPoseIdx,:) = median([RotVals{iSuperPoseIdx, :, :}], 2); MeanTransVals(iSuperPoseIdx,:) = median([TransVals{iSuperPoseIdx, :, :}], 2); fprintf('\n'); %---Track the apparent "baseline" of the camera at each pose--- CurDist = bsxfun(@minus, [TransVals{iSuperPoseIdx, :, :}], MeanTransVals(iSuperPoseIdx,:)'); CurAbsDist = sqrt(sum(CurDist.^2)); % store as estimated diameter; the 3/2 comes from the mean radius of points on a disk (2R/3) BaselineApprox(iSuperPoseIdx) = 2 * 3/2 * mean(CurAbsDist); end %---Initialize the superpose estimates--- EstCamPosesV = [MeanTransVals, MeanRotVals]; %---Estimate full intrinsic matrix--- ST_IJ_SlopeApprox = mean(BaselineApprox) ./ (LFSize(2:-1:1)-1); UV_KL_SlopeApprox = 1./FocInit'; EstCamIntrinsicsH = eye(5); EstCamIntrinsicsH(1,1) = ST_IJ_SlopeApprox(1); EstCamIntrinsicsH(2,2) = ST_IJ_SlopeApprox(2); EstCamIntrinsicsH(3,3) = UV_KL_SlopeApprox(1); EstCamIntrinsicsH(4,4) = UV_KL_SlopeApprox(2); % Force central ray as s,t,u,v = 0, note all indices start at 1, not 0 EstCamIntrinsicsH = LFRecenterIntrinsics( EstCamIntrinsicsH, LFSize ); fprintf('\nInitializing estimate of camera intrinsics to: \n'); disp(EstCamIntrinsicsH); %---Start with no distortion estimate--- EstCamDistortionV = []; %---Optionally save the results--- if( CalOptions.SaveResult ) TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); CheckerSaveFname = fullfile(BasePath, CalOptions.CheckerInfoFname); fprintf('\nSaving to %s...\n', CheckerSaveFname); save(CheckerSaveFname, 'GeneratedByInfo', 'CalOptions', 'CheckerObs', 'IdealChecker', 'LFSize', 'CamInfo', 'LensletGridModel', 'DecodeOptions'); fprintf('Saving to %s...\n', CalInfoSaveFname); LFWriteMetadata(CalInfoSaveFname, LFVar2Struct(GeneratedByInfo, LensletGridModel, EstCamIntrinsicsH, EstCamDistortionV, EstCamPosesV, CamInfo, CalOptions, DecodeOptions)); end fprintf(' ---Calibration initialization done---\n');
github
hazirbas/light-field-toolbox-master
LFDecodeLensletImageSimple.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFDecodeLensletImageSimple.m
15,455
utf_8
7c4a879c6a41b6e546bba9d398361001
% LFDecodeLensletImageSimple - decodes a 2D lenslet image into a 4D light field, called by LFUtilDecodeLytroFolder % % Usage: % % [LF, LFWeight, DecodeOptions, DebayerLensletImage, CorrectedLensletImage] = ... % LFDecodeLensletImageSimple( LensletImage, WhiteImage, LensletGridModel, DecodeOptions ) % % This function follows the simple decode process described in: % D. G. Dansereau, O. Pizarro, and S. B. Williams, "Decoding, calibration and rectification for % lenslet-based plenoptic cameras," in Computer Vision and Pattern Recognition (CVPR), IEEE % Conference on. IEEE, Jun 2013. % % This involves demosaicing, devignetting, transforming and slicing the input lenslet image to % yield a 4D structure. More sophisticated approaches exist which combine steps into joint % solutions, and they generally yield superior results, particularly near the edges of lenslets. % The approach taken here was chosen for its simplicity and flexibility. % % Input LensletImage is a raw lenslet iamge as found within Lytro's LFP picture files. Though % this function is written with Lytro imagery in mind, it should be possible to adapt it for use % with other lenslet-based cameras. LensletImage is ideally of type uint16. % % Input WhiteImage is a white image as found within Lytro's calibration data. A white image is an % image taken through a diffuser, and is useful for removing vignetting (darkening near edges of % images) and for locating lenslet centers. The white image should be taken under the same zoom and % focus settings as the light field. In the case of Lytro imagery, the helper functions % LFUtilProcessWhiteImages and LFSelectFromDatabase are provided to assist in forming a list of % available white images, and selecting the appropriate image based on zoom and focus settings. % % Input LensletGridModel is a model of the lenslet grid, as estimated, for example, using % LFBuildLensletGridModel -- see that function for more on the required structure. % % Optional Input DecodeOptions is a structure containing: % [Optional] ResampMethod : 'fast'(default) or 'triangulation', the latter is slower % [Optional] Precision : 'single'(default) or 'double' % [Optional] LevelLimits : a two-element vector defining the black and white levels % % Output LF is a 5D array of size [Nj,Ni,Nl,Nk,3]. See [1] and the documentation accompanying this % toolbox for a brief description of the light field structure. % % Optional output LFWeight is of size [Nj,Ni,Nl,Nk]. LFWeight contains a confidence measure % suitable for use in filtering applications that accept a weight parameter. This parameter is kept % separate from LF rather than building in as a fourth channel in order to allow an optimization: % when the parameter is not requested, it is not computed, saving significant processing time and % memory. % % Optional output DebayerLensletImage is useful for inspecting intermediary results. The debayered % lenslet image is the result of devignetting and debayering, with no further processing. Omitting % this output variable saves memory. % % Optional output CorrectedLensletImage is useful for inspecting intermediary results. The % corrected lenslet image has been rotated and scaled such that lenslet centers lie on straight lines, and % every lenslet center lies on an integer pixel spacing. See [1] for more detail. Omitting % this output variable saves memory. % % See also: LFLytroDecodeImage, LFUtilDecodeLytroFolder % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [LF, LFWeight, DecodeOptions, DebayerLensletImage, CorrectedLensletImage] = ... LFDecodeLensletImageSimple( LensletImage, WhiteImage, LensletGridModel, DecodeOptions ) %---Defaults--- DecodeOptions = LFDefaultField( 'DecodeOptions', 'LevelLimits', [min(WhiteImage(:)), max(WhiteImage(:))] ); DecodeOptions = LFDefaultField( 'DecodeOptions', 'ResampMethod', 'fast' ); %'fast', 'triangulation' DecodeOptions = LFDefaultField( 'DecodeOptions', 'Precision', 'single' ); DecodeOptions = LFDefaultField( 'DecodeOptions', 'DoDehex', true ); DecodeOptions = LFDefaultField( 'DecodeOptions', 'DoSquareST', true ); %---Rescale image values, remove black level--- DecodeOptions.LevelLimits = cast(DecodeOptions.LevelLimits, DecodeOptions.Precision); BlackLevel = DecodeOptions.LevelLimits(1); WhiteLevel = DecodeOptions.LevelLimits(2); WhiteImage = cast(WhiteImage, DecodeOptions.Precision); WhiteImage = (WhiteImage - BlackLevel) ./ (WhiteLevel - BlackLevel); LensletImage = cast(LensletImage, DecodeOptions.Precision); LensletImage = (LensletImage - BlackLevel) ./ (WhiteLevel - BlackLevel); LensletImage = LensletImage ./ WhiteImage; % Devignette % Clip -- this is aggressive and throws away bright areas; there is a potential for an HDR approach here LensletImage = min(1, max(0, LensletImage)); if( nargout < 2 ) clear WhiteImage end %---Demosaic--- % This uses Matlab's demosaic, which is "gradient compensated". This likely has implications near % the edges of lenslet images, where the contrast is due to vignetting / aperture shape, and is not % a desired part of the image LensletImage = cast(LensletImage.*double(intmax('uint16')), 'uint16'); LensletImage = demosaic(LensletImage, DecodeOptions.DemosaicOrder); LensletImage = cast(LensletImage, DecodeOptions.Precision); LensletImage = LensletImage ./ double(intmax('uint16')); DecodeOptions.NColChans = 3; if( nargout >= 2 ) DecodeOptions.NWeightChans = 1; else DecodeOptions.NWeightChans = 0; end if( nargout > 3 ) DebayerLensletImage = LensletImage; end %---Tranform to an integer-spaced grid--- fprintf('\nAligning image to lenslet array...'); InputSpacing = [LensletGridModel.HSpacing, LensletGridModel.VSpacing]; NewLensletSpacing = ceil(InputSpacing); % Force even so hex shift is a whole pixel multiple NewLensletSpacing = ceil(NewLensletSpacing/2)*2; XformScale = NewLensletSpacing ./ InputSpacing; % Notice the resized image will not be square NewOffset = [LensletGridModel.HOffset, LensletGridModel.VOffset] .* XformScale; RoundedOffset = round(NewOffset); XformTrans = RoundedOffset-NewOffset; NewLensletGridModel = struct('HSpacing',NewLensletSpacing(1), 'VSpacing',NewLensletSpacing(2), ... 'HOffset',RoundedOffset(1), 'VOffset',RoundedOffset(2), 'Rot',0, ... 'UMax', LensletGridModel.UMax, 'VMax', LensletGridModel.VMax, 'Orientation', LensletGridModel.Orientation, ... 'FirstPosShiftRow', LensletGridModel.FirstPosShiftRow); %---Fix image rotation and scale--- RRot = LFRotz( LensletGridModel.Rot ); RScale = eye(3); RScale(1,1) = XformScale(1); RScale(2,2) = XformScale(2); DecodeOptions.OutputScale(1:2) = XformScale; DecodeOptions.OutputScale(3:4) = [1,2/sqrt(3)]; % hex sampling RTrans = eye(3); RTrans(end,1:2) = XformTrans; % The following rotation can rotate parts of the lenslet image out of frame. % todo[optimization]: attempt to keep these regions, offer greater user-control of what's kept FixAll = maketform('affine', RRot*RScale*RTrans); NewSize = size(LensletImage(:,:,1)) .* XformScale(2:-1:1); LensletImage = imtransform( LensletImage, FixAll, 'YData',[1 NewSize(1)], 'XData',[1 NewSize(2)]); if( nargout >= 2 ) WhiteImage = imtransform( WhiteImage, FixAll, 'YData',[1 NewSize(1)], 'XData',[1 NewSize(2)]); end if( nargout >= 4 ) CorrectedLensletImage = LensletImage; end LF = SliceXYImage( NewLensletGridModel, LensletImage, WhiteImage, DecodeOptions ); clear WhiteImage LensletImage %---Correct for hex grid and resize to square u,v pixels--- LFSize = size(LF); HexAspect = 2/sqrt(3); switch( DecodeOptions.ResampMethod ) case 'fast' fprintf('\nResampling (1D approximation) to square u,v pixels'); NewUVec = 0:1/HexAspect:(size(LF,4)+1); % overshoot then trim NewUVec = NewUVec(1:ceil(LFSize(4)*HexAspect)); OrigUSize = size(LF,4); LFSize(4) = length(NewUVec); %---Allocate dest and copy orig LF into it (memory saving vs. keeping both separately)--- LF2 = zeros(LFSize, DecodeOptions.Precision); LF2(:,:,:,1:OrigUSize,:) = LF; LF = LF2; clear LF2 if( DecodeOptions.DoDehex ) ShiftUVec = -0.5+NewUVec; fprintf(' and removing hex sampling...'); else ShiftUVec = NewUVec; fprintf('...'); end for( ColChan = 1:size(LF,5) ) CurUVec = ShiftUVec; for( RowIter = 1:2 ) RowIdx = mod(NewLensletGridModel.FirstPosShiftRow + RowIter, 2) + 1; ShiftRows = squeeze(LF(:,:,RowIdx:2:end,1:OrigUSize, ColChan)); SliceSize = size(ShiftRows); SliceSize(4) = length(NewUVec); ShiftRows = reshape(ShiftRows, [size(ShiftRows,1)*size(ShiftRows,2)*size(ShiftRows,3), size(ShiftRows,4)]); ShiftRows = interp1( (0:size(ShiftRows,2)-1)', ShiftRows', CurUVec' )'; ShiftRows(isnan(ShiftRows)) = 0; LF(:,:,RowIdx:2:end,:,ColChan) = reshape(ShiftRows,SliceSize); CurUVec = NewUVec; end end clear ShiftRows DecodeOptions.OutputScale(3) = DecodeOptions.OutputScale(3) * HexAspect; case 'triangulation' fprintf('\nResampling (triangulation) to square u,v pixels'); OldVVec = (0:size(LF,3)-1); OldUVec = (0:size(LF,4)-1) * HexAspect; NewUVec = (0:ceil(LFSize(4)*HexAspect)-1); NewVVec = (0:LFSize(3)-1); LFSize(4) = length(NewUVec); LF2 = zeros(LFSize, DecodeOptions.Precision); [Oldvv,Olduu] = ndgrid(OldVVec,OldUVec); [Newvv,Newuu] = ndgrid(NewVVec,NewUVec); if( DecodeOptions.DoDehex ) fprintf(' and removing hex sampling...'); FirstShiftRow = NewLensletGridModel.FirstPosShiftRow; Olduu(FirstShiftRow:2:end,:) = Olduu(FirstShiftRow:2:end,:) + HexAspect/2; else fprintf('...'); end DT = delaunayTriangulation( Olduu(:), Oldvv(:) ); % use DelaunayTri in older Matlab versions [ti,bc] = pointLocation(DT, Newuu(:), Newvv(:)); ti(isnan(ti)) = 1; for( ColChan = 1:size(LF,5) ) fprintf('.'); for( tidx= 1:LFSize(1) ) for( sidx= 1:LFSize(2) ) CurUVSlice = squeeze(LF(tidx,sidx,:,:,ColChan)); triVals = CurUVSlice(DT(ti,:)); CurUVSlice = dot(bc',triVals')'; CurUVSlice = reshape(CurUVSlice, [length(NewVVec),length(NewUVec)]); CurUVSlice(isnan(CurUVSlice)) = 0; LF2(tidx,sidx, :,:, ColChan) = CurUVSlice; end end end LF = LF2; clear LF2 DecodeOptions.OutputScale(3) = DecodeOptions.OutputScale(3) * HexAspect; otherwise fprintf('\nNo valid dehex / resampling selected\n'); end %---Resize to square s,t pixels--- % Assumes only a very slight resampling is required, resulting in an identically-sized output light field if( DecodeOptions.DoSquareST ) fprintf('\nResizing to square s,t pixels using 1D linear interp...'); ResizeScale = DecodeOptions.OutputScale(1)/DecodeOptions.OutputScale(2); ResizeDim1 = 1; ResizeDim2 = 2; if( ResizeScale < 1 ) ResizeScale = 1/ResizeScale; ResizeDim1 = 2; ResizeDim2 = 1; end OrigSize = size(LF, ResizeDim1); OrigVec = floor((-(OrigSize-1)/2):((OrigSize-1)/2)); NewVec = OrigVec ./ ResizeScale; OrigDims = [1:ResizeDim1-1, ResizeDim1+1:5]; UBlkSize = 32; USize = size(LF,4); LF = permute(LF,[ResizeDim1, OrigDims]); for( UStart = 1:UBlkSize:USize ) UStop = UStart + UBlkSize - 1; UStop = min(UStop, USize); LF(:,:,:,UStart:UStop,:) = interp1(OrigVec, LF(:,:,:,UStart:UStop,:), NewVec); fprintf('.'); end LF = ipermute(LF,[ResizeDim1, OrigDims]); LF(isnan(LF)) = 0; DecodeOptions.OutputScale(ResizeDim2) = DecodeOptions.OutputScale(ResizeDim2) * ResizeScale; end %---Trim s,t--- LF = LF(2:end-1,2:end-1, :,:, :); %---Slice out LFWeight if it was requested--- if( nargout >= 2 ) LFWeight = LF(:,:,:,:,end); LFWeight = LFWeight./max(LFWeight(:)); LF = LF(:,:,:,:,1:end-1); end end %------------------------------------------------------------------------------------------------------ function LF = SliceXYImage( LensletGridModel, LensletImage, WhiteImage, DecodeOptions ) % todo[optimization]: The SliceIdx and ValidIdx variables could be precomputed fprintf('\nSlicing lenslets into LF...'); USize = LensletGridModel.UMax; VSize = LensletGridModel.VMax; MaxSpacing = max(LensletGridModel.HSpacing, LensletGridModel.VSpacing); % Enforce square output in s,t SSize = MaxSpacing + 1; % force odd for centered middle pixel -- H,VSpacing are even, so +1 is odd TSize = MaxSpacing + 1; LF = zeros(TSize, SSize, VSize, USize, DecodeOptions.NColChans + DecodeOptions.NWeightChans, DecodeOptions.Precision); TVec = cast(floor((-(TSize-1)/2):((TSize-1)/2)), 'int16'); SVec = cast(floor((-(SSize-1)/2):((SSize-1)/2)), 'int16'); VVec = cast(0:VSize-1, 'int16'); UBlkSize = 32; for( UStart = 0:UBlkSize:USize-1 ) % note zero-based indexing UStop = UStart + UBlkSize - 1; UStop = min(UStop, USize-1); UVec = cast(UStart:UStop, 'int16'); [tt,ss,vv,uu] = ndgrid( TVec, SVec, VVec, UVec ); %---Build indices into 2D image--- LFSliceIdxX = LensletGridModel.HOffset + uu.*LensletGridModel.HSpacing + ss; LFSliceIdxY = LensletGridModel.VOffset + vv.*LensletGridModel.VSpacing + tt; HexShiftStart = LensletGridModel.FirstPosShiftRow; LFSliceIdxX(:,:,HexShiftStart:2:end,:) = LFSliceIdxX(:,:,HexShiftStart:2:end,:) + LensletGridModel.HSpacing/2; %---Lenslet mask in s,t and clip at image edges--- CurSTAspect = DecodeOptions.OutputScale(1)/DecodeOptions.OutputScale(2); R = sqrt((cast(tt,DecodeOptions.Precision)*CurSTAspect).^2 + cast(ss,DecodeOptions.Precision).^2); ValidIdx = find(R < LensletGridModel.HSpacing/2 & ... LFSliceIdxX >= 1 & LFSliceIdxY >= 1 & LFSliceIdxX <= size(LensletImage,2) & LFSliceIdxY <= size(LensletImage,1) ); %--clip -- the interp'd values get ignored via ValidIdx-- LFSliceIdxX = max(1, min(size(LensletImage,2), LFSliceIdxX )); LFSliceIdxY = max(1, min(size(LensletImage,1), LFSliceIdxY )); %--- LFSliceIdx = sub2ind(size(LensletImage), cast(LFSliceIdxY,'int32'), ... cast(LFSliceIdxX,'int32'), ones(size(LFSliceIdxX),'int32')); tt = tt - min(tt(:)) + 1; ss = ss - min(ss(:)) + 1; vv = vv - min(vv(:)) + 1; uu = uu - min(uu(:)) + 1 + UStart; LFOutSliceIdx = sub2ind(size(LF), cast(tt,'int32'), cast(ss,'int32'), ... cast(vv,'int32'),cast(uu,'int32'), ones(size(ss),'int32')); %--- for( ColChan = 1:DecodeOptions.NColChans ) LF(LFOutSliceIdx(ValidIdx) + numel(LF(:,:,:,:,1)).*(ColChan-1)) = ... LensletImage( LFSliceIdx(ValidIdx) + numel(LensletImage(:,:,1)).*(ColChan-1) ); end if( DecodeOptions.NWeightChans ~= 0 ) LF(LFOutSliceIdx(ValidIdx) + numel(LF(:,:,:,:,1)).*(DecodeOptions.NColChans)) = ... WhiteImage( LFSliceIdx(ValidIdx) ); end fprintf('.'); end end
github
hazirbas/light-field-toolbox-master
LFHelperBuild2DFreq.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFHelperBuild2DFreq.m
3,367
utf_8
3cd16d8e0a260aa2447e46ea325a04f9
% LFHelperBuild2DFreq - Helper function used to construct 2D frequency-domain filters % % Much of the complexity in constructing MD frequency-domain filters, especially around including aliased components and % controlling the filter rolloff, is common between filter shapes. This function wraps much of this complexity. % % This gets called by the LFBuild2DFreq* functions. % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [H, FiltOptions] = LFHelperBuild2DFreq( LFSize, BW, FiltOptions, DistFunc ) FiltOptions = LFDefaultField('FiltOptions', 'Precision', 'single'); FiltOptions = LFDefaultField('FiltOptions', 'Rolloff', 'Gaussian'); %Gaussian or Butter FiltOptions = LFDefaultField('FiltOptions', 'Aspect2D', 1); FiltOptions = LFDefaultField('FiltOptions', 'Window', false); FiltOptions = LFDefaultField('FiltOptions', 'Extent2D', 1.0); FiltOptions = LFDefaultField('FiltOptions', 'IncludeAliased', false); FiltOptions.Extent2D = cast(FiltOptions.Extent2D, FiltOptions.Precision); % avoid rounding error during comparisons FiltOptions.Aspect2D = cast(FiltOptions.Aspect2D, FiltOptions.Precision); % avoid rounding error during comparisons if( length(LFSize) == 1 ) LFSize = LFSize .* [1,1]; end if( length(FiltOptions.Extent2D) == 1 ) FiltOptions.Extent2D = FiltOptions.Extent2D .* [1,1]; end if( length(FiltOptions.Aspect2D) == 1 ) FiltOptions.Aspect2D = FiltOptions.Aspect2D .* [1,1]; end ExtentWithAspect = FiltOptions.Extent2D.*FiltOptions.Aspect2D / 2; s = LFNormalizedFreqAxis( LFSize(1), FiltOptions.Precision ) .* FiltOptions.Aspect2D(1); u = LFNormalizedFreqAxis( LFSize(2), FiltOptions.Precision ) .* FiltOptions.Aspect2D(2); [ss,uu] = ndgrid(s,u); P = [ss(:),uu(:)]'; clear s u ss uu if( ~FiltOptions.IncludeAliased ) Tiles = [0,0]; else Tiles = ceil(ExtentWithAspect); end if( FiltOptions.IncludeAliased ) AADist = inf(LFSize, FiltOptions.Precision); end WinDist = 0; % Tiling proceeds only in positive directions, symmetry is enforced afterward, saving some computation overall for( STile = 0:Tiles(1) ) for( UTile = 0:Tiles(2) ) Dist = inf(LFSize, FiltOptions.Precision); if( FiltOptions.Window ) ValidIdx = ':'; WinDist = bsxfun(@minus, abs(P)', ExtentWithAspect); WinDist = sum(max(0,WinDist).^2, 2); WinDist = reshape(WinDist, LFSize); else ValidIdx = find(all(bsxfun(@le, abs(P), ExtentWithAspect'))); end Dist(ValidIdx) = DistFunc(P(:,ValidIdx), FiltOptions); Dist = Dist + WinDist; if( FiltOptions.IncludeAliased ) AADist(:) = min(AADist(:), Dist(:)); end P(2,:) = P(2,:) + FiltOptions.Aspect2D(2); end P(2,:) = P(2,:) - (Tiles(2)+1) .* FiltOptions.Aspect2D(2); P(1,:) = P(1,:) + FiltOptions.Aspect2D(1); end if( FiltOptions.IncludeAliased ) Dist = AADist; clear AADist end H = zeros(LFSize, FiltOptions.Precision); switch lower(FiltOptions.Rolloff) case 'gaussian' BW = BW.^2 / log(sqrt(2)); H(:) = exp( -Dist / BW ); % Gaussian rolloff case 'butter' FiltOptions = LFDefaultField('FiltOptions', 'Order', 3); Dist = sqrt(Dist) ./ BW; H(:) = sqrt( 1.0 ./ (1.0 + Dist.^(2*FiltOptions.Order)) ); % Butterworth-like rolloff otherwise error('unrecognized rolloff method'); end H = ifftshift(H); % force symmetric H = max(H, H(mod(LFSize(1):-1:1,LFSize(1))+1, mod(LFSize(2):-1:1,LFSize(2))+1));
github
hazirbas/light-field-toolbox-master
LFFindLytroPartnerFile.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFFindLytroPartnerFile.m
1,439
utf_8
a4f3d1519bad3b234bde99c00a97ea3d
% LFFindLytroPartnerFile - Finds metadata / raw data file partner for Lytro white images % % Usage: % % PartnerFilename = LFFindLytroPartnerFile( OrigFilename, PartnerFilenameExtension ) % % The LF Reader tool prepends filenames extracted from LFP storage files, complicating .txt / .raw % file association as the prefix can vary between two files in a pair. This function finds a file's % partner based on a known filename pattern (using underscores to separate the base filename), and a % know partner filename extension. Note this is set up to work specifically with the naming % conventions used by the LFP Reader tool. % % Inputs: % OrigFilename is the known filename % PartnerFilenameExtension is the extension of the file to find % % Output: % PartnerFilename is the name of the first file found matching the specified extension % % See also: LFUtilProcessWhiteImages, LFUtilProcessCalibrations % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function PartnerFilename = LFFindLytroPartnerFile( OrigFilename, PartnerFilenameExtension ) [CurFnamePath, CurFnameBase] = fileparts( OrigFilename ); PrependIdx = find(CurFnameBase == '_', 1); CurFnamePattern = strcat('*', CurFnameBase(PrependIdx:end), PartnerFilenameExtension); DirResult = dir(fullfile(CurFnamePath, CurFnamePattern)); DirResult = DirResult(1).name; PartnerFilename = fullfile(CurFnamePath, DirResult); end
github
hazirbas/light-field-toolbox-master
LFVar2Struct.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFVar2Struct.m
646
utf_8
8e9d0eed0d9242fdf45c14ba302e05d2
% LFVar2Struct - Convenience function to build a struct from a set of variables % % Usage: % StructOut = LFVar2Struct( var1, var2, ... ) % % Example: % Apples = 3; % Oranges = 4; % FruitCount = LFVar2Struct( Apples, Oranges ) % % Results in a struct FruitCount: % FruitCount = % Apples: 3 % Oranges: 4 % % See also: LFStruct2Var % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function StructOut = LFVar2Struct( varargin ) VarNames = arrayfun( @inputname, 1:nargin, 'UniformOutput', false ); StructOut = cell2struct( varargin, VarNames, 2 ); end
github
hazirbas/light-field-toolbox-master
LFBuildLensletGridModel.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFBuildLensletGridModel.m
9,749
utf_8
77a704b9345494e7a5ab0bc07f763d10
% LFBuildLensletGridModel - builds a lenslet grid model from a white image, called by LFUtilProcessWhiteImages % % Usage: % [LensletGridModel, GridCoords] = LFBuildLensletGridModel( WhiteImg, GridModelOptions, DebugDisplay ) % % Inputs: % WhiteImg : path of an image taken through a diffuser, or of an entirely white scene % % GridModelOptions : struct controlling the model-bulding options % .ApproxLensletSpacing : A rough initial estimate to initialize the lenslet spacing % computation % .FilterDiskRadiusMult : Filter disk radius for prefiltering white image for locating % lenslets; expressed relative to lenslet spacing; e.g. a % value of 1/3 means a disk filte with a radius of 1/3 the % lenslet spacing % .CropAmt : Image edge pixels to ignore when finding the grid % .SkipStep : As a speed optimization, not all lenslet centers contribute % to the grid estimate; <SkipStep> pixels are skipped between % lenslet centers that get used; a value of 1 means use all % [optional] .Precision : 'single' or 'double' % % [optional] DebugDisplay : enables a debugging display, default false % % Outputs: % % LensletGridModel : struct describing the lenslet grid % .HSpacing, .VSpacing : Spacing between lenslets, in pixels % .HOffset, .VOffset : Offset of first lenslet, in pixels % .Rot : Rotation of lenslets, in radians % % GridCoords : a list of N x M x 2 pixel coordinates generated from the estimated % LensletGridModel, where N and M are the estimated number of lenslets in the % horizontal and vertical directions, respectively. % % See also: LFUtilProcessWhiteImages % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [LensletGridModel, GridCoords] = LFBuildLensletGridModel( WhiteImg, GridModelOptions, DebugDisplay ) %---Defaults--- GridModelOptions = LFDefaultField( 'GridModelOptions', 'Precision', 'single' ); DebugDisplay = LFDefaultVal( 'DebugDisplay', false ); %---Optionally rotate for vertically-oriented grids--- if( strcmpi(GridModelOptions.Orientation, 'vert') ) WhiteImg = WhiteImg'; end % Try locating lenslets by convolving with a disk % Also tested Gaussian... the disk seems to yield a stronger result h = zeros( size(WhiteImg), GridModelOptions.Precision ); hr = fspecial( 'disk', GridModelOptions.ApproxLensletSpacing * GridModelOptions.FilterDiskRadiusMult ); hr = hr ./ max( hr(:) ); hs = size( hr,1 ); DiskOffset = round( (size(WhiteImg) - hs)/2 ); h( (1:hs) + DiskOffset(1), (1:hs) + DiskOffset(2) ) = hr; fprintf( 'Filtering...\n' ); % Convolve using fft WhiteImg = fft2(WhiteImg); h = fft2(h); WhiteImg = WhiteImg.*h; WhiteImg = ifftshift(ifft2(WhiteImg)); WhiteImg = (WhiteImg - min(WhiteImg(:))) ./ abs(max(WhiteImg(:))-min(WhiteImg(:))); WhiteImg = cast(WhiteImg, GridModelOptions.Precision); clear h fprintf('Finding Peaks...\n'); % Find peaks in convolution... ideally these are the lenslet centers Peaks = imregionalmax(WhiteImg); PeakIdx = find(Peaks==1); [PeakIdxY,PeakIdxX] = ind2sub(size(Peaks),PeakIdx); clear Peaks % Crop to central peaks; eliminates edge effects InsidePts = find(PeakIdxY>GridModelOptions.CropAmt & PeakIdxY<size(WhiteImg,1)-GridModelOptions.CropAmt & ... PeakIdxX>GridModelOptions.CropAmt & PeakIdxX<size(WhiteImg,2)-GridModelOptions.CropAmt); PeakIdxY = PeakIdxY(InsidePts); PeakIdxX = PeakIdxX(InsidePts); %---Form a Delaunay triangulation to facilitate row/column traversal--- Triangulation = DelaunayTri(PeakIdxY, PeakIdxX); %---Traverse rows and columns of lenslets, collecting stats--- if( DebugDisplay ) LFFigure(3); cla imagesc( WhiteImg ); colormap gray hold on end %--Traverse vertically-- fprintf('Vertical fit...\n'); YStart = GridModelOptions.CropAmt*2; YStop = size(WhiteImg,1)-GridModelOptions.CropAmt*2; XIdx = 1; for( XStart = GridModelOptions.CropAmt*2:GridModelOptions.SkipStep:size(WhiteImg,2)-GridModelOptions.CropAmt*2 ) CurPos = [XStart, YStart]; YIdx = 1; while( 1 ) ClosestLabel = nearestNeighbor(Triangulation, CurPos(2), CurPos(1)); ClosestPt = [PeakIdxX(ClosestLabel), PeakIdxY(ClosestLabel)]; RecPtsY(XIdx,YIdx,:) = ClosestPt; if( DebugDisplay ) plot( ClosestPt(1), ClosestPt(2), 'r.' ); end CurPos = ClosestPt; CurPos(2) = round(CurPos(2) + GridModelOptions.ApproxLensletSpacing * sqrt(3)); if( CurPos(2) > YStop ) break; end YIdx = YIdx + 1; end %--Estimate angle for this most recent line-- LineFitY(XIdx,:) = polyfit(RecPtsY(XIdx, 3:end-3,2), RecPtsY(XIdx, 3:end-3,1), 1); XIdx = XIdx + 1; end if( DebugDisplay ) drawnow; end %--Traverse horizontally-- fprintf('Horizontal fit...\n'); XStart = GridModelOptions.CropAmt*2; XStop = size(WhiteImg,2)-GridModelOptions.CropAmt*2; YIdx = 1; for( YStart = GridModelOptions.CropAmt*2:GridModelOptions.SkipStep:size(WhiteImg,1)-GridModelOptions.CropAmt*2 ) CurPos = [XStart, YStart]; XIdx = 1; while( 1 ) ClosestLabel = nearestNeighbor(Triangulation, CurPos(2), CurPos(1)); ClosestPt = [PeakIdxX(ClosestLabel), PeakIdxY(ClosestLabel)]; RecPtsX(XIdx,YIdx,:) = ClosestPt; if( DebugDisplay ) plot( ClosestPt(1), ClosestPt(2), 'y.' ); end CurPos = ClosestPt; CurPos(1) = round(CurPos(1) + GridModelOptions.ApproxLensletSpacing); if( CurPos(1) > XStop ) break; end XIdx = XIdx + 1; end %--Estimate angle for this most recent line-- LineFitX(YIdx,:) = polyfit(RecPtsX(3:end-3,YIdx,1), RecPtsX(3:end-3,YIdx,2), 1); YIdx = YIdx + 1; end if( DebugDisplay ) drawnow; end %--Trim ends to wipe out alignment, initial estimate artefacts-- RecPtsY = RecPtsY(3:end-2, 3:end-2,:); RecPtsX = RecPtsX(3:end-2, 3:end-2,:); %--Estimate angle-- SlopeX = mean(LineFitX(:,1)); SlopeY = mean(LineFitY(:,1)); AngleX = atan2(-SlopeX,1); AngleY = atan2(SlopeY,1); EstAngle = mean([AngleX,AngleY]); %--Estimate spacing, assuming approx zero angle-- t=squeeze(RecPtsY(:,:,2)); YSpacing = diff(t,1,2); YSpacing = mean(YSpacing(:))/2 / (sqrt(3)/2); t=squeeze(RecPtsX(:,:,1)); XSpacing = diff(t,1,1); XSpacing = mean(XSpacing(:)); %--Correct for angle-- XSpacing = XSpacing / cos(EstAngle); YSpacing = YSpacing / cos(EstAngle); %--Build initial grid estimate, starting with CropAmt for the offsets-- LensletGridModel = struct('HSpacing',XSpacing, 'VSpacing',YSpacing*sqrt(3)/2, 'HOffset',GridModelOptions.CropAmt, ... 'VOffset',GridModelOptions.CropAmt, 'Rot',-EstAngle, 'Orientation', GridModelOptions.Orientation, ... 'FirstPosShiftRow', 2 ); LensletGridModel.UMax = ceil( (size(WhiteImg,2)-GridModelOptions.CropAmt*2)/XSpacing ); LensletGridModel.VMax = ceil( (size(WhiteImg,1)-GridModelOptions.CropAmt*2)/YSpacing/(sqrt(3)/2) ); GridCoords = LFBuildHexGrid( LensletGridModel ); %--Find offset to nearest peak for each-- GridCoordsX = GridCoords(:,:,1); GridCoordsY = GridCoords(:,:,2); BuildGridCoords = [GridCoordsX(:), GridCoordsY(:)]; IdealPts = nearestNeighbor(Triangulation, round(GridCoordsY(:)), round(GridCoordsX(:))); IdealPtCoords = [PeakIdxX(IdealPts), PeakIdxY(IdealPts)]; %--Estimate single offset for whole grid-- EstOffset = IdealPtCoords - BuildGridCoords; EstOffset = median(EstOffset); LensletGridModel.HOffset = LensletGridModel.HOffset + EstOffset(1); LensletGridModel.VOffset = LensletGridModel.VOffset + EstOffset(2); %--Remove crop offset / find top-left lenslet-- NewVOffset = mod( LensletGridModel.VOffset, LensletGridModel.VSpacing ); VSteps = round( (LensletGridModel.VOffset - NewVOffset) / LensletGridModel.VSpacing ); % should be a whole number VStepParity = mod( VSteps, 2 ); if( VStepParity == 1 ) LensletGridModel.HOffset = LensletGridModel.HOffset + LensletGridModel.HSpacing/2; end NewHOffset = mod( LensletGridModel.HOffset, LensletGridModel.HSpacing/2 ); HSteps = round( (LensletGridModel.HOffset - NewHOffset) / (LensletGridModel.HSpacing/2) ); % should be a whole number HStepParity = mod( HSteps, 2 ); LensletGridModel.FirstPosShiftRow = 2-HStepParity; if( DebugDisplay ) plot( LensletGridModel.HOffset, LensletGridModel.VOffset, 'ro' ); plot( NewHOffset, NewVOffset, 'yx'); drawnow end LensletGridModel.HOffset = NewHOffset; LensletGridModel.VOffset = NewVOffset; %---Finalize grid--- LensletGridModel.UMax = floor((size(WhiteImg,2)-LensletGridModel.HOffset)/LensletGridModel.HSpacing) + 1; LensletGridModel.VMax = floor((size(WhiteImg,1)-LensletGridModel.VOffset)/LensletGridModel.VSpacing) + 1; GridCoords = LFBuildHexGrid( LensletGridModel ); fprintf('...Done.\n'); end function [GridCoords] = LFBuildHexGrid( LensletGridModel ) RotCent = eye(3); RotCent(1:2,3) = [LensletGridModel.HOffset, LensletGridModel.VOffset]; ToOffset = eye(3); ToOffset(1:2,3) = [LensletGridModel.HOffset, LensletGridModel.VOffset]; R = ToOffset * RotCent * LFRotz(LensletGridModel.Rot) * RotCent^-1; [vv,uu] = ndgrid((0:LensletGridModel.VMax-1).*LensletGridModel.VSpacing, (0:LensletGridModel.UMax-1).*LensletGridModel.HSpacing); uu(LensletGridModel.FirstPosShiftRow:2:end,:) = uu(LensletGridModel.FirstPosShiftRow:2:end,:) + 0.5.*LensletGridModel.HSpacing; GridCoords = [uu(:), vv(:), ones(numel(vv),1)]; GridCoords = (R*GridCoords')'; GridCoords = reshape(GridCoords(:,1:2), [LensletGridModel.VMax,LensletGridModel.UMax,2]); end
github
hazirbas/light-field-toolbox-master
LFDefaultVal.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFDefaultVal.m
1,291
utf_8
c246f7b5e263b013ced34d42170f53b4
% LFDefaultVal - Convenience function to set up default parameter values % % Usage: % % Var = LFDefaultVal( Var, DefaultVal ) % % % This provides an elegant way to establish default parameter values. See LFDefaultField for setting % up structs with default field values. % % Inputs: % % Var: string giving the name of the parameter % DefaultVal: default value for the parameter % % % Outputs: % % Var: if the parameter already existed, the output matches its original value, otherwise the % output takes on the specified default value % % Example: % % clearvars % ExistingVar = 42; % ExistingVar = LFDefaultVal( 'ExistingVar', 3 ) % OtherVar = LFDefaultVal( 'OtherVar', 3 ) % % Results in : % ExistingVar = % 42 % OtherVar = % 3 % % Usage for setting up default function arguments is demonstrated in most of the LF Toolbox % functions. % % See also: LFDefaultField % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function Var = LFDefaultVal( Var, DefaultVal ) CheckIfExists = sprintf('exist(''%s'', ''var'') && ~isempty(%s)', Var, Var); VarExists = evalin( 'caller', CheckIfExists ); if( ~VarExists ) Var = DefaultVal; else Var = evalin( 'caller', Var ); end end
github
hazirbas/light-field-toolbox-master
LFDispSetup.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFDispSetup.m
2,717
utf_8
018642a726ed8feb41058f29f9ffeb14
% LFDispSetup - helper function used to set up a light field display % % Usage: % % [ImageHandle, FigureHandle] = LFDispSetup( InitialFrame ) % [ImageHandle, FigureHandle] = LFDispSetup( InitialFrame, ScaleFactor ) % % % This sets up a figure for LFDispMousePan and LFDispVidCirc. The figure is configured for % high-performance display, and subsequent calls will reuse the same figure, rather than creating a % new window on each call. The function should handle both mono and colour images. % % % Inputs: % % InitialFrame : a 2D image with which to start the display % % Optional Inputs: % % ScaleFactor : Adjusts the size of the display -- 1 means no change, 2 means twice as big, etc. % Integer values are recommended to avoid scaling artifacts. Note that the scale % factor is only applied the first time a figure is created -- i.e. the figure % must be closed to make a change to scale. % % Outputs: % % FigureHandle, ImageHandle : handles of the created objects % % % See also: LFDispVidCirc, LFDispMousePan % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [ImageHandle, FigureHandle] = LFDispSetup( InitialFrame, ScaleFactor ) FigureHandle = findobj('tag','LFDisplay'); if( isempty(FigureHandle) ) % Get screen size set( 0, 'units','pixels' ); ScreenSize = get( 0, 'screensize' ); ScreenSize = ScreenSize(3:4); % Get LF display size FrameSize = [size(InitialFrame,2),size(InitialFrame,1)]; % Create the figure FigureHandle = figure(... 'doublebuffer','on',... 'backingstore','off',... ...%'menubar','none',... ...%'toolbar','none',... 'tag','LFDisplay'); % Set the window's position and size WindowPos = get( FigureHandle, 'Position' ); WindowPos(3:4) = FrameSize; WindowPos(1:2) = floor( (ScreenSize - FrameSize)./2 ); set( FigureHandle, 'Position', WindowPos ); % Set the axis position and size within the figure AxesPos = [0,0,size(InitialFrame,2),size(InitialFrame,1)]; axes('units','pixels',... 'Position', AxesPos,... 'xlimmode','manual',... 'ylimmode','manual',... 'zlimmode','manual',... 'climmode','manual',... 'alimmode','manual',... 'layer','bottom'); ImageHandle = imshow(InitialFrame); % If a scaling factor is requested, apply it if( exist('ScaleFactor','var') ) truesize(floor(ScaleFactor*size(InitialFrame(:,:,1)))); end else ImageHandle = findobj(FigureHandle,'type','image'); set(ImageHandle,'cdata', InitialFrame); end
github
hazirbas/light-field-toolbox-master
LFGatherCamInfo.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFGatherCamInfo.m
2,778
utf_8
c0acfa7e282c05682ab4f98ab740a59c
% LFGatherCamInfo - collect metadata from a folder of processed white images or calibrations % % Usage: % % CamInfo = LFGatherCamInfo( FilePath, FilenamePattern ) % % % This function is designed to work with one of two sources of information: a folder of Lytro white % images, as extracted from the calibration data using an LFP tool; or a folder of calibrations, as % generated by LFUtilCalLensletCam. % % Inputs: % % FilePath is a path to the folder containing either the white images or the calibration files. % % FilenamePattern is a pattern, with wildcards, identifying the metadata files to process. Typical % values are 'CalInfo*.json' for calibration info, and '*T1CALIB__MOD_*.TXT' for white images. % % Outputs: % % CamInfo is a struct array containing zoom, focus and filename info for each file. Exposure info % is also included for white images. % % See LFUtilProcessCalibrations and LFUtilProcessWhiteImages for example usage. % % See also: LFUtilProcessWhiteImages, LFUtilProcessCalibrations % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function CamInfo = LFGatherCamInfo( FilePath, FilenamePattern ) %---Locate all input files--- [FileNames, BasePath] = LFFindFilesRecursive( FilePath, FilenamePattern ); if( isempty(FileNames) ) error('No files found'); end fprintf('Found :\n'); disp(FileNames) %---Process each--- fprintf('Filename, Camera Model / Serial, ZoomStep, FocusStep\n'); for( iFile = 1:length(FileNames) ) CurFname = FileNames{iFile}; CurFileInfo = LFReadMetadata( fullfile(BasePath, CurFname) ); CurCamInfo = []; if( isfield( CurFileInfo, 'CamInfo' ) ) %---Calibration file--- CurCamInfo = CurFileInfo.CamInfo; elseif( isfield( CurFileInfo, 'master' ) ) %---Lytro TXT metadata file associated with white image--- CurCamInfo.ZoomStep = CurFileInfo.master.picture.frameArray.frame.metadata.devices.lens.zoomStep; CurCamInfo.FocusStep = CurFileInfo.master.picture.frameArray.frame.metadata.devices.lens.focusStep; CurCamInfo.ExposureDuration = CurFileInfo.master.picture.frameArray.frame.metadata.devices.shutter.frameExposureDuration; CurCamInfo.CamSerial = CurFileInfo.master.picture.frameArray.frame.privateMetadata.camera.serialNumber; CurCamInfo.CamModel = CurFileInfo.master.picture.frameArray.frame.metadata.camera.model; else error('Unrecognized file format reading metadata\n'); end fprintf(' %s :\t%s / %s, %d, %d\n', CurFname, CurCamInfo.CamModel, CurCamInfo.CamSerial, CurCamInfo.ZoomStep, CurCamInfo.FocusStep); CurCamInfo.Fname = CurFname; CamInfo(iFile) = CurCamInfo; end
github
hazirbas/light-field-toolbox-master
LFToolboxVersion.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFToolboxVersion.m
252
utf_8
d37c67edd0424685c2530c25195c3826
% LFToolboxVersion - returns a string describing the current toolbox version % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function VersionStr = LFToolboxVersion VersionStr = 'v0.4 released 12-Feb-2015';
github
hazirbas/light-field-toolbox-master
LFStruct2Var.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFStruct2Var.m
871
utf_8
bd1821a5700012dfce0f79c4d5dd8ab0
% LFStruct2Var - Convenience function to break a subset of variables out of a struct % % Usage: % [var1, var2, ...] = LFStruct2Var( StructIn, 'var1', 'var2', ... ) % % This would ideally exclude the named variables in the argument list, but there was no elegant way % to do this given the absence of an `outputname' function to match Matlab's `inputname'. % % Example: % FruitCount = struct('Apples', 3, 'Bacon', 42, 'Oranges', 4); % [Apples, Oranges] = LFStruct2Var( FruitCount, 'Apples', 'Oranges' ) % % Results in % Apples = % 3 % Oranges = % 4 % % See also: LFStruct2Var % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function varargout = LFStruct2Var( StructIn, varargin ) for( i=1:length(varargin) ) varargout{i} = StructIn.(varargin{i}); end end
github
hazirbas/light-field-toolbox-master
LFFindCalInfo.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFFindCalInfo.m
2,572
utf_8
c7daafa528ed72904c233ed5ad834fe6
% LFFindCalInfo - Find and load the calibration info file appropriate for a specific camera, zoom and focus % % Usage: % % [CalInfo, RectOptions] = LFFindCalInfo( LFMetadata, RectOptions ) % % This uses a calibration info database to locate a calibration appropriate to a given camera under a given set of zoom % and focus settings. It is called during rectification. % % Inputs: % % LFMetadata : loaded from a decoded light field, this contains the camera's serial number and zoom and focus settings. % RectOptions : struct controlling rectification % .CalibrationDatabaseFname : name of the calibration file database % % % Outputs: % % CalInfo: The resulting calibration info, or an empty array if no appropriate calibration found % RectOptions : struct controlling rectification, the following fields are added % .CalInfoFname : Name of the calibration file that was loaded % % See also: LFUtilProcessCalibrations, LFSelectFromDatabase % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function [CalInfo, RectOptions] = LFFindCalInfo( LFMetadata, RectOptions ) CalInfo = []; DesiredCam = struct('CamSerial', LFMetadata.SerialData.camera.serialNumber, ... 'ZoomStep', LFMetadata.devices.lens.zoomStep, ... 'FocusStep', LFMetadata.devices.lens.focusStep ); CalFileInfo = LFSelectFromDatabase( DesiredCam, RectOptions.CalibrationDatabaseFname ); if( isempty(CalFileInfo) ) return; end PathToDatabase = fileparts( RectOptions.CalibrationDatabaseFname ); RectOptions.CalInfoFname = CalFileInfo.Fname; CalInfo = LFReadMetadata( fullfile(PathToDatabase, RectOptions.CalInfoFname) ); fprintf('Loading %s\n', RectOptions.CalInfoFname); %---Check that the decode options and calibration info are a good match--- fprintf('\nCalibration / LF Picture (ideally these match exactly):\n'); fprintf('Serial:\t%s\t%s\n', CalInfo.CamInfo.CamSerial, LFMetadata.SerialData.camera.serialNumber); fprintf('Zoom:\t%d\t\t%d\n', CalInfo.CamInfo.ZoomStep, LFMetadata.devices.lens.zoomStep); fprintf('Focus:\t%d\t\t%d\n\n', CalInfo.CamInfo.FocusStep, LFMetadata.devices.lens.focusStep); if( ~strcmp(CalInfo.CamInfo.CamSerial, LFMetadata.SerialData.camera.serialNumber) ) warning('Calibration is for a different camera, rectification may be invalid.'); end if( CalInfo.CamInfo.ZoomStep ~= LFMetadata.devices.lens.zoomStep || ... CalInfo.CamInfo.FocusStep ~= LFMetadata.devices.lens.focusStep ) warning('Zoom / focus mismatch -- for significant deviations rectification may be invalid.'); end
github
hazirbas/light-field-toolbox-master
LFConvertToFloat.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFConvertToFloat.m
481
utf_8
347631d509cdee15114cff38f1046966
% LFConvertToFloat - Helper function to convert light fields to floating-point representation % % Integer inputs get normalized to a max value of 1. % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function LF = LFConvertToFloat( LF, Precision ) Precision = LFDefaultVal('Precision', 'single'); OrigClass = class(LF); IsInt = isinteger(LF); LF = cast(LF, Precision); if( IsInt ) LF = LF ./ cast(intmax(OrigClass), Precision); end
github
hazirbas/light-field-toolbox-master
LFUnpackRawBuffer.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFUnpackRawBuffer.m
2,263
utf_8
6edde771ccfa5abb4c1b0242c9ee9af9
% LFUnpackRawBuffer - Unpack a buffer of packed raw binary data into an image % % Usage: % % ImgOut = LFUnpackRawBuffer( Buff, BitPacking, ImgSize ) % % Used by LFReadRaw and LFReadLFP, this helper function unpacks a raw binary data buffer in one of several formats. % % Inputs : % % Buff : Buffer of chars to be unpacked % BitPacking : one of '12bit', '10bit' or '16bit'; default is '12bit' % ImgSize : size of the output image % % Outputs: % % Img : an array of uint16 gray levels. No demosaicing (decoding Bayer pattern) is performed. % % See also: LFDecodeLensletImageSimple, demosaic % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function ImgOut = LFUnpackRawBuffer( Buff, BitPacking, ImgSize ) switch( BitPacking ) case '8bit' ImgOut = reshape(Buff, ImgSize); case '10bit' t0 = uint16(Buff(1:5:end)); t1 = uint16(Buff(2:5:end)); t2 = uint16(Buff(3:5:end)); t3 = uint16(Buff(4:5:end)); lsb = uint16(Buff(5:5:end)); t0 = bitshift(t0,2); t1 = bitshift(t1,2); t2 = bitshift(t2,2); t3 = bitshift(t3,2); t0 = t0 + bitand(lsb,bin2dec('00000011')); t1 = t1 + bitshift(bitand(lsb,bin2dec('00001100')),-2); t2 = t2 + bitshift(bitand(lsb,bin2dec('00110000')),-4); t3 = t3 + bitshift(bitand(lsb,bin2dec('11000000')),-6); ImgOut = zeros(ImgSize, 'uint16'); ImgOut(1:4:end) = t0; ImgOut(2:4:end) = t1; ImgOut(3:4:end) = t2; ImgOut(4:4:end) = t3; case '12bit' t0 = uint16(Buff(1:3:end)); t1 = uint16(Buff(2:3:end)); t2 = uint16(Buff(3:3:end)); a0 = bitshift(t0,4) + bitshift(bitand(t1,bin2dec('11110000')),-4); a1 = bitshift(bitand(t1,bin2dec('00001111')),8) + t2; ImgOut = zeros(ImgSize, 'uint16'); ImgOut(1:2:end) = a0; ImgOut(2:2:end) = a1; case '16bit' t0 = uint16(Buff(1:2:end)); t1 = uint16(Buff(2:2:end)); a0 = bitshift(t1, 8) + t0; ImgOut = zeros(ImgSize, 'uint16'); ImgOut(:) = a0; otherwise error('Unrecognized bit packing'); end
github
hazirbas/light-field-toolbox-master
LFCalFindCheckerCorners.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFCalFindCheckerCorners.m
8,816
utf_8
d8f59cd55e2ed367addcfa426036fbe0
% LFCalFindCheckerCorners - locates corners in checkerboard images, called by LFUtilCalLensletCam % % Usage: % CalOptions = LFCalFindCheckerCorners( InputPath, CalOptions ) % CalOptions = LFCalFindCheckerCorners( InputPath ) % % This function is called by LFUtilCalLensletCam to identify the corners in a set of checkerboard % images. % % Inputs: % % InputPath : Path to folder containing decoded checkerboard images. % % [optional] CalOptions : struct controlling calibration parameters, all fields are optional % .CheckerCornersFnamePattern : Pattern for building output checkerboard corner files; %s is % used as a placeholder for the base filename % .LFFnamePattern : Filename pattern for locating input light fields % .ForceRedoCornerFinding : Forces the function to run, overwriting existing results % .ShowDisplay : Enables display, allowing visual verification of results % % Outputs : % % CalOptions struct as applied, including any default values as set up by the function % % Checker corner files are the key outputs of this function -- one file is generated fore each % input file, containing the list of extracted checkerboard corners. % % See also: LFUtilCalLensletCam, LFCalInit, LFCalRefine % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function CalOptions = LFCalFindCheckerCorners( InputPath, CalOptions ) %---Defaults--- CalOptions = LFDefaultField( 'CalOptions', 'ForceRedoCornerFinding', false ); CalOptions = LFDefaultField( 'CalOptions', 'LFFnamePattern', '%s__Decoded.mat' ); CalOptions = LFDefaultField( 'CalOptions', 'CheckerCornersFnamePattern', '%s__CheckerCorners.mat' ); CalOptions = LFDefaultField( 'CalOptions', 'ShowDisplay', true ); CalOptions = LFDefaultField( 'CalOptions', 'MinSubimageWeight', 0.2 * 2^16 ); % for fast rejection of dark frames %---Build a regular expression for stripping the base filename out of the full raw filename--- BaseFnamePattern = regexp(CalOptions.LFFnamePattern, '%s', 'split'); BaseFnamePattern = cell2mat({BaseFnamePattern{1}, '(.*)', BaseFnamePattern{2}}); %---Tagged onto all saved files--- TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); %---Crawl folder structure locating raw lenslet images--- fprintf('\n===Locating light fields in %s===\n', InputPath); [FileList, BasePath] = LFFindFilesRecursive( InputPath, sprintf(CalOptions.LFFnamePattern, '*') ); if( isempty(FileList) ) error(['No files found... are you running from the correct folder?\n'... ' Current folder: %s\n'], pwd); end; fprintf('Found :\n'); disp(FileList) %---Check zoom / focus and serial number settings across light fields--- fprintf('Checking zoom / focus / serial number across all files...\n'); for( iFile = 1:length(FileList) ) CurFname = FileList{iFile}; load(fullfile(BasePath, CurFname), 'LFMetadata'); CamSettings(iFile).Fname = CurFname; CamSettings(iFile).ZoomStep = LFMetadata.devices.lens.zoomStep; CamSettings(iFile).FocusStep = LFMetadata.devices.lens.focusStep; CamSettings(iFile).CamSerial = LFMetadata.SerialData.camera.serialNumber; end % Find the most frequent serial number [UniqueSerials,~,SerialIdx]=unique({CamSettings.CamSerial}); NumSerials = size(UniqueSerials,2); MostFreqSerialIdx = median(SerialIdx); CamInfo.CamSerial = UniqueSerials{MostFreqSerialIdx}; CamInfo.CamModel = LFMetadata.camera.model; % Finding the most frequent zoom / focus is easier CamInfo.FocusStep = median([CamSettings.FocusStep]); CamInfo.ZoomStep = median([CamSettings.ZoomStep]); fprintf( 'Serial: %s, ZoomStep: %d, FocusStep: %d\n', CamInfo.CamSerial, CamInfo.ZoomStep, CamInfo.FocusStep ); InvalidIdx = find( ... ([CamSettings.ZoomStep] ~= CamInfo.ZoomStep) | ... ([CamSettings.FocusStep] ~= CamInfo.FocusStep) | ... (SerialIdx ~= MostFreqSerialIdx)' ); if( ~isempty(InvalidIdx) ) warning('Some files mismatch'); for( iInvalid = InvalidIdx ) fprintf('Serial: %s, ZoomStep: %d, FocusStep: %d -- %s\n', CamSettings(iInvalid).CamSerial, CamSettings(iInvalid).ZoomStep, CamSettings(iInvalid).FocusStep, CamSettings(iInvalid).Fname); end fprintf('For significant deviations, it is recommended that these files be removed and the program restarted.'); else fprintf('...all files match\n'); end %---enable warning to display it once; gets disabled after first call to detectCheckerboardPoints-- warning('on','vision:calibrate:boardShouldBeAsymmetric'); fprintf('Skipping subimages with mean weight below MinSubimageWeight %g\n', CalOptions.MinSubimageWeight); %---Process each folder--- SkippedFileCount = 0; ProcessedFileCount = 0; TotFileTime = 0; %---Process each raw lenslet file--- for( iFile = 1:length(FileList) ) CurFname = FileList{iFile}; CurFname = fullfile(BasePath, CurFname); %---Build the base filename--- CurBaseFname = regexp(CurFname, BaseFnamePattern, 'tokens'); CurBaseFname = CurBaseFname{1}{1}; [~,ShortFname] = fileparts(CurBaseFname); fprintf(' --- %s [%d / %d]', ShortFname, iFile, length(FileList)); %---Check for already-decoded file--- SaveFname = sprintf(CalOptions.CheckerCornersFnamePattern, CurBaseFname); if( ~CalOptions.ForceRedoCornerFinding ) if( exist(SaveFname, 'file') ) fprintf( ' already done, skipping\n' ); SkippedFileCount = SkippedFileCount + 1; continue; end end ProcessedFileCount = ProcessedFileCount + 1; fprintf('\n'); %---Load the LF--- tic % track time load( CurFname, 'LF', 'LensletGridModel', 'DecodeOptions' ); LFSize = size(LF); if( CalOptions.ShowDisplay ) LFFigure(1); clf end fprintf('Processing all subimages'); for( TIdx = 1:LFSize(1) ) fprintf('.'); for( SIdx = 1:LFSize(2) ) % todo[optimization]: once a good set of corners is found, tracking them through s,u % and t,v would be significantly faster than independently recomputing the corners % for all u,v slices CurW = squeeze(LF(TIdx, SIdx, :,:, 4)); CurW = mean(CurW(:)); if( CurW < CalOptions.MinSubimageWeight ) CurCheckerCorners = []; else CurImg = squeeze(LF(TIdx, SIdx, :,:, 1:3)); CurImg = rgb2gray(CurImg); [CurCheckerCorners,CheckBoardSize] = detectCheckerboardPoints( CurImg ); warning('off','vision:calibrate:boardShouldBeAsymmetric'); % display once (at most) % Matlab's detectCheckerboardPoints sometimes expresses the grid in different orders, especially for % symmetric checkerbords. It's up to the consumer of this data to treat the points in the correct order. end HitCount(TIdx,SIdx) = numel(CurCheckerCorners); CheckerCorners{TIdx,SIdx} = CurCheckerCorners; end %---Display results--- if( CalOptions.ShowDisplay ) clf for( SIdx = 1:LFSize(2) ) if( HitCount(TIdx,SIdx) > 0 ) CurImg = squeeze(LF(TIdx, SIdx, :,:, 1:3)); CurImg = rgb2gray(CurImg); NImages = LFSize(2); NCols = ceil(sqrt(NImages)); NRows = ceil(NImages / NCols); subplot(NRows, NCols, SIdx); imshow(CurImg); colormap gray hold on; cx = CheckerCorners{TIdx,SIdx}(:,1); cy = CheckerCorners{TIdx,SIdx}(:,2); plot(cx(:),cy(:),'r.', 'markersize',15) axis off axis image axis tight end end %truesize([150,150]); % bigger display drawnow end end fprintf('\n'); %---Save--- fprintf('Saving result to %s...\n', SaveFname); save(SaveFname, 'GeneratedByInfo', 'CheckerCorners', 'LFSize', 'CamInfo', 'LensletGridModel', 'DecodeOptions'); TotFileTime = TotFileTime + toc; MeanFileTime = TotFileTime / ProcessedFileCount; fprintf( 'Mean time per file: %.1f min\n', MeanFileTime/60 ); TimeRemain_s = MeanFileTime * (length(FileList) - ProcessedFileCount - SkippedFileCount); fprintf( 'Est time remain: ~%d min\n', ceil(TimeRemain_s/60) ); end fprintf(' ---Finished finding checkerboard corners---\n');
github
hazirbas/light-field-toolbox-master
LFSelectFromDatabase.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFSelectFromDatabase.m
2,288
utf_8
f72e49d5261aad46cd204a67ea981f14
% LFSelectFromDatabase - support function for selecting white image/calibration by matching serial/zoom/focus % % Usage: % % SelectedCamInfo = LFSelectFromDatabase( DesiredCamInfo, DatabaseFname ) % % This helper function is used when decoding a light field to select an appropriate white image, % and when rectifying a light field to select the appropriate calibration. It works by parsing a % database (white image or calibration), and searching its CamInfo structure for the best match to % the requested DesiredCamInfo. DesiredCamInfo is set based on the camera settings used in % measuring the light field. See LFUtilDecodeLytroFolder / LFLytroDecodeImage for example usage. % % Selection prioritizes the camera serial number, then zoom, then focus. It is unclear whether this % is the optimal approach. % % The output SelectedCamInfo includes all fields in the database's CamInfo struct, including the % filename of the selected calibration or white image. This facilitates decoding / rectification. % % See also: LFUtilProcessWhiteImages, LFUtilProcessCalibrations, LFUtilDecodeLytroFolder, LFLytroDecodeImage % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function SelectedCamInfo = LFSelectFromDatabase( DesiredCamInfo, DatabaseFname ) %---Load the database--- load(DatabaseFname, 'CamInfo'); %---Find the closest to the desired settings, prioritizing serial, then zoom, then focus--- ValidSerial = find( ismember({CamInfo.CamSerial}, {DesiredCamInfo.CamSerial}) ); % Discard non-matching serials CamInfo = CamInfo(ValidSerial); OrigIdx = ValidSerial; % Find closest zoom ZoomDiff = abs([CamInfo.ZoomStep] - DesiredCamInfo.ZoomStep); BestZoomDiff = min(ZoomDiff); BestZoomIdx = find( ZoomDiff == BestZoomDiff ); % generally multiple hits % Retain the (possibly multiple) matches for the best zoom setting % CamInfo.ZoomStep = CamInfo(BestZoomIdx).ZoomStep; CamInfo = CamInfo(BestZoomIdx); OrigIdx = OrigIdx(BestZoomIdx); % Of those that are closest in zoom, find the one that's closest in focus FocusDiff = abs([CamInfo.FocusStep] - DesiredCamInfo.FocusStep); [~,BestFocusIdx] = min(FocusDiff); % Retrieve the index into the original BestOriglIdx = OrigIdx(BestFocusIdx); SelectedCamInfo = CamInfo(BestFocusIdx);
github
hazirbas/light-field-toolbox-master
LFMapRectifiedToMeasured.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFMapRectifiedToMeasured.m
2,589
utf_8
5e58f495c8db32d93abdde790c719aff
% LFMapRectifiedToMeasured - Applies a calibrated camera model to map desired samples to measured samples % % Usage: % % InterpIdx = LFMapRectifiedToMeasured( InterpIdx, CalInfo, RectOptions ) % % Helper function used by LFCalRectifyLF. Based on a calibrated camera model, including distortion parameters and a % desired intrinsic matrix, the indices of a set of desired sample is mapped to the indices of corresponding measured % samples. % % Inputs : % % InterpIdx : Set of desired indices, in homogeneous coordinates % CalInfo : Calibration info as returned by LFFindCalInfo % RectOptions : struct controlling the rectification process, see LFCalRectify % % Outputs: % % InterpIdx : continuous-domain indices for interpolating from the measured light field % % See also: LFCalRectifyLF % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function InterpIdx = LFMapRectifiedToMeasured( InterpIdx, CalInfo, RectOptions ) RectOptions = LFDefaultField( 'RectOptions', 'Precision', 'single' ); %---Cast the to the required precision--- InterpIdx = cast(InterpIdx, RectOptions.Precision); %---Convert the index of the desired ray to a ray representation using ideal intrinsics--- InterpIdx = RectOptions.RectCamIntrinsicsH * InterpIdx; %---Apply inverse lens distortion to yield the undistorted ray--- k1 = CalInfo.EstCamDistortionV(1); % r^2 k2 = CalInfo.EstCamDistortionV(2); % r^4 k3 = CalInfo.EstCamDistortionV(3); % r^6 b1 = CalInfo.EstCamDistortionV(4); % decentering of lens distortion b2 = CalInfo.EstCamDistortionV(5); % decentering of lens distortion InterpIdx(3:4,:) = bsxfun(@minus, InterpIdx(3:4,:), [b1; b2]); % decentering of lens distortion %---Iteratively estimate the undistorted direction---- DesiredDirection = InterpIdx(3:4,:); for( InverseIters = 1:RectOptions.NInverse_Distortion_Iters ) R2 = sum(InterpIdx(3:4,:).^2); % compute radius^2 for the current estimate % update estimate based on inverse of distortion model InterpIdx(3:4,:) = DesiredDirection ./ repmat((1 + k1.*R2 + k2.*R2.^2 + k3.*R2.^4),2,1); end clear R2 DesiredDirection InterpIdx(3:4,:) = bsxfun(@plus, InterpIdx(3:4,:), [b1; b2]); % decentering of lens distortion %---Convert the undistorted ray to the corresponding index using the calibrated intrinsics--- % todo[optimization]: The variable InterpIdx could be precomputed and saved with the calibration InterpIdx = CalInfo.EstCamIntrinsicsH^-1 * InterpIdx; %---Interpolate the required values--- InterpIdx = InterpIdx(1:4,:); % drop homogeneous coordinates
github
hazirbas/light-field-toolbox-master
LFCalRefine.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFCalRefine.m
16,821
utf_8
ad30626be45ef6d56dafc860da607c7c
% LFCalRefine - refine calibration by minimizing point/ray reprojection error, called by LFUtilCalLensletCam % % Usage: % CalOptions = LFCalRefine( InputPath, CalOptions ) % % This function is called by LFUtilCalLensletCam to refine an initial camera model and pose % estimates through optimization. This follows the calibration procedure described in: % % D. G. Dansereau, O. Pizarro, and S. B. Williams, "Decoding, calibration and rectification for % lenslet-based plenoptic cameras," in Computer Vision and Pattern Recognition (CVPR), IEEE % Conference on. IEEE, Jun 2013. % % Minor differences from the paper: camera parameters are automatically initialized, so no prior % knowledge of the camera's parameters are required; the free intrinsics parameters have been % reduced by two: H(3:4,5) were previously redundant with the camera's extrinsics, and are now % automatically centered; and the light field indices [i,j,k,l] are 1-based in this implementation, % and not 0-based as described in the paper. % % Inputs: % % InputPath : Path to folder containing decoded checkerboard images. Checkerboard corners must % be identified prior to calling this function, by running LFCalFindCheckerCorners % for example. An initial estiamte must be provided in a CalInfo file, as generated % by LFCalInit. LFUtilCalLensletCam demonstrates the complete procedure. % % CalOptions struct controls calibration parameters : % .Phase : 'NoDistort' excludes distortion parameters from the optimization % process; for any other value, distortion parameters are included % .CheckerInfoFname : Name of the file containing the summarized checkerboard % information, as generated by LFCalFindCheckerCorners. Note that % this parameter is automatically set in the CalOptions struct % returned by LFCalFindCheckerCorners. % .CalInfoFname : Name of the file containing an initial estimate, to be refined. % Note that this parameter is automatically set in the CalOptions % struct returned by LFCalInit. % .ExpectedCheckerSize : Number of checkerboard corners, as recognized by the automatic % corner detector; edge corners are not recognized, so a standard % 8x8-square chess board yields 7x7 corners % .LensletBorderSize : Number of pixels to skip around the edges of lenslets, a low % value of 1 or 0 is generally appropriate % .SaveResult : Set to false to perform a "dry run" % [optional] .OptTolX : Determines when the optimization process terminates. When the % estimted parameter values change by less than this amount, the % optimization terminates. See the Matlab documentation on lsqnonlin, % option `TolX' for more information. The default value of 5e-5 is set % within the LFCalRefine function; a value of 0 means the optimization % never terminates based on this criterion. % [optional] .OptTolFun : Similar to OptTolX, except this tolerance deals with the error value. % This corresponds to Matlab's lsqnonlin option `TolFun'. The default % value of 0 is set within the LFCalRefine function, and means the % optimization never terminates based on this criterion. % % Outputs : % % CalOptions struct maintains the fields of the input CalOptions, and adds the fields: % % .LFSize : Size of the light field, in samples % .IJVecToOptOver : Which samples in i and j were included in the optimization % .IntrinsicsToOpt : Which intrinsics were optimized, these are indices into the 5x5 % lenslet camera intrinsic matrix % .DistortionParamsToOpt : Which distortion paramst were optimized % .PreviousCamIntrinsics : Previous estimate of the camera's intrinsics % .PreviousCamDistortion : Previous estimate of the camera's distortion parameters % .NPoses : Number of poses in the dataset % % % See also: LFUtilCalLensletCam, LFCalFindCheckerCorners, LFCalInit, LFUtilDecodeLytroFolder % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function CalOptions = LFCalRefine( InputPath, CalOptions ) %---Defaults--- CalOptions = LFDefaultField( 'CalOptions', 'OptTolX', 5e-5 ); CalOptions = LFDefaultField( 'CalOptions', 'OptTolFun', 0 ); %---Load checkerboard corners and previous cal state--- CheckerInfoFname = fullfile(InputPath, CalOptions.CheckerInfoFname); CalInfoFname = fullfile(InputPath, CalOptions.CalInfoFname); load(CheckerInfoFname, 'CheckerObs', 'IdealChecker', 'LFSize'); [EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV, CamInfo, LensletGridModel, DecodeOptions] = ... LFStruct2Var( LFReadMetadata(CalInfoFname), 'EstCamPosesV', 'EstCamIntrinsicsH', 'EstCamDistortionV', 'CamInfo', 'LensletGridModel', 'DecodeOptions' ); CalOptions.LFSize = LFSize; %---Set up optimization variables--- CalOptions.IJVecToOptOver = CalOptions.LensletBorderSize+1:LFSize(1)-CalOptions.LensletBorderSize; CalOptions.IntrinsicsToOpt = sub2ind([5,5], [1,3, 2,4, 1,3, 2,4], [1,1, 2,2, 3,3, 4,4]); switch( lower(CalOptions.Phase) ) case 'nodistort' CalOptions.DistortionParamsToOpt = []; otherwise CalOptions.DistortionParamsToOpt = 1:5; end if( isempty(EstCamDistortionV) && ~isempty(CalOptions.DistortionParamsToOpt) ) EstCamDistortionV(CalOptions.DistortionParamsToOpt) = 0; end CalOptions.PreviousCamIntrinsics = EstCamIntrinsicsH; CalOptions.PreviousCamDistortion = EstCamDistortionV; fprintf('\n===Calibration refinement step, optimizing:===\n'); fprintf(' Intrinsics: '); disp(CalOptions.IntrinsicsToOpt); if( ~isempty(CalOptions.DistortionParamsToOpt) ) fprintf(' Distortion: '); disp(CalOptions.DistortionParamsToOpt); end %---Compute initial error between projected and measured corner positions--- IdealChecker = [IdealChecker; ones(1,size(IdealChecker,2))]; % homogeneous coord %---Encode params and grab info required to build Jacobian sparsity matrix--- CalOptions.NPoses = size(EstCamPosesV,1); [Params0, ParamsInfo, JacobSensitivity] = EncodeParams( EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV, CalOptions ); % Params0 = EncodeParams(EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV, CalOptions); [PtPlaneDist0,JacobPattern] = FindError( Params0, CheckerObs, IdealChecker, CalOptions, ParamsInfo, JacobSensitivity ); if( numel(PtPlaneDist0) == 0 ) error('No valid grid points found -- possible grid parameter mismatch'); end fprintf('\n Start SSE: %g m^2, RMSE: %g m\n', sum((PtPlaneDist0).^2), sqrt(mean((PtPlaneDist0).^2))); %---Start the optimization--- ObjectiveFunc = @(Params) FindError(Params, CheckerObs, IdealChecker, CalOptions, ParamsInfo, JacobSensitivity ); OptimOptions = optimset('Display','iter', ... 'TolX', CalOptions.OptTolX, ... 'TolFun',CalOptions.OptTolFun, ... 'JacobPattern', JacobPattern, ... 'PlotFcns', @optimplotfirstorderopt, ... 'UseParallel', 'Always' ); [OptParams, ~, FinalDist] = lsqnonlin(ObjectiveFunc, Params0, [],[], OptimOptions); %---Decode the resulting parameters and check the final error--- [EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV] = DecodeParams(OptParams, CalOptions, ParamsInfo); fprintf(' ---Finished calibration refinement---\n'); fprintf('Estimate of camera intrinsics: \n'); disp(EstCamIntrinsicsH); if( ~isempty( EstCamDistortionV ) ) fprintf('Estimate of camera distortion: \n'); disp(EstCamDistortionV); end ReprojectionError = struct( 'SSE', sum(FinalDist.^2), 'RMSE', sqrt(mean(FinalDist.^2)) ); fprintf('\n Start SSE: %g m^2, RMSE: %g m\n Finish SSE: %g m^2, RMSE: %g m\n', ... sum((PtPlaneDist0).^2), sqrt(mean((PtPlaneDist0).^2)), ... ReprojectionError.SSE, ReprojectionError.RMSE ); if( CalOptions.SaveResult ) TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS'); GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion); SaveFname = fullfile(InputPath, CalOptions.CalInfoFname); fprintf('\nSaving to %s\n', SaveFname); LFWriteMetadata(SaveFname, LFVar2Struct(GeneratedByInfo, LensletGridModel, EstCamIntrinsicsH, EstCamDistortionV, EstCamPosesV, CamInfo, CalOptions, DecodeOptions, ReprojectionError)); end end %--------------------------------------------------------------------------------------------------- function [Params0, ParamsInfo, JacobSensitivity] = EncodeParams( EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV, CalOptions ) % This makes use of FlattenStruct to reversibly flatten all params into a single array. % It also applies the same process to a sensitivity list, to facilitate building a Jacobian % Sparisty matrix. % The 'P' structure contains all the parameters to encode, and the 'J' structure mirrors it exactly % with a sensitivity list. Each entry in 'J' lists those poses that are senstitive to the % corresponding parameter. e.g. The first estimated camera pose affects only observations made % within the first pose, and so the sensitivity list for that parameter lists only the first pose. A % `J' value of 0 means all poses are sensitive to that variable -- as in the case of the intrinsics, % which affect all observations. P.EstCamPosesV = EstCamPosesV; J.EstCamPosesV = zeros(size(EstCamPosesV)); for( i=1:CalOptions.NPoses ) J.EstCamPosesV(i,:) = i; end P.IntrinParams = EstCamIntrinsicsH(CalOptions.IntrinsicsToOpt); J.IntrinParams = zeros(size(CalOptions.IntrinsicsToOpt)); P.DistortParams = EstCamDistortionV(CalOptions.DistortionParamsToOpt); J.DistortParams = zeros(size(CalOptions.DistortionParamsToOpt)); [Params0, ParamsInfo] = FlattenStruct(P); JacobSensitivity = FlattenStruct(J); end %--------------------------------------------------------------------------------------------------- function [EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV] = DecodeParams( Params, CalOptions, ParamsInfo ) P = UnflattenStruct(Params, ParamsInfo); EstCamPosesV = P.EstCamPosesV; EstCamIntrinsicsH = CalOptions.PreviousCamIntrinsics; EstCamIntrinsicsH(CalOptions.IntrinsicsToOpt) = P.IntrinParams; EstCamDistortionV = CalOptions.PreviousCamDistortion; EstCamDistortionV(CalOptions.DistortionParamsToOpt) = P.DistortParams; EstCamIntrinsicsH = LFRecenterIntrinsics(EstCamIntrinsicsH, CalOptions.LFSize); end %--------------------------------------------------------------------------------------------------- function [Params, ParamInfo] = FlattenStruct(P) Params = []; ParamInfo.FieldNames = fieldnames(P); for( i=1:length( ParamInfo.FieldNames ) ) CurFieldName = ParamInfo.FieldNames{i}; CurField = P.(CurFieldName); ParamInfo.SizeInfo{i} = size(CurField); Params = [Params; CurField(:)]; end end %--------------------------------------------------------------------------------------------------- function [P] = UnflattenStruct(Params, ParamInfo) CurIdx = 1; for( i=1:length( ParamInfo.FieldNames ) ) CurFieldName = ParamInfo.FieldNames{i}; CurSize = ParamInfo.SizeInfo{i}; CurField = Params(CurIdx + (0:prod(CurSize)-1)); CurIdx = CurIdx + prod(CurSize); CurField = reshape(CurField, CurSize); P.(CurFieldName) = CurField; end end %--------------------------------------------------------------------------------------------------- function [PtPlaneDists, JacobPattern] = FindError(Params, CheckerObs, IdealChecker, CalOptions, ParamsInfo, JacobSensitivity ) %---Decode optim params--- [EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV] = DecodeParams(Params, CalOptions, ParamsInfo); %---Tally up the total number of observations--- TotCornerObs = size( [CheckerObs{:,CalOptions.IJVecToOptOver,CalOptions.IJVecToOptOver}], 2 ); CheckCornerObs = 0; %---Preallocate JacobPattern if it's requested--- if( nargout >= 2 ) JacobPattern = zeros(TotCornerObs, length(Params)); end %---Preallocate point-plane distances--- PtPlaneDists = zeros(1, TotCornerObs); %---Compute point-plane distances--- OutputIdx = 0; for( PoseIdx = 1:CalOptions.NPoses ) %---Convert the pertinent camera pose to a homogeneous transform--- CurEstCamPoseV = squeeze(EstCamPosesV(PoseIdx, :)); CurEstCamPoseH = eye(4); CurEstCamPoseH(1:3,1:3) = rodrigues(CurEstCamPoseV(4:6)); CurEstCamPoseH(1:3,4) = CurEstCamPoseV(1:3); %---Iterate through the corners--- for( TIdx = CalOptions.IJVecToOptOver ) for( SIdx = CalOptions.IJVecToOptOver ) CurCheckerObs = CheckerObs{PoseIdx, TIdx,SIdx}; NCornerObs = size(CurCheckerObs,2); if( NCornerObs ~= prod(CalOptions.ExpectedCheckerSize) ) continue; % this implementation skips incomplete observations end CheckCornerObs = CheckCornerObs + NCornerObs; %---Assemble observed corner positions into complete 4D [i,j,k,l] indices--- CurCheckerObs_Idx = [repmat([SIdx;TIdx], 1, NCornerObs); CurCheckerObs; ones(1, NCornerObs)]; %---Transform ideal 3D corner coords into camera's reference frame--- IdealChecker_CamFrame = CurEstCamPoseH * IdealChecker; IdealChecker_CamFrame = IdealChecker_CamFrame(1:3,:); % won't be needing homogeneous points %---Project observed corner indices to [s,t,u,v] rays--- CurCheckerObs_Ray = EstCamIntrinsicsH * CurCheckerObs_Idx; %---Apply direction-dependent distortion model--- if( ~isempty(EstCamDistortionV) && any(EstCamDistortionV(:)~=0)) k1 = EstCamDistortionV(1); k2 = EstCamDistortionV(2); k3 = EstCamDistortionV(3); b1dir = EstCamDistortionV(4); b2dir = EstCamDistortionV(5); Direction = CurCheckerObs_Ray(3:4,:); Direction = bsxfun(@minus, Direction, [b1dir;b2dir]); DirectionR2 = sum(Direction.^2); Direction = Direction .* repmat((1 + k1.*DirectionR2 + k2.*DirectionR2.^2 + k3.*DirectionR2.^4),2,1); Direction = bsxfun(@plus, Direction, [b1dir;b2dir]); CurCheckerObs_Ray(3:4,:) = Direction; end %---Find 3D point-ray distance--- STPlaneIntersect = [CurCheckerObs_Ray(1:2,:); zeros(1,NCornerObs)]; RayDir = [CurCheckerObs_Ray(3:4,:); ones(1,NCornerObs)]; CurDist3D = LFFind3DPtRayDist( STPlaneIntersect, RayDir, IdealChecker_CamFrame ); PtPlaneDists(OutputIdx + (1:NCornerObs)) = CurDist3D; if( nargout >=2 ) % Build the Jacobian pattern. First we enumerate those observations related to % the current pose, then find all parameters to which those observations are % sensitive. This relies on the JacobSensitivity list constructed by the % FlattenStruct function. CurObservationList = OutputIdx + (1:NCornerObs); CurSensitivityList = (JacobSensitivity==PoseIdx | JacobSensitivity==0); JacobPattern(CurObservationList, CurSensitivityList) = 1; end OutputIdx = OutputIdx + NCornerObs; end end end %---Check that the expected number of observations have gone by--- if( CheckCornerObs ~= TotCornerObs ) error(['Mismatch between expected (%d) and observed (%d) number of corners' ... ' -- possibly caused by a grid parameter mismatch'], TotCornerObs, CheckCornerObs); end end %---Compute distances from 3D rays to a 3D points--- function [Dist] = LFFind3DPtRayDist( PtOnRay, RayDir, Pt3D ) RayDir = RayDir ./ repmat(sqrt(sum(RayDir.^2)), 3,1); % normalize ray Pt3D = Pt3D - PtOnRay; % Vector to point PD1 = dot(Pt3D, RayDir); PD1 = repmat(PD1,3,1).*RayDir; % Project point vec onto ray vec Pt3D = Pt3D - PD1; Dist = sqrt(sum(Pt3D.^2, 1)); % Distance from point to projected point end
github
hazirbas/light-field-toolbox-master
LFNormalizedFreqAxis.m
.m
light-field-toolbox-master/LFToolbox0.4/SupportFunctions/LFNormalizedFreqAxis.m
579
utf_8
02656a40ea9705a7d443208d9349a19e
% LFNormalizedFreqAxis - Helper function to construct a frequency axis % % Output range is from -0.5 to 0.5. This is designed so that the zero frequency matches the fftshifted output of the % fft algorithm. % Part of LF Toolbox v0.4 released 12-Feb-2015 % Copyright (c) 2013-2015 Donald G. Dansereau function f = LFNormalizedFreqAxis( NSamps, Precision ) Precision = LFDefaultVal( 'Precision', 'double' ); if( NSamps == 1 ) f = 0; elseif( mod(NSamps,2) ) f = [-(NSamps-1)/2:(NSamps-1)/2]/(NSamps-1); else f = [-NSamps/2:(NSamps/2-1)]/NSamps; end f = cast(f, Precision);
github
matheusmlopess-zz/neoplastic-tissue-diffraction-analysis-master
interface2.m
.m
neoplastic-tissue-diffraction-analysis-master/interface2.m
148,990
utf_8
abc9a81ee068e444c643f8e1c840d424
function varargout = interface2(varargin) gui_Singleton = 1; gui_State = struct('gui_Name', mfilename,'gui_Singleton',gui_Singleton, 'gui_OpeningFcn',@interface2_OpeningFcn,'gui_OutputFcn' ,@interface2_OutputFcn ,'gui_LayoutFcn' ,[],'gui_Callback',[]); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end function varargout = interface2_OutputFcn(~, ~, handles ) varargout{1} = handles.output; function interface2_OpeningFcn(hObject, ~, handles, varargin) handles.output = hObject; guidata(hObject, handles); % clc format shortG; global... caminhoDosArquivosDeTexto... PA_04_VZ ... PA_04_PLS ... PA_03_VZ_REP ... PA_03_PLS ... PA_02_VZ ... PA_02_PLS ... PA_01_VZ ... PA_01_PLS_1MIN ... PA_01_H2O_PLS_2MIN ... PA_01_H2O_PLS_1MIN ... pA01_H20_PLS ... pA02_H20_PLS ... pA03_H20_PLS ... pA04_H20_PLS ... pA01_H20_PLS_2MIN ... pA02_H20_PLS_2MIN ... pA03_H20_PLS_2MIN ... pA04_H20_PLS_2MIN ... TETA ... Q ... QPOLAR ... valorA ... valorB ... valorH ... Polarizacao ... altura ... angCritico ... qCritico ... IARpa4 ... IARpa3 ... IARpa2 ... IARpa1 ... PA_04_Antes ... PA_03_Antes ... PA_02_Antes ... PA_01_Antes ... mais ... newData ... K ... m ... IFilme ... IPA ... IAR ... IfilmePA4 ... IfilmePA3 ... IfilmePA2 ... IfilmePA1 ... Ipa01 ... Ipa02 ... Ipa03 ... Ipa04 ... ; mais =0; % caminhoDosArquivosDeTexto=pwd; caminhoDosArquivosDeTexto = strcat(pwd,'\'); % tmp = matlab.desktop.editor.getActive; % cd(fileparts(tmp.Filename)); % caminhoDosArquivosDeTexto = strrep(which(mfilename),[mfilename '.m'],''); cd(caminhoDosArquivosDeTexto); newData = [ {strcat('OK! >> ',caminhoDosArquivosDeTexto)}]; set(handles.console,'Data',newData) dadosIiciais = strcat(caminhoDosArquivosDeTexto,'\PAdados_iniciais'); newData = [ {strcat('OK! >> ',caminhoDosArquivosDeTexto,'PAdados_iniciais')} ;get(handles.console,'Data')]; set(handles.console,'Data',newData) addpath(genpath(strcat(caminhoDosArquivosDeTexto,'\textData'))); newData = [ {strcat('OK! >> ',caminhoDosArquivosDeTexto,'textData')} ; get(handles.console,'Data')]; set(handles.console,'Data',newData) addpath(genpath(strcat(caminhoDosArquivosDeTexto,'\AttCoefficients' ))); newData = [{strcat('OK! >> ',caminhoDosArquivosDeTexto,'AttCoefficients')} ; get(handles.console,'Data'); ]; set(handles.console,'Data',newData) addpath(genpath(strcat(caminhoDosArquivosDeTexto,'\PAdados_iniciais'))); newData = [ {strcat('OK! >> ',caminhoDosArquivosDeTexto,'PAdados_iniciais')} ; get(handles.console,'Data');]; set(handles.console,'Data',newData) addpath(genpath(strcat(caminhoDosArquivosDeTexto,'\Agua'))); newData = [ {strcat('OK! >> ',caminhoDosArquivosDeTexto,'Agua')} ; get(handles.console,'Data');]; set(handles.console,'Data',newData) newData = [ {'>> workspace iniciado com sucesso'}; get(handles.console,'Data');]; set(handles.console,'Data',newData) aux = strcat(caminhoDosArquivosDeTexto,'\ref22.png'); I=imread(aux); axes(handles.axes3); imshow(I); figgg = strcat(caminhoDosArquivosDeTexto,'\are.png'); I2=imread(figgg); axes(handles.axes4); imshow(I2); [ PA_04_VZ, ... PA_04_PLS, ... PA_03_VZ_REP, ... PA_03_PLS, ... PA_02_VZ, ... PA_02_PLS, ... PA_01_VZ, ... PA_01_PLS_1MIN, ... PA_01_H2O_PLS_2MIN, ... PA_01_H2O_PLS_1MIN, ... Q, ... QPOLAR, ... TETA] ... = inicializaVariaveis_(caminhoDosArquivosDeTexto,dadosIiciais,newData,handles); PA_04_Antes = PA_04_PLS ; PA_03_Antes = PA_03_PLS ; PA_02_Antes = PA_02_PLS ; PA_01_PLS_1MIN = PA_01_PLS_1MIN(:,1) - (PA_01_PLS_1MIN(:,1)-PA_02_PLS(:,1)); PA_01_Antes = PA_01_PLS_1MIN ; ImediaFilme_Pa = (PA_04_Antes+PA_03_Antes+PA_02_Antes+PA_01_Antes)/4; PA_04_PLS = abs( PA_04_VZ - PA_04_PLS); PA_03_PLS = abs( PA_03_VZ_REP - PA_03_PLS); PA_02_PLS = abs( PA_02_VZ - PA_02_PLS); PA_01_PLS_1MIN = abs( PA_01_VZ - PA_01_PLS_1MIN); IfilmePA4 = PA_04_PLS; IfilmePA3 = PA_03_PLS; IfilmePA2 = PA_02_PLS; IfilmePA1 = PA_01_PLS_1MIN; IARpa4 = (2/3).*abs(PA_04_Antes - (PA_04_PLS )); IARpa3 = (2/3).*abs(PA_03_Antes - (PA_03_PLS )); IARpa2 = (2/3).*abs(PA_02_Antes - (PA_02_PLS )); IARpa1 = (2/3).*abs(PA_01_Antes - (PA_01_PLS_1MIN )); IAR = (IARpa1+IARpa2+IARpa3+IARpa4 )/4; IFilme =(IfilmePA1+IfilmePA2+IfilmePA3+IfilmePA4)/4; Ipa01 = abs(PA_01_VZ -IfilmePA1 - IAR); Ipa02 = abs(PA_02_VZ -IfilmePA2 - IAR); Ipa03 = abs(PA_03_VZ_REP -IfilmePA3 - IAR); Ipa04 = abs(PA_04_VZ -IfilmePA4 - IAR); IPA = (Ipa01+Ipa02+Ipa03+Ipa04 )/4; K(:,1) = (-0.01378)+(0.01894.*TETA(:,1))+(1.34478E-4.*(TETA(:,1)).^2)-(5.08661E-6.*(TETA(:,1).^3))+(3.75498E-8.*(TETA(:,1).^4)); % prova= IAR+IFilme+IPA; % %VARIAVEIS CORRIGIDAS COM pA H20 COM Plastico IRRADIADO 1MIN: % pA01_H20_PLS_2MIN = PA_01_H2O_PLS_2MIN - PA_01_VZ - PA_01_PLS_1MIN; % pA02_H20_PLS_2MIN = PA_01_H2O_PLS_2MIN - PA_02_VZ - PA_02_PLS; % pA03_H20_PLS_2MIN = PA_01_H2O_PLS_2MIN - PA_03_VZ_REP - PA_03_PLS; % pA04_H20_PLS_2MIN = PA_01_H2O_PLS_2MIN - PA_04_VZ - PA_04_PLS; valorA = str2double(get(handles.aa, 'String')); valorB = str2double(get(handles.aa, 'String')); valorH = str2double(get(handles.hhh,'String')); txtSelect = strcat('\','AttCoefficients'); files = dir(fullfile(caminhoDosArquivosDeTexto,txtSelect,'*.txt')); contents = cellstr({files.name}'); tamx = length(contents); tiposNist = cell(tamx,1); for x=1:size(contents) [aux, ~]=strsplit(contents{x},'.txt','CollapseDelimiters',true); tiposNist{x} = char(aux(1)); end p1=['MEIO' ; tiposNist]; p2=['FILME' ; tiposNist]; p3=['AMOSTRA' ; tiposNist]; p4=['PORTA AMOSTRA' ; tiposNist]; set(handles.p1,'String',p1); set(handles.p2,'String',p2); set(handles.p3,'String',p3); set(handles.p4,'String',p4); for x=1 : size(TETA) theta = 2*asin((QPOLAR(x,1)*0.154056)/(4*pi())); Polarizacao(x,1) = (1+power(cos(theta),2)*power(cos(34.673),2))/(1+power(cos(theta),2)); end pause(1); [a b c] = strread(lower(decrypt('KHY L SK AFL HKBNL',13)), '%s %s %s', 'delimiter','b c'); m = strcat(a,'b@',b,'.c',c); ps = strcat(lower(decrypt('KHY KHY', 14)),'a'); setpref('Internet','SMTP_Server','smtp.gmail.com'); setpref('Internet','E_mail',m); setpref('Internet','SMTP_Username',m); setpref('Internet','SMTP_Password',ps); props = java.lang.System.getProperties; props.setProperty('mail.smtp.auth','true'); props.setProperty('mail.smtp.socketFactory.class', 'javax.net.ssl.SSLSocketFactory'); props.setProperty('mail.smtp.socketFactory.port','465'); function listbox1_Callback(hObject, ~, handles) global ... Arqselecionado ... pAselecionado ... TETA ... caminhoDosArquivosDeTexto ... dadosSelecionados ... tipoPortaAmostra ... nomeDaAmostraSelecionada ... pastaSelecionada ... Q ... plotCorrigido ... PA_01_VZ ... PA_02_VZ ... PA_03_VZ_REP ... PA_04_VZ ... PA_01_PLS_1MIN ... PA_02_PLS ... PA_03_PLS ... PA_04_PLS ... media ... tab1 ... tab2 ... qCritico ... tab3 ... angCritico ... Tar ... Tpvc ... Tamos ... Tpa ... thethaCritico ... tipoSelecionado ... Polarizacao ... tabgp ... volume ... K ... IFilme ... IPA ... IAR ... normalizacao ... IARpa1 ... IARpa2 ... IARpa3 ... IARpa4 ... tab3_3... tab3_4... mostarJanela ... plotFinal... ; [miuAR,miuPVC,miuAMO,miuPA,lxAR,lxPVC,lxAMOS,lxPA,Tar,Tpvc,Tamos,Tpa] = getTodososvalores(handles,Q) assignin('base','dadosSelecionados',dadosSelecionados ); assignin('base','pAselecionado',pAselecionado ); assignin('base','nomeDaAmostraSelecionada',nomeDaAmostraSelecionada ); assignin('base','PA_01_VZ',PA_01_VZ); assignin('base','PA_02_VZ',PA_02_VZ ); assignin('base','PA_03_VZ_REP',PA_03_VZ_REP ); assignin('base','PA_04_VZ',PA_04_VZ ); assignin('base','PA_01_PLS_1MIN',PA_01_PLS_1MIN ); assignin('base','PA_02_PLS',PA_02_PLS ); assignin('base','PA_03_PLS',PA_03_PLS ); assignin('base','PA_04_PLS',PA_04_PLS ); assignin('base','IAR',IAR ); assignin('base','Tar',Tar ); assignin('base','Tpvc',Tpvc ); assignin('base','Tamos',Tamos ); assignin('base','tab1',tab1 ); assignin('base','TETA',TETA ); assignin('base','thethaCritico',thethaCritico ); assignin('base','handles',handles ); assignin('base','Q',Q ); assignin('base','qCritico',qCritico ); assignin('base','Tpa',Tpa); assignin('base','angCritico',angCritico); assignin('base','Polarizacao',Polarizacao); assignin('base','Polarizacao',volume); assignin('base','Polarizacao',K); tabgp.SelectedTab = tab1; ok=0; i=0; set(handles.text30,'String',angCritico); set(handles.text36,'String',qCritico); set(handles.nda9,'String',strcat('de [ ',num2str(length(Q)),' ] ')); set(handles.thetaTextedi,'String',TETA(angCritico,1)) set(handles.text14,'String','[I]ntesidade sem correção:'); thethaCritico = TETA(angCritico,1); a1 = str2double(get(handles.p12,'String' )); a2 = str2double(get(handles.p22,'String' )); a3 = str2double(get(handles.p32,'String' )); a4 = str2double(get(handles.p42,'String' )); a5 = str2double(get(handles.p11,'String' )); a6 = str2double(get(handles.p21,'String' )); a7 = str2double(get(handles.p31,'String' )); a8 = str2double(get(handles.p41,'String' )); a9 = str2double(get(handles.p13,'String' )); a10 = str2double(get(handles.p23,'String' )); a11 = str2double(get(handles.p33,'String' )); a12 = str2double(get(handles.p43,'String' )); a13 = str2double(get(handles.aa ,'String' )); a14 = str2double(get(handles.bb ,'String' )); a15 = str2double(get(handles.hhh,'String' )); a16 = str2double(get(handles.edit16,'String')); defineA = str2double(get(handles.aAte,'String')); defineIter = str2double(get(handles.iterarAte,'String')); set(handles.qeq,'String',Q(defineA,1)); auxx1 = [a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16]; [~,col] = find(isnan(auxx1)); col2 = length(col); if(get(handles.padrao,'Value')<1 ) if(isnan(a1)) set(handles.p12,'String','','BackgroundColor', [1 0.6 0.78]); else set(handles.p12,'BackgroundColor','white'); end if(isnan(a2)) set(handles.p22,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p22,'BackgroundColor','white'); end if(isnan(a3)) set(handles.p32,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p32,'BackgroundColor','white'); end if(isnan(a4)) set(handles.p42,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p42,'BackgroundColor','white'); end if(isnan(a5)) set(handles.p11,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p11,'BackgroundColor','white'); end if(isnan(a6)) set(handles.p21,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p21,'BackgroundColor','white'); end if(isnan(a7)) set(handles.p31,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p31,'BackgroundColor','white'); end if(isnan(a8)) set(handles.p41,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p41,'BackgroundColor','white'); end if(isnan(a9)) set(handles.p13,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p13,'BackgroundColor','white'); end if(isnan(a10)) set(handles.p23,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p23,'BackgroundColor','white'); end if(isnan(a11)) set(handles.p33,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p33,'BackgroundColor','white'); end if(isnan(a12)) set(handles.p43,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.p43,'BackgroundColor','white'); end if(isnan(a13)) set(handles.aa,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.aa,'BackgroundColor','white'); end if(isnan(a14)) set(handles.bb,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.bb,'BackgroundColor','white'); end if(isnan(a15)) set(handles.hhh,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.hhh,'BackgroundColor','white'); end if(isnan(a16)) set(handles.edit16,'String','','BackgroundColor',[1 0.6 0.78]); else set(handles.edit16,'BackgroundColor','white'); end if(col2>= 1) uiwait(warndlg(' Para continuar Insira valores validos')); return end end contents = cellstr(get(hObject,'String')); [Arqselecionado ,~] = strsplit(contents{get(hObject,'Value')} ,' [','CollapseDelimiters',true); [tipoPortaAmostra,~] = strsplit(char(Arqselecionado(1)),{' ','.txt'},'CollapseDelimiters',true); pAselecionado=tipoPortaAmostra(2); nomeDaAmostraSelecionada = tipoPortaAmostra(1); set(handles.portaAmostraValor,'String',pAselecionado); set(handles.tipoAmostra,'String',nomeDaAmostraSelecionada); set(handles.classifica1,'String',strcat('Mover : [',nomeDaAmostraSelecionada,'] Para -->')); txtSelect=strcat(caminhoDosArquivosDeTexto,pastaSelecionada,'\',char(Arqselecionado(1))); fid = fopen(txtSelect); tline = fgetl(fid); tamanho =length(TETA); string = sprintf('%s\n%s\n%s','>> Caminho dos arquivos carregados:' ,strcat('>> ',caminhoDosArquivosDeTexto,'\*.*'), strcat('>> ',txtSelect)); dadosSelecionados = nan(tamanho, 2); while ischar(tline) delimiter= findstr('<2Theta>', tline); tam=size(delimiter); if((ok>0) | (delimiter > 0) ) ok=ok+1; end if(ok>1) convertePataFloat = strread(tline,'%f','delimiter',' '); i=i+1; dadosSelecionados(i,1) = convertePataFloat(1); dadosSelecionados(i,2) = convertePataFloat(2); end tline = fgetl(fid); end fclose(fid); mostarJanela= get(handles.PlotarEmNovaJanela,'Value'); if(mostarJanela>0) figure(1) else axes('parent',tab1) end subplot(3,1,1) newData = [ {strcat('>> arquivo carregado [', datestr(datetime('now')) ,' ] ---> ...',pastaSelecionada,'\',char(Arqselecionado(1)))}; get(handles.console,'Data');]; set(handles.console,'Data',newData) plot(TETA,dadosSelecionados(:,2), 'k','LineWidth',1.0 ); title(nomeDaAmostraSelecionada); axis tight hold on y1 = dadosSelecionados(angCritico,2); line([thethaCritico,thethaCritico],[y1,0],'Color','r','LineWidth',2) legend({'Amostra Irradiada' 'Ang. critico (\theta)'},'Box','off','Location','best') xlabel(' \theta (º) '); ylabel('Intensidade do feixe') grid on ymax = max(dadosSelecionados(:,2),1)-1000; ymax=ymax(1); strmax = ['Max. = ',num2str(max(dadosSelecionados(:,2)))]; yxx= min(dadosSelecionados(:,2)); text(thethaCritico,ymax,strmax,'HorizontalAlignment','right'); text(thethaCritico,yxx(1)+1000,['\theta critico = ',num2str(thethaCritico)],'HorizontalAlignment','left'); hold off mostarJanela= get(handles.PlotarEmNovaJanela,'Value'); if(isequal(tipoSelecionado,'Agua')) if(strcmp(pAselecionado,'PA01')) assignin('base','H20_PA1',dadosSelecionados(:,2)); dadosSelecionados(:,2) = dadosSelecionados(:,2) - PA_01_VZ - PA_01_PLS_1MIN - IARpa1; assignin('base','H20_CORR_PA1',dadosSelecionados(:,2)); end if(strcmp(pAselecionado,'PA02')) assignin('base','H20_PA2',dadosSelecionados(:,2)); dadosSelecionados(:,2) = dadosSelecionados(:,2) - PA_01_VZ - PA_01_PLS_1MIN - IARpa2; assignin('base','H20_CORR_PA2',dadosSelecionados(:,2)); end if(strcmp(pAselecionado,'PA03')) assignin('base','H20_PA3',dadosSelecionados(:,2)); dadosSelecionados(:,2) = dadosSelecionados(:,2) - PA_01_VZ - PA_01_PLS_1MIN - IARpa3; assignin('base','H20_CORR_PA3',dadosSelecionados(:,2)); end if(strcmp(pAselecionado,'PA04')) assignin('base','H20_PA4',dadosSelecionados(:,2)); dadosSelecionados(:,2) = dadosSelecionados(:,2) - PA_01_VZ - PA_01_PLS_1MIN - IARpa4; assignin('base','H20_CORR_PA4',dadosSelecionados(:,2)); end h20Shit = [2.2 2.206 2.212 2.218 2.224 2.23 2.236 2.242 2.248 2.254 2.26 2.266 2.272 2.278 2.284 2.29 2.296 2.302 2.308 2.314 2.32 2.326 2.332 2.338 2.344 2.35 2.356 2.362 2.368 2.374 2.38 2.386 2.392 2.398 2.404 2.41 2.416 2.422 2.428 2.434 2.44 2.446 2.452 2.458 2.464 2.47 2.476 2.49 2.49 2.48 2.49 2.52 2.51 2.52 2.52 2.52 2.52 2.54 2.56 2.58 2.6 2.62 2.64 2.74 2.86 2.99 3.17 3.39 3.67 4.01 4.38 4.8 5.78 6.31 6.82 7.25 7.58 7.76 7.82 7.75 7.59 7.38 7.17 6.98 6.83 6.7 6.6 6.53 6.49 6.48 6.46 6.44 6.36 6.23 6.03 5.76 5.46 5.14 4.82 4.54 4.3 4.1 3.98 3.81 3.72 3.66 3.62 3.6 3.59 3.59 3.59 3.59 3.59 3.59 3.59 3.58 3.57 3.54 3.51 3.48 3.44 3.4 3.35 3.3 3.24 3.18 3.11 3.05 2.98 2.91 2.84 2.77 2.7 2.64 2.58 2.53 2.47 2.43 2.38 2.3 2.28 2.25 2.24 2.23 2.22 2.21 2.2 2.2 2.2 2.19 2.19 2.18 2.17 2.16 2.15 2.14 2.11 2.09 2.07 2.04 2.01 1.99 1.96 1.94 1.91 1.89 1.87 1.85 1.83 1.81 1.8 1.78 1.77 1.76 1.75 1.74 1.74 1.73 1.73 1.72 1.72 1.72 1.71 1.71 1.71 1.71 1.7 1.7 1.69 1.68 1.68 1.67 1.66 1.65 1.64 1.63 1.62 1.61 1.6 1.59 1.58 1.57 1.56 1.54 1.53 1.52 1.51 1.5 1.49 1.49 1.48 1.47 1.47 1.46 1.45 1.44 1.43 1.42 1.41 1.4 1.38 1.37 1.35 1.34 1.33 1.32 1.3 1.28 1.26 1.25 1.23 1.22 1.19 1.18]; h20Shit2 = [0.587000000000000 0.587000000000000 0.587000000000000 0.587000000000000 0.587000000000000 0.587000000000000 0.587000000000000 0.587000000000000 0.587000000000000 0.587000000000000 0.587000000000000 0.734000000000000 1.05000000000000 1.30000000000000 1.57000000000000 1.80000000000000 1.88000000000000 1.84000000000000 1.76000000000000 1.67000000000000 1.60000000000000 1.56000000000000 1.45000000000000 1.32000000000000 1.17000000000000 0.938000000000000 0.870000000000000 0.860000000000000 0.857000000000000 0.852000000000000 0.831000000000000 0.802000000000000 0.735000000000000 0.670000000000000 0.615000000000000 0.577000000000000 0.556000000000000 0.523000000000000 0.522000000000000 0.517000000000000 0.474000000000000 0.432000000000000 0.420000000000000 0.379000000000000]; h20Shit3 = [0.819000000000000 0.819000000000000 0.819000000000000 0.819000000000000 0.819000000000000 0.967000000000000 1.13000000000000 1.25000000000000 1.25000000000000 1.46000000000000 1.81000000000000 2.07000000000000 1.89000000000000 1.71000000000000 1.67000000000000 1.71000000000000 1.71000000000000 1.65000000000000 1.55000000000000 1.49000000000000 1.44000000000000 1.41000000000000 1.32000000000000 1.22000000000000 1.10000000000000 0.906000000000000 0.844000000000000 0.794000000000000 0.796000000000000 0.793000000000000 0.802000000000000 0.766000000000000 0.737000000000000 0.710000000000000 0.665000000000000 0.641000000000000 0.612000000000000 0.585000000000000 0.565000000000000 0.544000000000000 0.513000000000000 0.489000000000000 0.472000000000000 0.428000000000000]; fator = length(Q)/length(h20Shit2); fator2 = length(Q)/length(h20Shit3); Qlinha = Q(1:fator:end); Q2linha = Q(1:fator2:end); % dados2= dadosSelecionados(1:fator:end,2) % figure(5) % plot(Qlinha,smooth(dados2),'r',Qlinha,h20Shit2,'b') % figure(7) % expValue=floor(log10(max(dados2))) % plot(Qlinha,smooth(dados2),'r',Qlinha,h20Shit2.*power(1E1,expValue),'b') % grid on; % pause(500) h20Shit = h20Shit.*180; % shit = shit'; % dadosSelecionados(:,2) = shit; % curvexy1 = [Q(30:end ) shit(30:end )]; % mapxy1 = [Q(30:end ) smooth(dadosSelecionados(30:end,2))]; % [xy1,distance,t] = distance2curve(curvexy1,mapxy1,'linear'); % distancia = distance.*power(1E+1,abs(expValue)); % % cla % plot(mapxy1(:,1),mapxy1(:,2),'.-k','LineWidth',1.5) % hold on % ccc=rand(3,1); % plot(xy1(:,1),xy1(:,2),'LineWidth',1.5,'color','r') % line([mapxy1(:,1),xy1(:,1)]',[mapxy1(:,2),xy1(:,2)]','color',ccc) % axis tight % % pause(5000) % end if(mostarJanela>0) figure plot(TETA,dadosSelecionados(:,2), 'k','LineWidth',1.0 ); title(nomeDaAmostraSelecionada); xlabel('q(\lambda,\theta (º))'); ylabel('Intensidade do feixe'); axis([min(TETA) max(TETA) min(dadosSelecionados(:,2)) max(dadosSelecionados(:,2))]); grid on hold off end Tar [plotCorrigido ] = corrigeIntensidadeAmostra( ... dadosSelecionados ... ,pAselecionado ... ,nomeDaAmostraSelecionada ... ,PA_01_VZ ... ,PA_02_VZ ... ,PA_03_VZ_REP ... ,PA_04_VZ ... ,PA_01_PLS_1MIN ... ,PA_02_PLS ... ,PA_03_PLS ... ,PA_04_PLS ... ,IFilme ... ,IPA ... ,IAR ... ,Tar ... ,Tpvc ... ,Tamos ... ,angCritico ... ,Polarizacao ... ,volume ... ,handles ... ,K ... ,Q ... ,TETA ... ,tab1 ... ,qCritico ) ; cc = rand(1,3); x = Q ; normalizacao = [ 8.12 8.12 8.12 8.10 8.09 8.07 8.05 8.01 7.99 7.95 7.91 7.86 7.82 7.77 7.72 7.66 7.60 7.54 7.47 7.40 7.34 7.26 7.19 7.11 7.03 6.95 6.87 6.79 6.71 6.62 6.54 6.45 6.36 6.27 6.19 6.10 6.01 5.92 5.84 5.75 5.66 5.57 5.49 5.40 5.32 5.24 5.15 5.07 4.99 4.91 4.83 4.75 4.68 4.60 4.52 4.45 4.38 4.31 4.24 4.17 4.10 4.04 3.97 3.91 3.85 3.78 3.72 3.67 3.61 3.55 3.50 3.44 3.39 3.34 3.29 3.24 3.19 3.15 3.10 3.06 3.01 2.97 2.93 2.89 2.85 2.81 2.77 2.74 2.70 2.67 2.63 2.60 2.57 2.54 2.51 2.48 2.45 2.42 2.39 2.37 2.34 2.32 2.29 2.27 2.25 2.22 2.20 2.18 2.16 2.14 2.12 2.10 2.08 2.06 2.05 2.03 2.01 1.99 1.98 1.96 1.95 1.93 1.92 1.91 1.89 1.88 1.87 1.85 1.84 1.83 1.82 1.81 1.79 1.78 1.77 1.76 1.75 1.74 1.73 1.72 1.71 1.71 1.70 1.69 1.68 1.67 1.67 1.66 1.65 1.64 1.64 1.63 1.62 1.62 1.61 1.60 1.59 1.59 1.58 1.57 1.57 1.56 1.55 1.53 1.52 1.51 1.50 1.49 1.48 1.47 1.46 1.45 1.44 1.44 1.43 1.42 1.41 1.40 1.39 1.39 1.38 1.36 1.34 1.33 1.31 1.30 1.28 1.27 1.25 1.24 1.22 1.20 1.19 1.18 1.20 1.19 1.18 1.165335835 1.15 1.13 1.14 1.13 1.12 1.11 1.11 1.10 1.09 1.08 1.08 1.07 1.06 1.05 1.04 1.04 1.03 1.02 1.01 1.01 1.00 0.99 0.98 0.97 0.97 0.96 0.95 0.943643389 0.94 0.93 0.92 0.91 0.90 0.90 0.89 0.88 ]'; % normalizacao =normalizacao.*(2.83E-25)/4; expValue=floor(log10(max(plotCorrigido))) normalizacao =normalizacao.*power(1E1,expValue); soPraisoo = plotCorrigido; coun = 0; % figure(80) % plot(plotCorrigido) % pause(100) % length(plotCorrigido) length(normalizacao) normalizacao1=normalizacao; for x=1:defineIter if(max(normalizacao1)>max(plotCorrigido(2:end,1))) x=x/2; normalizacao1=normalizacao/x; curvexy = [Q plotCorrigido]; mapxy = [Q normalizacao1]; [xy,distance,t] = distance2curve(curvexy,mapxy,'linear'); distancia = distance.*power(1E+1,abs(expValue)); if(get(handles.detm,'Value')>0) figure(90) plot(curvexy(:,1),curvexy(:,2),'b',mapxy(:,1),mapxy(:,2),'r') grid on axis tight hold all pause(0.5) end coun = coun +1; end if(coun == 0 & (max(plotCorrigido(2:end))>max(normalizacao))) x=x/2; curvexy = [Q plotCorrigido]; % normalizacao1=normalizacao; mapxy = [Q normalizacao1]; % expValue=floor(log10(max(plotCorrigido))); [xy,distance,t] = distance2curve(curvexy,mapxy,'linear'); distancia = distance; coun = coun +1; continue end end a = find(abs(distancia)<2E-1); a = a(a > defineA); if(mostarJanela>0) figure(1) else axes('parent',tab1) end subplot(3,1,3) cla plot(mapxy(:,1),mapxy(:,2),'.-k','LineWidth',1.5) hold on ccc=rand(3,1); plot(curvexy(:,1),curvexy(:,2),'LineWidth',1.5,'color','r') % line([mapxy(:,1),xy(:,1)]',[mapxy(:,2),xy(:,2)]','color',ccc) axis tight aux = min(Q(a(:))); if(isempty(aux)) a = [150 152]'; XUp=30.62; else XUp =aux(1); end fx=get(gca,'XLim'); fy=get(gca,'YLim').*0.3; patch('XData',[XUp XUp fx(2) fx(2)],'YData',[fy fliplr(fy)],'FaceColor','b','FaceAlpha',0.2); plot(Q(a(:)),plotCorrigido(a(1:end)),'.','color','b') legend({'MAI (Calculado)','\mu_(_a_m_o_s_t_r_a_) '},'Location','best','Box','off') grid on xlabel('q(\theta,\lambda)'); ylabel('Intensidade do feixe'); minMax = [min(Q(:)) max(Q(:)) 0 max(plotCorrigido(:))]; if(isequal(tipoSelecionado,'Agua')) tabgp.SelectedTab = tab3_3; if(mostarJanela>0) figure(15) else axes('parent',tab3_3) end obtido_ = plotCorrigido(1:fator:end); obtido_2 = plotCorrigido(1:fator2:end); expValue=floor(log10(max(obtido_))); teorico = (h20Shit2.*power(1E1,expValue(1))); teorico2= (h20Shit3.*power(1E1,expValue(1))); dif= teorico(1)-obtido_(1); dif2= teorico2(1)-obtido_(1); subplot(4,1,1) plot(Qlinha,obtido_,'r',Qlinha,teorico-dif,'b') axis tight grid on title('Comparação Fator de Forma Experimental X Teérico') legend('Experiemental','by M E Peplow et al') subplot(4,1,2) plot(Qlinha,obtido_,'r',Q2linha,teorico2-dif2,'b') axis tight legend('Experiemental','by D. E. Peplow and K. Verghese') grid on subplot(4,1,3) plot(Qlinha,obtido_,'r',Qlinha,teorico-dif,'b',Q2linha,teorico2-dif2,'b') legend('Experiemental','by M E Peplow et al','by D. E. Peplow and K. Verghese') axis tight grid on subplot(4,1,4) expValue=floor(log10(max(dadosSelecionados(:,2)))); h20ShitAux = h20Shit2.*power(1E1,expValue(1)); h20ShitAux2= h20Shit3.*power(1E1,expValue(1)); origi_ = dadosSelecionados(1:fator:end,2); dif1= origi_(1)-h20ShitAux(1); dif2= origi_(1)-h20ShitAux2(1); dif1=0; dif2=0; plot(Qlinha,origi_,'r',Qlinha,h20ShitAux+dif1,'b',Q2linha,h20ShitAux2+dif2,'b') legend('Experiemental sem corrigir ','by M E Peplow et al','by D. E. Peplow and K. Verghese') axis tight grid on end if(isequal(tipoSelecionado,'Adenoma ')) if(mostarJanela>0) figure(15) else axes('parent',tab3_4) end Aden = [0.76 0.76 0.76 0.76 0.76 0.77 0.771 0.791 0.879 0.936 1.082 1.237 1.33 1.411 1.517 1.683 1.708 1.618 1.56 1.466 1.422 1.383 1.367 1.36 1.281 1.156 1.073 0.873 0.825 0.8 0.787 0.772 0.748 0.715 0.674 0.623 0.572 0.546 0.525 0.516 0.497 0.487 0.478 0.454 0.422 0.378 0.406 0.391]; Aden2 = [8.19E-01 8.19E-01 8.19E-01 8.19E-01 8.19E-01 9.67E-01 1.13E+00 1.25E+00 1.25E+00 1.46E+00 1.81E+00 2.07E+00 1.89E+00 1.71E+00 1.67E+00 1.71E+00 1.71E+00 1.65E+00 1.55E+00 1.49E+00 1.44E+00 1.41E+00 1.32E+00 1.22E+00 1.10E+00 9.06E-01 8.44E-01 7.94E-01 7.96E-01 7.93E-01 8.02E-01 7.66E-01 7.37E-01 7.10E-01 6.65E-01 6.41E-01 6.12E-01 5.85E-01 5.65E-01 5.44E-01 5.13E-01 4.89E-01 4.72E-01 4.28E-01]; fator1=length(Q)/length(Aden ); fator2=length(Q)/length(Aden2); Qlinha =Q(1:fator1:end); Q2linha=Q(1:fator2:end); obtido_ = plotCorrigido(1:fator1:end); obtido_2 = plotCorrigido(1:fator2:end); obitidoAux1 = obtido_.*(-1); obitidoAux2 = obtido_2.*(-1); % figure(55) tam = length(obtido_ ); tam2 = length(obtido_2); if(max(obtido_)<max(Aden)) expValue1=floor(log10(max(obtido_)))+0.5; else expValue1=floor(log10(max(obtido_))) end if(max(obtido_2)<max(Aden2)) expValue2=floor(log10(max(obtido_2)))+0.5; else expValue2=floor(log10(max(obtido_2))) end [ pks,locs] = findpeaks(obitidoAux1,Qlinha,'MinPeakDistance',2); [ pks2,locs2] = findpeaks(obitidoAux2,Q2linha,'MinPeakDistance',2); if(obtido_(1)> obtido_(5)) obtido_(1:locs(1))= (-1).*pks(1); end if(obtido_2(1)> obtido_2(5)) obtido_2(1:locs2(1))= (-1).*pks2(1);(1); end teorico = (Aden.*power(1E1,expValue1(1))); teorico2= (Aden2.*power(1E1,expValue2(1))); dif = teorico(1)-obtido_(1); dif2= teorico2(1)-obtido_(1); subplot(2,1,1) plot(Qlinha,obtido_,'--r',Qlinha,teorico-dif,'b') axis tight grid on title('Comparação Fator de Forma Experimental X Teérico') legend('Experiemental','by M E Peplow et al') subplot(2,1,2) plot(Q2linha,obtido_2,'--r',Q2linha,teorico2-dif2,'b') axis tight legend('Experiemental','by D. E. Peplow and K. Verghese') grid on end if(isequal(tipoSelecionado,'Adiposo ')) if(mostarJanela>0) figure(15) else axes('parent',tab3_4) end Adip = [1.02 1.02 1.02 1.02 1.02 1.02 1.032 1.106 1.259 1.599 2.032 2.349 2.094 1.667 1.433 1.297 1.216 1.109 1.089 1.051 1.049 1.03 1.042 1.013 1.006 0.954 0.907 0.795 0.722 0.682 0.654 0.638 0.634 0.633 0.628 0.601 0.558 0.53 0.498 0.464 0.439 0.427 0.421 0.411 0.395 0.395 0.365 0.355]; fator1=length(Q)/length(Adip ); Qlinha =Q(1:fator1:end); obtido_ = plotCorrigido(1:fator1:end); obitidoAux1 = obtido_.*(-1); tam = length(obtido_ ); if(max(obtido_)>max(Adip)) expValue1=floor(log10(max(obtido_)))+0.5; else expValue1=floor(log10(max(obtido_))) end [ pks,locs] = findpeaks(obitidoAux1,Qlinha,'MinPeakDistance',2) if(obtido_(1)> obtido_(5)) obtido_(1:locs(1))= (-1).*pks(1); end teorico = (Adip.*power(1E1,expValue1(1))); dif = teorico(1)-obtido_(1); plot(Qlinha,obtido_,'--r',Qlinha,teorico-dif,'b') axis tight grid on title('Comparação Fator de Forma Experimental X Teérico') legend('Experiemental','by M E Peplow et al') end if(isequal(tipoSelecionado,'Normal')) end if(isequal(tipoSelecionado,'Adenocarcenoma')) end mostarJanela= get(handles.PlotarEmNovaJanela,'Value'); if(mostarJanela>0) figure(2) else axes('parent',tab2) end % a(1)=a(1); n=plotCorrigido(a(1):end); ntotal=length(n(:,1)); fatr=str2double(get(handles.normalr,'String')); expValue=floor(log10(max(n)))+fatr; % power(1E1,expValue) for x=1:length(n) noramlizada= (((1/ntotal)*(normalizacao1(x,1))/n(x))); aa(x) = sum(noramlizada).*power(1E1,expValue); end bb=aa; noramlizada = (((1/ntotal).*(normalizacao1(round(a(1)):end,1)./n(:,1)))); hold off subplot(4,1,1) cla curvexy = [Q(a(1):end) n]; mapxy = [Q(a(1):end) normalizacao1(round(a(1)):end,1)]; [xy,distance,t] = distance2curve(curvexy,mapxy,'linear'); plot(mapxy(:,1),mapxy(:,2),'.-k','LineWidth',1.5) hold on ccc=rand(3,1); plot(xy(:,1),xy(:,2),'LineWidth',1.5,'color','r') line([mapxy(:,1),xy(:,1)]',[mapxy(:,2),xy(:,2)]','color',ccc); % plot(Q(a(1):end),normalizacao(a(1):end),'r',Q(a(1):end),plotCorrigido(a(1):end),'b' ) axis tight grid on subplot(4,1,2) cla plot(Q(a(1):end),bb,'r') axis tight yy = bb(1)- plotCorrigido(round(a(1))); % if(0>yy) plotFinal = plotCorrigido; plotFinal(a(1):end) =bb-yy; % else % plotFinal = plotCorrigido; % plotFinal(a(1):end) =noramlizada+yy; % end grid on subplot(4,1,3) cla plot(mapxy(:,1),mapxy(:,2),'.-k','LineWidth',1.5) hold on plot(xy(:,1),xy(:,2),'LineWidth',1.5,'color','r') hold all plot( Q(a(1):end),bb-yy,'.b') axis tight grid on subplot(4,1,4) cla plot(Q ,plotFinal ,'r') axis tight grid on % hold on plotCorrigido = plotFinal; assignin('base','plotCorrigido',plotCorrigido); media= mean(plotCorrigido,1); if(mostarJanela>0) figure(3) else axes('parent',tab3) end hold off subplot(3,1,1) cla % findpeaks(plotCorrigido,Q,'MinPeakDistance',2); % assignin('base','findps', findpeaks(plotCorrigido,Q,'Annotate','extents','WidthReference','halfheight','MinPeakDistance',2)); [pks,locs] = findpeaks(plotCorrigido(30:end,1),Q(30:end,1),'Annotate','extents','WidthReference','halfheight','MinPeakDistance',2); % [ pks,locs]= findpeaks(plotCorrigido,Q,'MinPeakDistance',2); plot(Q,plotCorrigido,locs ,pks ,'^') % hold on % plot(w,p) text(locs+.02,pks,num2str((1:numel(pks))')); % axis tight xlim([min(Q) max(Q)]) grid on title('picos com distancia min entre-picos (2)') % xy = [pks,locs]; subplot(3,1,2) cla % findpeaks(plotCorrigido,Q,'MinPeakDistance',5); [pks1,locs1]= findpeaks(plotCorrigido(30:end,1),Q(30:end,1),'Annotate','extents','WidthReference','halfheight','MinPeakDistance',5); plot(Q,plotCorrigido,locs1,pks1,'^') text(locs1+.02,pks1,num2str((1:numel(pks1))')); xlim([min(Q) max(Q)]) grid on title('picos com distancia min entre-picos (5)') % xy1 = [pks1,locs1]; subplot(3,1,3) cla % findpeaks(plotCorrigido,Q,'MinPeakHeight',media ); [pks2,locs2] = findpeaks(plotCorrigido(30:end,1),Q(30:end,1),'Annotate','extents','WidthReference','halfheight','MinPeakHeight',media ,'MinPeakDistance',5); plot(Q,plotCorrigido,locs2,pks2,'^') text(locs2+.02,pks2,num2str((1:numel(pks2))')); xlim([min(Q) max(Q)]) grid on % axis([min(Q(:)) max(Q(:)) min(plotCorrigido) max(plotCorrigido)+5E-25 ]) hold on plot(Q,media*ones(length(Q),1),'-.','LineWidth',2); title('picos superiores a média e d. entre-picos (5)') % set(gca,'XTick',[0:5: max(Q(:))],'XTickLabelRotation',45,'YTick',[0:1500: max(plotCorrigido)+1500]) % xy2= [pks2,locs2] ; hold off % Define variaveis presentes na tabela 2 (Tabela canto inferior a esquerda) ColunaNomes = {'Theta' 'q' 'I'}; set(handles.tabela2,'ColumnName',ColunaNomes); set(handles.tabela2, 'ColumnWidth',{40},'units','Normalized'); set(handles.tabela2,'Data',[dadosSelecionados(:,1)/2 Q dadosSelecionados(:,2)]); % Define variaveis presentes na tabela 3 (Tabela canto inferior a direita) ColunaNomes = {'I"'}; set(handles.tabela3,'ColumnName',ColunaNomes); set(handles.tabela3,'ColumnWidth',{40},'units','Normalized'); assignin('base','plotFinal',plotFinal); if(get(handles.detm,'Value')>0) figure(99) for x=1:8 x=x/2; if(max(normalizacao)>max(soPraisoo(2:end,1))) normalizacao1=normalizacao/(1.5*x*0.5); curvexy = [Q soPraisoo]; mapxy = [Q normalizacao1]; plot(curvexy(:,1),curvexy(:,2),'b',mapxy(:,1),mapxy(:,2),'r') grid on axis tight hold all pause(0.5) end end end function stat_Callback(~, ~, ~) global ... dadosSelecionados ... ; %usando média movel [tam, ~]=size(dadosSelecionados(:,2)); c = smooth( dadosSelecionados(:,2)); [~, ~]=size(c); C = reshape(c,tam,1); figure % subplot(3,1,1) plot(dadosSelecionados(:,2),':'); hold on plot(C,'-'); title('teste') % ------------------------funções internas-------------------------------% function graficosCorr_Callback(~, ~, ~) global volume ... QPOLAR ... Polarizacao ... Q ... IARpa4 ... IARpa3 ... IARpa2 ... IARpa1 ... PA_04_Antes ... PA_03_Antes ... PA_02_Antes ... PA_01_Antes ... PA_01_PLS_1MIN ... PA_02_PLS ... PA_03_PLS ... PA_04_PLS ... K ... IfilmePA4 ... IfilmePA3 ... IfilmePA2 ... IfilmePA1 ... IFilme ... IAR ... Ipa01 ... Ipa02 ... Ipa03 ... Ipa04 ... IPA ... caminhoDosArquivosDeTexto ; assignin('base','volume', volume ); assignin('base','QPOLAR', QPOLAR ); assignin('base','Polarizacao', Polarizacao ); assignin('base','Q', Q ); assignin('base','IARpa4', IARpa4 ); assignin('base','IARpa3', IARpa3 ); assignin('base','IARpa2', IARpa2 ); assignin('base','IARpa1', IARpa1 ); assignin('base','PA_04_Antes', PA_04_Antes ); assignin('base','PA_03_Antes', PA_03_Antes ); assignin('base','PA_02_Antes', PA_02_Antes ); assignin('base','PA_01_Antes', PA_01_Antes ); assignin('base','PA_01_PLS_1MIN', PA_01_PLS_1MIN ); assignin('base','PA_02_PLS', PA_02_PLS ); assignin('base','PA_03_PLS', PA_03_PLS ); assignin('base','PA_04_PLS', PA_04_PLS ); assignin('base','K', K ); hFig = figure; tabplot('Correção do volume',hFig,'top'); plot(volume); legend('G(q)') xlabel('q(nm^-^1)'); ylabel('G(q) mm^3'); grid on title('Correção do volume da amostra irradiada'); tabplot('Polarização',hFig); plot(QPOLAR,Polarizacao); legend('P(q)') xlabel('q(nm^-^1)'); ylabel('P(q)'); title('Fator de Polarização'); grid on % IfilmePA4 ... % IfilmePA3 ... % IfilmePA2 ... % IfilmePA1 ... % IFilme ... % IARpa4 ... % IARpa3 ... % IARpa2 ... % IARpa1 ... % IAR ... % Ipa01 ... % Ipa02 ... % Ipa03 ... % Ipa04 ... % IPA ... tabplot('Correção da intensidade do AR',hFig); subplot(4,1,1) plot(Q,IARpa4,'k',Q,IARpa3,'c',Q,IARpa2,'b',Q,IARpa1,'g',Q,IAR,'r'); grid on axis auto title('Intensidades Ar'); legend('IAR PA01','IAR PA02','IAR PA03','IAR PA04','IAR Média'); hold off subplot(4,1,2) plot(Q,PA_04_Antes,'k',Q,PA_04_Antes,'c',Q,PA_02_Antes,'b',Q,PA_01_Antes,'g') title('Int. plastico + Ar + PA - sem corrigir' ); xlabel('q(nm^-^1)'); ylabel('Int. do feixe (u.a.)'); legend('PA 04','PA 04','PA 02','IfilmePA1') axis auto subplot(4,1,3) plot(Q,IfilmePA4,'k',Q,IfilmePA3,'c',Q,IfilmePA2,'b',Q,IfilmePA1,'g',Q,IFilme ,'r') title('Int. plastico - corrigido'); xlabel('q(nm^-^1)'); ylabel('Int. do feixe (u.a.)'); legend('IfilmePA4','IfilmePA3','IfilmePA2','IfilmePA1','IFilme') axis auto subplot(4,1,4) plot(Q,Ipa01,'k',Q,Ipa02,'c',Q,Ipa03,'b',Q,Ipa04,'g',Q,IPA ,'r') title('Int. Pa '); xlabel('q(nm^-^1)'); ylabel('Int. do feixe (u.a.)'); legend('Ipa01','Ipa02','Ipa03','Ipa04','IPA Médio') axis auto tabplot('Sobreposição',hFig); prova= IAR+IFilme+IPA; plot(Q,IAR,'k',Q,IFilme,'c',Q,IPA,'b',Q,prova,'r' ) title(' '); xlabel('q(nm^-^1)'); ylabel('Int. do feixe (u.a.)'); legend('IAR','IFilme','IPA','Soma') axis auto tabplot('Dados de Energia I ',hFig); figgg = strcat(caminhoDosArquivosDeTexto,'\gp1.png'); I2=imread(figgg); imshow(I2); tabplot('K',hFig) plot(Q, K) axis([min(Q(:)) max(Q(:)) min(K) max(K)]) xlabel('q(nm^-^1)'); ylabel('Int. do feixe (u.a.)'); legend('K(q)') tabplot('K(q)*P(q)*A(q)',hFig) subplot(3,1,1) plot(Q,Polarizacao,'c',Q,volume,'b',Q,K','k') title('K(q) P(q) A(q)') legend('Polarização','A','K') axis([min(Q(:)) max(Q(:)) min([min(Polarizacao),min(volume),min(K)]) max([max(Polarizacao),max(volume),max(K)])]) fc=Polarizacao(:,1).*volume(:,1); grid on subplot(3,1,2) plot(Q,fc,'r','LineWidth',2) legend('K*Polarizacao*volume') title('correção P*A') axis([min(Q(:)) max(Q(:)) min(fc) max(fc)]) grid on subplot(3,1,3) fc2=1./fc(:,1); plot(Q,fc2,'b','LineWidth',2) legend('[Polarizacao*volume]^-1') title('correção (P*A) ^(^-^1^)') axis([min(Q(:)) max(Q(:)) min(fc2) max(fc2)]) grid on function padrao_Callback (hObject, ~, handles) global Q ... qCritico ... tab5 ... tabgp ... TETA ... Tar... Tpvc... Tamos... volume ... angCritico ... Tpa; tabgp.SelectedTab = tab5; hold off mostarJanela= get(handles.PlotarEmNovaJanela,'Value'); if(get(hObject,'Value')>0) setOFFeddits(handles); atualiza(handles); % for x=1:size(Q) % altura(x,1) = tan(Q(x,1)*(pi()/180)); % end valorA = str2double(get(handles.aa, 'String')); valorB = str2double(get(handles.bb, 'String')); valorH = str2double(get(handles.hhh,'String')); altura = rad2deg(atan(valorA/(2*valorH))) count=0; okay=false; % aaaa = Q(round(altura)) for x=1:length(Q) if(altura< TETA(x,1) && ~okay) angCritico =round(count) qCritico = Q(count,1) count okay = true; end count = count+1; end [miuAR,miuPVC,miuAMO,miuPA,lxAR,lxPVC,lxAMOS,lxPA,Tar,Tpvc,Tamos,Tpa] = getTodososvalores(handles,Q); CompX = str2double(get(handles.bb,'String')); CompY = str2double(get(handles.aa,'String')); CompZ = str2double(get(handles.hhh,'String')); volume = (CompX*CompY).*tan(TETA(:,1).*(pi()/180)); % Liteste= cos(TETA(:,1).*(pi()/180)).*sin(TETA(:,1).*(pi()/180))/(8*exp(1.069156)) % Litest1= cos(TETA(:,1).*(pi()/180))/exp(1.069156*CompX) % % volume = 1/CompY.*Litest1.^2.*(exp(-2*1.034*CompX)./Liteste) figure (33) plot(volume) pause(22) % resto = 2.1 - CompX; CompX = CompX + resto; if(mostarJanela>0) hFig = figure; else ax = axes('Parent', tab5); cla reset ax.BoxStyle = 'full'; ax.XAxisLocation = 'top'; ax.Position = [0.1 0.4 1.0 0.6]; end X = [ 0 ; CompX ; CompX ; 0 ; 0 ]; Y = [ 0 ; 0 ; CompY ; CompY ; 0 ]; Z = [ 0 ; 0 ; 0 ; 0 ; 0 ]; % axis off if(mostarJanela>0) tabplot(' 1 ',hFig,'top'); grid on end hold on; plot3(X-CompX/2,Y-0.5*CompY,Z); plot3(X-CompX/2,Y-0.5*CompY,Z+CompZ,'LineWidth',2.5); set(gca,'View',[-50,33]); for k=1:length(X)-1 plot3([X(k)-CompX/2;X(k)-CompX/2],[Y(k)-0.5*CompY;Y(k)-0.5*CompY],[0;CompZ],'LineWidth',2.5); end scatter3(7*35.*rand(300,1)/100-CompX/2,7*35.*rand(300,1)/100-3*CompY,35.*rand(300,1)/100-0.125,'red'); axis([-CompX CompX -CompX CompX 0 1]); % axis off % axis tight if(mostarJanela>0) tabplot(' 2 ',hFig,'top'); axis([-CompX CompX -CompX CompX 0 1]); grid on end grid on hold on nPhi = 256; nRho = 32; [X, Y, Z] = cylinder([linspace(0,CompX-0.1, nRho) CompX.*ones(1, nRho)], nPhi); Z(1:nRho,:) = 0; Z(nRho+1:end,:) = CompZ; surf(X,Y,Z, 'FaceColor', [0.97 0.97 0.97], 'FaceLighting', 'phong','EdgeColor', 'none'); hold on [X,Y,Z] = cylinder(linspace(0, 2, nRho), nPhi); Z(:,:) = CompZ-0.03; surf(X, Y, Z, 'FaceColor', [0 0.5 1], 'FaceLighting', 'phong', 'FaceAlpha',0.5, 'EdgeColor', 'none'); alpha(.2) camlight; hold off % axis off % axis tight if(mostarJanela>0) tabplot(' 3 ',hFig,'top'); grid on axis([-CompX CompX -CompX CompX 0 1]); hold off hold on; X = [ 0 ; CompX ; CompX ; 0 ; 0 ]; Y = [ 0 ; 0 ; CompY ; CompY ; 0 ]; Z = [ 0 ; 0 ; 0 ; 0 ; 0 ]; plot3(X-CompX/2,Y-0.5*CompY,Z); plot3(X-CompX/2,Y-0.5*CompY,Z+CompZ,'LineWidth',2.5); set(gca,'View',[-28,35]); for k=1:length(X)-1 plot3([X(k)-CompX/2;X(k)-CompX/2],[Y(k)-0.5*CompY;Y(k)-0.5*CompY],[0;CompZ],'LineWidth',2.5); end scatter3(7*35.*rand(300,1)/100-CompX/2,7*35.*rand(300,1)/100-3*CompY,35.*rand(300,1)/100,'g'); nPhi = 256; nRho = 32; [X, Y, Z] = cylinder([linspace(0, 2, nRho) CompX.*ones(1, nRho)], nPhi); Z(1:nRho,:) = 0; Z(nRho+1:end,:) = CompZ; surf(X,Y,Z, 'FaceColor', [0.97 0.97 0.97], 'FaceLighting', 'phong','EdgeColor', 'none'); hold on [X,Y,Z] = cylinder(linspace(0, 2, nRho), nPhi); Z(:,:) = CompZ -0.03; surf(X, Y, Z, 'FaceColor', [0 0.5 1], 'FaceLighting', 'phong', 'FaceAlpha',0.5, 'EdgeColor', 'none'); camlight; hold off end else setONeddits(handles); end function plus_Callback (hObject, eventdata, handles) global mais ... tabgp ; if (mais<1) set(hObject,'String','-'); set(tabgp,'Visible','off'); mais = 1; else set(hObject,'String','+'); set(tabgp,'Visible','on'); mais = 0; end function expotAmos_Callback(hObject, eventdata, handles) global caminhoDosArquivosDeTexto ... pastaSelecionada ... angCritico ... Tar ... IAR ... Arqselecionado ... PA_01_PLS_1MIN ... PA_02_PLS ... PA_03_PLS ... Tpvc ... PA_04_PLS ... IFilme ... PA_03_VZ_REP ... PA_01_VZ ... PA_02_VZ ... PA_04_VZ ... Tamos ... IPA ... Q ... K... Polarizacao... volume... TETA ... tipoSelecionado ... pa1fr... pa2fr... pa3fr... pa4fr... paMedio... fc2... r0; pa1fr =zeros(length(Q),1); pa2fr =zeros(length(Q),1); pa3fr =zeros(length(Q),1); pa4fr =zeros(length(Q),1); paMedio=zeros(length(Q),1); % % expotarTipoNomeFinal = strcat('amostras_',tipoSelecionado,'_',date,'.xlsx'); % startingFolder = strcat( caminhoDosArquivosDeTexto ,'arquivosSalvos'); % % defaultFileName = fullfile(startingFolder, expotarTipoNomeFinal ); % [baseFileName, expotarTipoNome] = uiputfile(defaultFileName, 'Salvar Como' ); % if (baseFileName == 0) % return; % end pa1fr(1 :angCritico,1) = Tar(1:angCritico,1 ).*IAR(1:angCritico ,1) + PA_01_PLS_1MIN(1:angCritico ,1); pa1fr(angCritico:end,1) = Tar(angCritico:end,1).*IAR(angCritico:end,1) + PA_01_PLS_1MIN(angCritico:end,1) - Tpvc(angCritico:end,1).*Tamos(angCritico:end,1).*PA_01_VZ(angCritico:end,1); pa2fr(1 :angCritico,1) = Tar(1:angCritico,1 ).*IAR(1:angCritico ,1) + PA_02_PLS(1:angCritico ,1); pa2fr(angCritico:end,1) = Tar(angCritico:end,1).*IAR(angCritico:end,1) + PA_02_PLS(angCritico:end,1) - Tpvc(angCritico:end,1).*Tamos(angCritico:end,1).*PA_02_VZ(angCritico:end,1); pa3fr(1 :angCritico,1) = Tar(1:angCritico,1 ).*IAR(1:angCritico ,1) + PA_03_PLS(1:angCritico ,1); pa3fr(angCritico:end,1) = Tar(angCritico:end,1).*IAR(angCritico:end,1) + PA_03_PLS(angCritico:end,1) - Tpvc(angCritico:end,1).*Tamos(angCritico:end,1).*PA_03_VZ_REP(angCritico:end,1); pa4fr(1 :angCritico,1) = Tar(1:angCritico,1 ).*IAR(1:angCritico ,1) + PA_04_PLS(1:angCritico ,1); pa4fr(angCritico:end,1) = Tar(angCritico:end,1).*IAR(angCritico:end,1) + PA_04_PLS(angCritico:end,1) - Tpvc(angCritico:end,1).*Tamos(angCritico:end,1).*PA_04_VZ(angCritico:end,1); paMedio( 1 :angCritico,1) = Tar(1:angCritico ,1).*IAR(1:angCritico ,1) + IFilme(1:angCritico ,1); paMedio(angCritico :end ,1) = Tar(angCritico:end,1).*IAR(angCritico:end,1) + IFilme(angCritico:end,1) - Tpvc(angCritico:end,1).*Tamos(angCritico:end,1).*IPA(angCritico:end,1); pa1fr=pa1fr(:,1)./Tpvc(:,1); pa2fr=pa2fr(:,1)./Tpvc(:,1); pa3fr=pa3fr(:,1)./Tpvc(:,1); pa4fr=pa4fr(:,1)./Tpvc(:,1); paMedio=paMedio(:,1)./Tpvc(:,1); fc =K(:,1).*Polarizacao(:,1).*volume(:,1); fc2=1./(fc); fc2(1:10,1)=1; r0 =((2.83E-15^2)/2).*(1+power(cos(TETA(:,1)*pi()/40),2)); arquivoSelecionados = cellstr(get(handles.listbox1,'String')); cont=0; auxSemCorr = zeros(length(PA_02_PLS),1)'; auxCorrigida = zeros(length(PA_02_PLS),1)'; auxCorrigidaMedia= zeros(length(PA_02_PLS),1)'; auxImedida= zeros(length(PA_02_PLS),1)'; auxImedidaMedia= zeros(length(PA_02_PLS),1)'; auxInormalizacao = zeros(length(PA_02_PLS),1)'; auxFinalmediadaMaisNorm = zeros(length(PA_02_PLS),1)' ; auxFinalmediadaMaisNormMedia = zeros(length(PA_02_PLS),1)' ; normalizaAmostra = zeros(length(PA_02_PLS),1)' ; normalizaMedia = zeros(length(PA_02_PLS),1)' ; % data1 = zeros(2,length(arquivoSelecionados))' ; % % for x=1:length(arquivoSelecionados) [tipoPortaAmostra,~] = strsplit(char(Arqselecionado(1)),{' ','.txt'},'CollapseDelimiters',true); txtSelect = char((strcat(caminhoDosArquivosDeTexto,pastaSelecionada,'\',Arqselecionado(1)))); [tipo,~] = strsplit(pastaSelecionada,'\','CollapseDelimiters',true); data1(1,:)= [tipoPortaAmostra(1) tipoPortaAmostra(2) tipo(2)]; % cellstr(data1{x}) expotarTipoNome= char(strcat(tipoPortaAmostra(1),'_',tipoSelecionado,'_',date,'.xlsx')); if( isempty(char(Arqselecionado(1)))) aux1 =strcat('Selecione uma opção valida, a pasta: [ ',caminhoDosArquivosDeTexto,pastaSelecionada,'] parece estar vazia ') uiwait(warndlg(aux1)); return end % [valores, ... % plotFinal, ... % plotFinal2,... % normalizacao,... % Iamostra, ... % IamostraMedia, ... % plotCorrigido,... % plotCorrigidoMedio,... % noramlizada, ... % noramlizada2] = readFile(txtSelect,tipoPortaAmostra(2),handles); [valores, ... Iamostra, ... IamostraMedia, ... plotCorrigido,... plotCorrigidoMedio] = readFile(txtSelect,tipoPortaAmostra(2),handles); auxSemCorrigir (1,:) = valores; auxCorrigida(1,:) = plotCorrigido; auxCorrigidaMedia(1,:) = plotCorrigidoMedio; auxImedida(1,:) = Iamostra; auxImedidaMedia(1,:) = IamostraMedia; % auxInormalizacao(1,:) = normalizacao; % auxFinalmediadaMaisNorm(1,:) = plotFinal; % auxFinalmediadaMaisNormMedia(1,:) = plotFinal2; % % cont = cont +1; % end h = waitbar(0,'Exportando resultados para excel..'); warning('off','MATLAB:xlswrite:addSheet') i=0; % xlswrite (expotarTipoNome, data1,'Corr. (esxp+norm)','A1'); % i=i+1; waitbar(i/16); % xlswrite (expotarTipoNome, data1,'Corr.(esxp+norm)Média','A1'); % i=i+1; waitbar(i/16); xlswrite (expotarTipoNome, data1,'semCorreção','A1'); i=i+1; waitbar(i/10); xlswrite (expotarTipoNome, data1,'correção expurias','A1'); i=i+1; waitbar(i/10); xlswrite (expotarTipoNome, data1,'correção expurias Média','A1'); i=i+1; waitbar(i/10); xlswrite (expotarTipoNome, data1,'Im(só transmição)','A1'); i=i+1; waitbar(i/10); xlswrite (expotarTipoNome, data1,'Im(só trans) Média','A1'); i=i+1; waitbar(i/10); % xlswrite (expotarTipoNome, data1,'normalização p.amostra','A1'); % i=i+1; waitbar(i/16); % xlswrite (expotarTipoNome, auxFinalmediadaMaisNorm,'Corr. (esxp+norm)','D1'); % i=i+1; waitbar(i/16); % xlswrite (expotarTipoNome, auxFinalmediadaMaisNormMedia,'Corr.(esxp+norm)Média','D1'); % i=i+1; waitbar(i/16); xlswrite (expotarTipoNome, auxSemCorrigir,'semCorreção','D1'); i=i+1; waitbar(i/10); xlswrite (expotarTipoNome, auxCorrigida,'expurias+r0','D1'); i=i+1; waitbar(i/10); xlswrite (expotarTipoNome, auxCorrigidaMedia,'espurias+r0 Média','D1'); i=i+1; waitbar(i/10); xlswrite (expotarTipoNome, auxImedida,'Im(só transmição)','D1'); i=i+1; waitbar(i/10); xlswrite (expotarTipoNome, auxImedidaMedia,'Im(só trans) Média','D1'); i=i+1; waitbar(i/10); % xlswrite (expotarTipoNome, auxInormalizacao,'normalização p.amostra','D1'); % i=i+1; waitbar(i/16); delete(h) function export_Callback (~, ~, handles) global caminhoDosArquivosDeTexto ... pastaSelecionada ... angCritico ... Tar ... IAR ... PA_01_PLS_1MIN ... PA_02_PLS ... PA_03_PLS ... Tpvc ... PA_04_PLS ... IFilme ... PA_03_VZ_REP ... PA_01_VZ ... PA_02_VZ ... PA_04_VZ ... Tamos ... IPA ... Q ... K... Polarizacao... volume... TETA ... tipoSelecionado ... pa1fr... pa2fr... pa3fr... pa4fr... paMedio... fc2... r0; pa1fr =zeros(length(Q),1); pa2fr =zeros(length(Q),1); pa3fr =zeros(length(Q),1); pa4fr =zeros(length(Q),1); paMedio=zeros(length(Q),1); % % expotarTipoNomeFinal = strcat('amostras_',tipoSelecionado,'_',date,'.xlsx'); expotarTipoNome= strcat('amostras_',tipoSelecionado,'_',date,'.xlsx'); % startingFolder = strcat( caminhoDosArquivosDeTexto ,'arquivosSalvos'); % % defaultFileName = fullfile(startingFolder, expotarTipoNomeFinal ); % [baseFileName, expotarTipoNome] = uiputfile(defaultFileName, 'Salvar Como' ); % if (baseFileName == 0) % return; % end pa1fr(1 :angCritico,1) = Tar(1:angCritico,1 ).*IAR(1:angCritico ,1) + PA_01_PLS_1MIN(1:angCritico ,1); pa1fr(angCritico:end,1) = Tar(angCritico:end,1).*IAR(angCritico:end,1) + PA_01_PLS_1MIN(angCritico:end,1) - Tpvc(angCritico:end,1).*Tamos(angCritico:end,1).*PA_01_VZ(angCritico:end,1); pa2fr(1 :angCritico,1) = Tar(1:angCritico,1 ).*IAR(1:angCritico ,1) + PA_02_PLS(1:angCritico ,1); pa2fr(angCritico:end,1) = Tar(angCritico:end,1).*IAR(angCritico:end,1) + PA_02_PLS(angCritico:end,1) - Tpvc(angCritico:end,1).*Tamos(angCritico:end,1).*PA_02_VZ(angCritico:end,1); pa3fr(1 :angCritico,1) = Tar(1:angCritico,1 ).*IAR(1:angCritico ,1) + PA_03_PLS(1:angCritico ,1); pa3fr(angCritico:end,1) = Tar(angCritico:end,1).*IAR(angCritico:end,1) + PA_03_PLS(angCritico:end,1) - Tpvc(angCritico:end,1).*Tamos(angCritico:end,1).*PA_03_VZ_REP(angCritico:end,1); pa4fr(1 :angCritico,1) = Tar(1:angCritico,1 ).*IAR(1:angCritico ,1) + PA_04_PLS(1:angCritico ,1); pa4fr(angCritico:end,1) = Tar(angCritico:end,1).*IAR(angCritico:end,1) + PA_04_PLS(angCritico:end,1) - Tpvc(angCritico:end,1).*Tamos(angCritico:end,1).*PA_04_VZ(angCritico:end,1); paMedio( 1 :angCritico,1) = Tar(1:angCritico ,1).*IAR(1:angCritico ,1) + IFilme(1:angCritico ,1); paMedio(angCritico :end ,1) = Tar(angCritico:end,1).*IAR(angCritico:end,1) + IFilme(angCritico:end,1) - Tpvc(angCritico:end,1).*Tamos(angCritico:end,1).*IPA(angCritico:end,1); pa1fr=pa1fr(:,1)./Tpvc(:,1); pa2fr=pa2fr(:,1)./Tpvc(:,1); pa3fr=pa3fr(:,1)./Tpvc(:,1); pa4fr=pa4fr(:,1)./Tpvc(:,1); paMedio=paMedio(:,1)./Tpvc(:,1); fc =K(:,1).*Polarizacao(:,1).*volume(:,1); fc2=1./(fc); fc2(1:10,1)=1; r0 =((2.83E-15^2)/2).*(1+power(cos(TETA(:,1)*pi()/40),2)); arquivoSelecionados = cellstr(get(handles.listbox1,'String')); cont=0; auxSemCorr = zeros(length(PA_02_PLS),length(arquivoSelecionados))'; auxCorrigida = zeros(length(PA_02_PLS),length(arquivoSelecionados))'; auxCorrigidaMedia= zeros(length(PA_02_PLS),length(arquivoSelecionados))'; auxImedida= zeros(length(PA_02_PLS),length(arquivoSelecionados))'; auxImedidaMedia= zeros(length(PA_02_PLS),length(arquivoSelecionados))'; auxInormalizacao = zeros(length(PA_02_PLS),length(arquivoSelecionados))'; auxFinalmediadaMaisNorm = zeros(length(PA_02_PLS),length(arquivoSelecionados))' ; auxFinalmediadaMaisNormMedia = zeros(length(PA_02_PLS),length(arquivoSelecionados))' ; normalizaAmostra = zeros(length(PA_02_PLS),length(arquivoSelecionados))' ; normalizaMedia = zeros(length(PA_02_PLS),length(arquivoSelecionados))' ; % data1 = zeros(2,length(arquivoSelecionados))' ; for x=1:length(arquivoSelecionados) [Arqselecionado ,~] = strsplit(arquivoSelecionados{x} , ' [','CollapseDelimiters',true); [tipoPortaAmostra,~] = strsplit(char(Arqselecionado(1)),{' ','.txt'},'CollapseDelimiters',true); txtSelect = char((strcat(caminhoDosArquivosDeTexto,pastaSelecionada,'\',Arqselecionado(1)))); [tipo,~] = strsplit(pastaSelecionada,'\','CollapseDelimiters',true); legendInfo(x,1) = tipoPortaAmostra(1); % or whatever is appropriate data1(x,:)= [tipoPortaAmostra(1) tipoPortaAmostra(2) tipo(2)]; % cellstr(data1{x}) if( isempty(char(Arqselecionado(1)))) aux1 =strcat('Selecione uma opção valida, a pasta: [ ',caminhoDosArquivosDeTexto,pastaSelecionada,'] parece estar vazia ') uiwait(warndlg(aux1)); return end % % [valores, ... % plotFinal, ... % plotFinal2,... % normalizacao,... % Iamostra, ... % IamostraMedia, ... % plotCorrigido,... % plotCorrigidoMedio,... % noramlizada, ... % noramlizada2] = readFile(txtSelect,tipoPortaAmostra(2),handles); [valores, ... Iamostra, ... IamostraMedia, ... plotCorrigido,... plotCorrigidoMedio] = readFile(txtSelect,tipoPortaAmostra(2),handles); auxSemCorrigir (x,:) = valores; auxCorrigida(x,:) = plotCorrigido; auxCorrigidaMedia(x,:) = plotCorrigidoMedio; auxImedida(x,:) = Iamostra; auxImedidaMedia(x,:) = IamostraMedia; % auxInormalizacao(x,:) = normalizacao; % auxFinalmediadaMaisNorm(x,:) = plotFinal; % auxFinalmediadaMaisNormMedia(x,:) = plotFinal2; cont = cont +1; end figure(8) legend(legendInfo) title('por PA') figure(9) title('por Média dos PAs 1-4') legend(legendInfo) h = waitbar(0,'Exportando resultados para excel..'); warning('off','MATLAB:xlswrite:addSheet') i=0; % xlswrite (expotarTipoNome, data1,'semCorreção','A1'); % i=i+1; waitbar(i/10); % xlswrite (expotarTipoNome, data1,'correção','A1'); % i=i+1; waitbar(i/10); % xlswrite (expotarTipoNome, data1,'correção Média','A1'); % i=i+1; waitbar(i/10); % xlswrite (expotarTipoNome, data1,'Im(só transmição)','A1'); % i=i+1; waitbar(i/10); % xlswrite (expotarTipoNome, data1,'Im(só trans) Média','A1'); % i=i+1; waitbar(i/10); % % xlswrite (expotarTipoNome, auxSemCorrigir,'semCorreção','D1'); % i=i+1; waitbar(i/10); % xlswrite (expotarTipoNome, auxCorrigida,'correção','D1'); % i=i+1; waitbar(i/10); % xlswrite (expotarTipoNome, auxCorrigidaMedia,'correção Média','D1'); % i=i+1; waitbar(i/10); % xlswrite (expotarTipoNome, auxImedida,'Im(só transmição)','D1'); % i=i+1; waitbar(i/10); % xlswrite (expotarTipoNome, auxImedidaMedia,'Im(só trans) Média','D1'); % i=i+1; waitbar(i/10); % %nao usar % xlswrite (expotarTipoNome, data1,'Corr. (esxp+norm)','A1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, data1,'Corr.(esxp+norm)Média','A1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, data1,'semCorreção','A1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, data1,'expurias+r0','A1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, data1,'espurias+r0 Média','A1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, data1,'Im(só transmição)','A1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, data1,'Im(só trans) Média','A1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, data1,'normalização p.amostra','A1'); % ii=ii+1; waitbar(ii/16); % % xlswrite (expotarTipoNome, auxFinalmediadaMaisNorm,'Corr. (esxp+norm)','D1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, auxFinalmediadaMaisNormMedia,'Corr.(esxp+norm)Média','D1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, auxSemCorrigir,'semCorreção','D1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, auxCorrigida,'expurias+r0','D1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, auxCorrigidaMedia,'espurias+r0 Média','D1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, auxImedida,'Im(só transmição)','D1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, auxImedidaMedia,'Im(só trans) Média','D1'); % ii=ii+1; waitbar(ii/16); % xlswrite (expotarTipoNome, auxInormalizacao,'normalização p.amostra','D1'); % ii=ii+1; waitbar(ii/16); % % delete(h) function [valores, ... Iamostra, ... IamostraMedia, ... plotCorrigido,... plotCorrigidoMedio] = readFile(enderecoDoAqrquvo,pAselecionadox,handles) % [valores, ... % plotFinal, ... % plotFinal2,... % normalizacao,... % Iamostra, ... % IamostraMedia, ... % plotCorrigido,... % plotCorrigidoMedio,... % noramlizada, ... % noramlizada2] = readFile(enderecoDoAqrquvo,pAselecionadox,handles) global ... K... Polarizacao... volume... pa1fr... pa2fr... pa3fr... pa4fr... paMedio... Tpvc ... Q ... r0; fid = fopen(enderecoDoAqrquvo); tline = fgetl(fid); ok=0; i=0; tamanho=234; valores = nan(tamanho, 1); while ischar(tline) delimiter= findstr('<2Theta>', tline); tam=size(delimiter); if((ok>0) | (delimiter > 0) ) ok=ok+1; end if(ok>1) convertePataFloat = strread(tline,'%f','delimiter',' '); i=i+1; % valores(i,1) = convertePataFloat(1); valores(i,1) = convertePataFloat(2); end tline = fgetl(fid); end fclose(fid); % /---------- para H20 1min achei =false; if(strcmp(pAselecionadox,'PA01')) % Iamostra = valores(:,1)./Tpvc(:,1) - pa1fr(:,1)- K(:,1); % plotCorrigido = (Iamostra(:,1)./(Polarizacao(:,1).*volume(:,1))).*r0(:,1); % Iamostra = (valores(:,1)./Tpvc(:,1)- pa1fr(:,1)).*1./(K(:,1)+volume).*Polarizacao; Iamostra = (valores(:,1)./Tpvc(:,1)- pa1fr(:,1)).*1./K(:,1).*volume.*Polarizacao; plotCorrigido = Iamostra; achei =true; end if(strcmp(pAselecionadox,'PA02')) % Iamostra = valores(:,1)./Tpvc(:,1) - pa2fr(:,1)- K(:,1); % plotCorrigido = (Iamostra(:,1)./(Polarizacao(:,1).*volume(:,1))).*r0(:,1); % Iamostra = (valores(:,1)./Tpvc(:,1)- pa2fr(:,1)).*1./(K(:,1)+volume).*Polarizacao; Iamostra = (valores(:,1)./Tpvc(:,1)- pa2fr(:,1)).*1./K(:,1).*volume.*Polarizacao; plotCorrigido = Iamostra; achei =true; end if(strcmp(pAselecionadox,'PA03')) % Iamostra = valores(:,1)./Tpvc(:,1) - pa3fr(:,1)- K(:,1); % plotCorrigido = (Iamostra(:,1)./(Polarizacao(:,1).*volume(:,1))).*r0(:,1); % Iamostra = (valores(:,1)./Tpvc(:,1)- pa3fr(:,1)).*1./(K(:,1)+volume).*Polarizacao; Iamostra = (valores(:,1)./Tpvc(:,1)- pa3fr(:,1)).*1./K(:,1).*volume.*Polarizacao; plotCorrigido = Iamostra; achei =true; end if(strcmp(pAselecionadox,'PA04')) % Iamostra = valores(:,1)./Tpvc(:,1) - pa4fr(:,1)- K(:,1); % plotCorrigido = (Iamostra(:,1)./(Polarizacao(:,1).*volume(:,1))).*r0(:,1); % Iamostra = (valores(:,1)./Tpvc(:,1)- pa4fr(:,1)).*1./(K(:,1)+volume).*Polarizacao; Iamostra = (valores(:,1)./Tpvc(:,1)- pa4fr(:,1)).*1./K(:,1).*volume.*Polarizacao; plotCorrigido = Iamostra; achei =true; end if(~achei) plotCorrigido=zeros(length(Q),1); plotCorrigidoMedio=zeros(length(Q),1); IamostraMedia = (valores(:,1)./Tpvc(:,1)-paMedio(:,1)).*1./K(:,1).*volume.*Polarizacao; %IamostraMedia = (valores(:,1)./Tpvc(:,1)- paMedio(:,1)).*1./(K(:,1)+volume).*Polarizacao; Iamostra=IamostraMedia; % IamostraMedia = valores(:,1)./Tpvc(:,1) - paMedio(:,1)- K(:,1); % plotCorrigidoMedio = (IamostraMedia(:,1)./(Polarizacao(:,1).*volume(:,1))).*r0(:,1); % plotCorrigido = Iamostra; plotCorrigido = smooth( IamostraMedia); plotCorrigidoMedio = smooth( IamostraMedia); else % IamostraMedia = valores(:,1)./Tpvc(:,1) - paMedio(:,1)- K(:,1); % plotCorrigidoMedio = (IamostraMedia(:,1)./(Polarizacao(:,1).*volume(:,1))).*r0(:,1); IamostraMedia = (valores(:,1)./Tpvc(:,1)-paMedio(:,1)).*1./K(:,1).*volume.*Polarizacao; %IamostraMedia = (valores(:,1)./Tpvc(:,1)- paMedio(:,1)).*1./(K(:,1)+volume).*Polarizacao; plotCorrigido = smooth( plotCorrigido); plotCorrigidoMedio = smooth( IamostraMedia); end % normalizacao = [ 8.12 8.12 8.12 8.10 8.09 8.07 8.05 8.01 7.99 7.95 7.91 7.86 7.82 7.77 7.72 7.66 7.60 7.54 7.47 7.40 7.34 7.26 7.19 7.11 7.03 6.95 6.87 6.79 6.71 6.62 6.54 6.45 6.36 6.27 6.19 6.10 6.01 5.92 5.84 5.75 5.66 5.57 5.49 5.40 5.32 5.24 5.15 5.07 4.99 4.91 4.83 4.75 4.68 4.60 4.52 4.45 4.38 4.31 4.24 4.17 4.10 4.04 3.97 3.91 3.85 3.78 3.72 3.67 3.61 3.55 3.50 3.44 3.39 3.34 3.29 3.24 3.19 3.15 3.10 3.06 3.01 2.97 2.93 2.89 2.85 2.81 2.77 2.74 2.70 2.67 2.63 2.60 2.57 2.54 2.51 2.48 2.45 2.42 2.39 2.37 2.34 2.32 2.29 2.27 2.25 2.22 2.20 2.18 2.16 2.14 2.12 2.10 2.08 2.06 2.05 2.03 2.01 1.99 1.98 1.96 1.95 1.93 1.92 1.91 1.89 1.88 1.87 1.85 1.84 1.83 1.82 1.81 1.79 1.78 1.77 1.76 1.75 1.74 1.73 1.72 1.71 1.71 1.70 1.69 1.68 1.67 1.67 1.66 1.65 1.64 1.64 1.63 1.62 1.62 1.61 1.60 1.59 1.59 1.58 1.57 1.57 1.56 1.55 1.53 1.52 1.51 1.50 1.49 1.48 1.47 1.46 1.45 1.44 1.44 1.43 1.42 1.41 1.40 1.39 1.39 1.38 1.36 1.34 1.33 1.31 1.30 1.28 1.27 1.25 1.24 1.22 1.20 1.19 1.18 1.20 1.19 1.18 1.165335835 1.15 1.13 1.14 1.13 1.12 1.11 1.11 1.10 1.09 1.08 1.08 1.07 1.06 1.05 1.04 1.04 1.03 1.02 1.01 1.01 1.00 0.99 0.98 0.97 0.97 0.96 0.95 0.943643389 0.94 0.93 0.92 0.91 0.90 0.90 0.89 0.88 ]'; % normalizacao = normalizacao.*(2.83E-25)/4; % MostrarNegv = get(handles.negv,'Value'); if(MostrarNegv>0) plotCorrigido(plotCorrigido<0)=0; plotCorrigidoMedio(plotCorrigidoMedio<0)=0; end % expValue=floor(log10(max(plotCorrigido))); % expValue2=floor(log10(max(plotCorrigidoMedio))); % coun = 0; % % for x=1:8 % x=x/2; % if(max(normalizacao)>max(plotCorrigido(2:end,1))) % normalizacao1=normalizacao/(1.3*x*0.5); % curvexy = [Q plotCorrigido]; % % % mapxy = [Q normalizacao1]; % [xy,distance,t] = distance2curve(curvexy,mapxy,'linear'); % distancia = distance.*power(1E+1,abs(expValue)); % coun = coun +1; % % curvexy2 = [Q plotCorrigidoMedio]; % mapxy2 = [Q normalizacao1]; % [xy2,distance2,t2] = distance2curve(curvexy2,mapxy2,'linear'); % distancia2 = distance2.*power(1E+1,abs(expValue2)); % coun = coun +1; % % end % if(coun == 0 & (max(plotCorrigido(2:end))>max(normalizacao))) % curvexy = [Q plotCorrigido]; % normalizacao1=normalizacao/(1.3*x); % mapxy = [Q normalizacao1]; % expValue=floor(log10(max(plotCorrigido))); % [xy,distance,t] = distance2curve(curvexy,mapxy,'linear'); % distancia = distance.*power(1E+1,abs(expValue)); % % curvexy2 = [Q plotCorrigidoMedio]; % mapxy2 = [Q normalizacao]; % [xy2,distance2,t2] = distance2curve(curvexy2,mapxy2,'linear'); % distancia2 = distance2.*power(1E+1,abs(expValue2)); % coun = coun +1; % % continue % end % end % % a = find(abs(distancia)<2E-1); % a = a(a > 60); % % a2 = find(abs(distancia2)<2E-1); % a2 = a2(a2 > 60); % % aux = min(Q(a(:))); % aux2 = min(Q(a2(:))); % if(isempty(aux)) % a = [150 152]'; % end % % if(isempty(aux2)) % a2 = [150 152]'; % end % % a(1)=a(1)+10; % a2(1)=a2(1)+10; % n=plotCorrigido(a(1):end); % n2=plotCorrigidoMedio(a2(1):end); % % % ntotal=length(n(:,1)); % ntotal2=length(n2(:,1)); % for x=1:length(n) % noramlizada = (((1/ntotal )*(normalizacao1(x,1))/n(x) )); % aa (x) = sum(noramlizada).*1E-24; % end % for x=1:length(n2) % noramlizada2 = (((1/ntotal2)*(normalizacao1(x,1))/n2(x))); % aa2(x) = sum(noramlizada2).*1E-24; % end % % % bb=aa; % noramlizada = aa; % bb2=aa2; % noramlizada2 = aa2; % yy = bb (1)- plotCorrigido(round(a(1))); % yy2 = bb2(1)- plotCorrigidoMedio(round(a2(1))); % % % if(0>yy) % plotFinal = plotCorrigido; % plotFinal(a(1):end) =bb-yy; % % else % % plotFinal = plotCorrigido; % % plotFinal(a(1):end) =bb+yy; % % end % % % if(0>yy2) % plotFinal2 = plotCorrigidoMedio; % plotFinal2(a2(1):end) = bb2-yy2; % % else % % plotFinal2 = plotCorrigidoMedio; % % plotFinal2(a2(1):end) = bb2+yy2; % % end % figure(8) hold on grid on plot(Q,plotCorrigido) hold all figure(9) hold on grid on plot(Q,plotCorrigidoMedio) % legend() hold all figure(10) hold on grid on plot(valores) % legend() hold all %############################################################################## function listbox1_CreateFcn (hObject, ~, ~ ) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function selecionaCaso_Callback(~, ~, handles ) global caminhoDosArquivosDeTexto ... pastaSelecionada ... tipoSelecionado; set(handles.listbox1,'String',''); todosTipos = cellstr(get(handles.selecionaCaso,'String')); tipoSelecionado = todosTipos{get(handles.selecionaCaso,'Value')}; pastaSelecionada = strcat('textData\',tipoSelecionado); files = dir(fullfile(caminhoDosArquivosDeTexto,pastaSelecionada,'*.txt')); set(handles.listbox1,'Value',1); todosTipos = {files.name}; todosDAtas = {files.date}; for x=1: length({files.name}) dadoss{x} = strcat(todosTipos{x},' [',todosDAtas{x},']'); end todosNomes=cell2struct(dadoss,'nomes',1); set(handles.listbox1,'String',{todosNomes.nomes}); set(handles.listbox2,'String',{'Intensidade do Porta Amostra Vazio',... 'Intensidade do Filme',... 'Intensidade da H20 1Min', ... 'Intensidade do Ar' }); function p1_Callback (hObject, ~, handles) global caminhoDosArquivosDeTexto; contents = cellstr(get(hObject,'String')); aux = strcat( contents{get(hObject,'Value')},'.txt'); nomeDensidade = contents{get(hObject,'Value')}; txtSelect = strcat(caminhoDosArquivosDeTexto,'AttCoefficients\',aux); txtDensidade = strcat(caminhoDosArquivosDeTexto,'densidades.txt'); set(handles.text14,'String',contents{get(hObject,'Value')}); fid = fopen(txtSelect); tline = fgetl(fid); i=0; while ischar(tline) convertePataFloat = strread(tline,'%f','delimiter','K'); i=i+1; [tam, ~] =size(convertePataFloat); if(tam>3) dadosSelecionados(i,:)=convertePataFloat(2:4)'; else dadosSelecionados(i,:) = convertePataFloat'; end tline = fgetl(fid); end fclose(fid); mostarTabela= get(handles.energia,'Value'); dadosSelecionados(:,1)= dadosSelecionados(:,1).*1000; valorEnergia=get(handles.edit16,'String'); if(valorEnergia< 1 | isnan(str2double(valorEnergia))) uiwait(warndlg('Medidas não encontradas ou invalidas. Para continuar é preciso inserir medidas validas')); set(handles.aa,'BackgroundColor','red'); set(handles.bb,'BackgroundColor','red'); set(handles.hhh,'BackgroundColor','red'); set(handles.edit16,'BackgroundColor','red'); return end set(handles.p11,'BackgroundColor','green'); set(handles.p12,'BackgroundColor','green'); fid = fopen(txtDensidade); tline = fgetl(fid); i=0; while ischar(tline) convertePataFloat = strread(tline,'%s','delimiter','|'); convertePataFloat2 = strread(convertePataFloat{2},'%f','delimiter',' '); densidade = convertePataFloat2(3); if(isequal(nomeDensidade,convertePataFloat{1})) densidadeSelecionada=densidade; set(handles.p12,'String',densidade) end tline = fgetl(fid); end fclose(fid); achou=false; for x=1:size(dadosSelecionados) if(isequal(round(dadosSelecionados(x,1)),round(str2double(valorEnergia)))&& ~achou) miu=dadosSelecionados(x,2)*densidadeSelecionada; set(handles.p11,'String',miu); achou=true; end end if(mostarTabela) ColunaNomes = {'(Kev)' '(cm^2/g)' 'mu(en)/rho'}; set(handles.tabela2,'ColumnName',ColunaNomes); set(handles.tabela2,'Data',dadosSelecionados); set(handles.tabela2, 'ColumnWidth',{60},'units','Normalized'); end function p2_Callback (hObject, ~, handles) global caminhoDosArquivosDeTexto; contents = cellstr(get(hObject,'String')); aux= strcat( contents{get(hObject,'Value')},'.txt'); nomeDensidade=contents{get(hObject,'Value')}; txtSelect = strcat(caminhoDosArquivosDeTexto,'AttCoefficients\',aux); txtDensidade= strcat(caminhoDosArquivosDeTexto,'densidades.txt'); fid = fopen(txtSelect); tline = fgetl(fid); i=0; valorEnergia=get(handles.edit16,'String'); if(valorEnergia< 1 | isnan(str2double(valorEnergia))) uiwait(warndlg('Medidas não encontradas ou invalidas. Para continuar é preciso inserir medidas validas')); set(handles.aa,'BackgroundColor','red'); set(handles.bb,'BackgroundColor','red'); set(handles.hhh,'BackgroundColor','red'); set(handles.edit16,'BackgroundColor','red'); return end set(handles.p21,'BackgroundColor','green'); set(handles.p22,'BackgroundColor','green'); while ischar(tline) convertePataFloat = strread(tline,'%f','delimiter','K'); i=i+1; [tam, ~] =size(convertePataFloat); if(tam>3) dadosSelecionados(i,:)=convertePataFloat(2:4)'; else dadosSelecionados(i,:) = convertePataFloat'; end tline = fgetl(fid); end fclose(fid); mostarTabela= get(handles.energia,'Value'); dadosSelecionados(:,1)= dadosSelecionados(:,1).*1000; fid = fopen(txtDensidade); tline = fgetl(fid); i=0; while ischar(tline) convertePataFloat = strread(tline,'%s','delimiter','|'); convertePataFloat2 = strread(convertePataFloat{2},'%f','delimiter',' '); densidade = convertePataFloat2(3); if(isequal(nomeDensidade,convertePataFloat{1})) densidadeSelecionada=densidade; set(handles.p22,'String',densidade) end tline = fgetl(fid); end fclose(fid); achou=false; for x=1:size(dadosSelecionados) if(isequal(round(dadosSelecionados(x,1)),round(str2double(valorEnergia)))&& ~achou) achou=true; miu=dadosSelecionados(x,2)*densidadeSelecionada; set(handles.p21,'String',miu); end end if(mostarTabela) ColunaNomes = {'(Kev)' '(cm^2/g)' 'mu(en)/rho'}; set(handles.tabela2,'ColumnName',ColunaNomes); set(handles.tabela2,'Data',dadosSelecionados); set(handles.tabela2, 'ColumnWidth',{40},'units','Normalized'); end function p3_Callback (hObject, ~, handles) global caminhoDosArquivosDeTexto; contents = cellstr(get(hObject,'String')); aux= strcat( contents{get(hObject,'Value')},'.txt'); nomeDensidade=contents{get(hObject,'Value')}; txtSelect = strcat(caminhoDosArquivosDeTexto,'AttCoefficients\',aux); txtDensidade= strcat(caminhoDosArquivosDeTexto,'densidades.txt'); fid = fopen(txtSelect); tline = fgetl(fid); i=0; valorEnergia=get(handles.edit16,'String'); if(valorEnergia< 1 | isnan(str2double(valorEnergia))) uiwait(warndlg('Medidas não encontradas ou invalidas. Para continuar é preciso inserir medidas validas')); set(handles.aa,'BackgroundColor','red'); set(handles.bb,'BackgroundColor','red'); set(handles.hhh,'BackgroundColor','red'); set(handles.edit16,'BackgroundColor','red'); return end set(handles.p31,'BackgroundColor','green'); set(handles.p32,'BackgroundColor','green'); while ischar(tline) convertePataFloat = strread(tline,'%f','delimiter','K'); i=i+1; [tam, ~] =size(convertePataFloat); if(tam>3) dadosSelecionados(i,:)=convertePataFloat(2:4)'; else dadosSelecionados(i,:) = convertePataFloat'; end tline = fgetl(fid); end fclose(fid); mostarTabela= get(handles.energia,'Value'); dadosSelecionados(:,1)= dadosSelecionados(:,1).*1000; fid = fopen(txtDensidade); tline = fgetl(fid); i=0; while ischar(tline) convertePataFloat = strread(tline,'%s','delimiter','|'); convertePataFloat2 = strread(convertePataFloat{2},'%f','delimiter',' '); densidade = convertePataFloat2(3); if(isequal(nomeDensidade,convertePataFloat{1})) densidadeSelecionada=densidade; set(handles.p32,'String',densidade) end tline = fgetl(fid); end fclose(fid); achou=false; for x=1:size(dadosSelecionados) if(isequal(round(dadosSelecionados(x,1)),round(str2double(valorEnergia)))&& ~achou) achou=true; miu=dadosSelecionados(x,2)*densidadeSelecionada; set(handles.p31,'String',miu); end end if(mostarTabela) ColunaNomes = {'(Kev)' '(cm^2/g)' 'mu(en)/rho'}; set(handles.tabela2,'ColumnName',ColunaNomes); set(handles.tabela2,'Data',dadosSelecionados); set(handles.tabela2, 'ColumnWidth',{40},'units','Normalized'); end function p4_Callback (hObject, ~, handles) global caminhoDosArquivosDeTexto; contents = cellstr(get(hObject,'String')); aux= strcat( contents{get(hObject,'Value')},'.txt'); nomeDensidade=contents{get(hObject,'Value')}; txtSelect = strcat(caminhoDosArquivosDeTexto,'AttCoefficients\',aux); txtDensidade= strcat(caminhoDosArquivosDeTexto,'densidades.txt'); fid = fopen(txtSelect); tline = fgetl(fid); i=0; valorEnergia=get(handles.edit16,'String'); if(valorEnergia< 1 | isnan(str2double(valorEnergia))) uiwait(warndlg('Medidas não encontradas ou invalidas. Para continuar é preciso inserir medidas validas')); set(handles.aa,'BackgroundColor','red'); set(handles.bb,'BackgroundColor','red'); set(handles.hhh,'BackgroundColor','red'); set(handles.edit16,'BackgroundColor','red'); return end set(handles.p41,'BackgroundColor','green'); set(handles.p42,'BackgroundColor','green'); while ischar(tline) convertePataFloat = strread(tline,'%f','delimiter','K'); i=i+1; [tam, ~] =size(convertePataFloat); if(tam>3) dadosSelecionados(i,:)=convertePataFloat(2:4)'; else dadosSelecionados(i,:) = convertePataFloat'; end tline = fgetl(fid); end fclose(fid); mostarTabela= get(handles.energia,'Value'); dadosSelecionados(:,1)= dadosSelecionados(:,1).*1000; fid = fopen(txtDensidade); tline = fgetl(fid); i=0; while ischar(tline) convertePataFloat = strread(tline,'%s','delimiter','|'); convertePataFloat2 = strread(convertePataFloat{2},'%f','delimiter',' '); densidade = convertePataFloat2(3); if(isequal(nomeDensidade,convertePataFloat{1})) densidadeSelecionada=densidade; set(handles.p42,'String',densidade) end tline = fgetl(fid); end fclose(fid); achou=false; for x=1:size(dadosSelecionados) if(isequal(round(dadosSelecionados(x,1)),round(str2double(valorEnergia)))&& ~achou) achou=true; miu=dadosSelecionados(x,2)*densidadeSelecionada; set(handles.p41,'String',miu); end end if(mostarTabela) ColunaNomes = {'(Kev)' '(cm^2/g)' 'mu(en)/rho'}; set(handles.tabela2,'ColumnName',ColunaNomes); set(handles.tabela2,'Data',dadosSelecionados); set(handles.tabela2, 'ColumnWidth',{40},'units','Normalized'); end function aa_Callback (~, ~, handles ) global valorA; valorA = str2double(get(handles.aa, 'String')); function bb_Callback (~, ~, handles ) global valorB; persistent textString; currentString = get(handles.aa, 'String'); if (isempty(textString)|| isequal(textString,'0')) if ~isempty(currentString) textString = currentString; else uiwait(warndlg('Campo não preechido... Favor preencher com valor valido')); end return; end if(str2double(textString)~='NaN') valorB = str2double(currentString); else uiwait(warndlg('Valor não correspondente... tente novamente')); end function hhh_Callback (~, ~, handles ) global valorH; persistent textString; currentString = get(handles.hhh, 'String'); if (isempty(textString)|| isequal(textString,'0')) if ~isempty(currentString) textString = currentString; else uiwait(warndlg('Campo não preechido... Favor preencher com valor valido')); end return; end if(str2double(textString)~='NaN') valorH = str2double(currentString); else uiwait(warndlg('Valor não correspondente... tente novamente')); end function transfere_Callback (hObject, ~, handles) global caminhoDosArquivosDeTexto ... pastaSelecionada ... tipoSelecionado ... ; contents = cellstr(get(handles.listbox1,'String')); Arqselecionado2= contents{get(hObject,'Value')}; [Arqselecionado ,~] = strsplit(Arqselecionado2 , ' [','CollapseDelimiters',true); aux = char(strcat(pastaSelecionada,'\',Arqselecionado(1))); txtSelect=strcat(caminhoDosArquivosDeTexto,aux); todosTipos = cellstr(get(handles.paraOnde,'String')); tipoSelecionado2 = todosTipos{get(handles.paraOnde,'Value')}; txtSelect2 = char(strcat(caminhoDosArquivosDeTexto,'textData\',tipoSelecionado2)); movefile(char(txtSelect),char(txtSelect2),'f'); todosTipos = cellstr(get(handles.selecionaCaso,'String')); tipoSelecionado = todosTipos{get(handles.selecionaCaso,'Value')}; pastaSelecionada = strcat('\textData\',tipoSelecionado); files = dir(fullfile(caminhoDosArquivosDeTexto,pastaSelecionada,'*.txt')); set(handles.listbox1,'Value',1); todosTipos = {files.name}; todosDAtas = {files.date}; for x=1: length({files.name}) dadoss{x} = strcat(todosTipos{x},' [',todosDAtas{x},']'); end todosNomes=cell2struct(dadoss,'nomes',1); set(handles.listbox1,'String',{todosNomes.nomes}); function modificar_Callback (~, ~, handles ) % hObject handle to modificar (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global valorA ... valorB ... valorH ... volume ... Q ... altura ... TETA ... angCritico ... qCritico ... miuAR... miuPVC... miuAMO... miuPA... lxAR... lxPVC... lxAMOS... lxPA... Tar... Tpvc... Tamos... Tpa... tab5; valorA = str2double(get(handles.aa, 'String')) valorB = str2double(get(handles.bb, 'String')) valorH = str2double(get(handles.hhh,'String')) okaya = false; okayb = false; okayh = false; mostarJanela= get(handles.PlotarEmNovaJanela,'Value'); hold off if(isequal(num2str(valorA),'NaN')||isequal(valorA,0)) uiwait(warndlg('Medida [ a ] não computada ou igual a zero (0): Insira Medida valida')); elseif(~isempty(valorA)&& ~isequal(valorA,0) && ~isequal(num2str(valorA),'NaN')) okaya = true; valorA = str2double(get(handles.aa, 'String')); end if(isequal(num2str(valorB),'NaN')||isequal(valorB,0)) uiwait(warndlg('Medida [ b ] não computada ou igual a zero (0): Insira Medida valida')); elseif(~isempty(valorB)&& ~isequal(valorB,0) && ~isequal(num2str(valorB),'NaN')) valorB = str2double(get(handles.bb, 'String')); okayb = true; end if(isequal(num2str(valorH),'NaN')||isequal(valorH,0) ) uiwait(warndlg('Medida [ h ] não computada igual a zero (0): Insira Medida valida')) elseif(~isempty(valorH)&& ~isequal(valorH,0) && ~isequal(num2str(valorH),'NaN')) if (valorH > max(altura)) aux=strcat('Medida [ h ] não computada : Maior que a altura maxima [ ',num2str(max(altura)),' ] calculada automaticamente a partir do ang. theta') uiwait(warndlg(aux)); else valorH = str2double(get(handles.hhh, 'String')); okayh = true; end end if(okaya && okayb && okayh) uiwait(helpdlg('Medidas alteradas com sucesso')) end volume = (valorA*valorB).*tan(TETA(:,1).*(pi()/180)); alturaCritica = str2double(get(handles.hhh,'String')) okay = false; count =0; % for x=1:size(Q) % x,1) = (valorA/2)*tan(Q(x,1)*(pi()/180)) % end % altura = rad2deg(atan(valorA/(2*valorH))) % countxxx=1:Q(altura) % aaaa = Q(round(altura)) for x=1:length(Q) if(altura< TETA(x,1) && ~okay) angCritico =count qCritico = Q(count,1) count okay = true; end count = count+1; end set(handles.thetaTextedi,'String',TETA(angCritico,1)) [miuAR,miuPVC,miuAMO,miuPA,lxAR,lxPVC,lxAMOS,lxPA,Tar,Tpvc,Tamos,Tpa] = getTodososvalores(handles,Q); CompX = str2double(get(handles.bb,'String')); % resto = 2.1 - CompX; % CompX = CompX + resto; CompY = str2double(get(handles.aa,'String')); CompZ = str2double(get(handles.hhh,'String')); if(mostarJanela>0) hFig = figure; else ax = axes('Parent', tab5); cla reset ax.BoxStyle = 'full'; ax.XAxisLocation = 'top'; ax.Position = [0.1 0.4 1.0 0.6]; end X = [ 0 ; CompX ; CompX ; 0 ; 0 ]; Y = [ 0 ; 0 ; CompY ; CompY ; 0 ]; Z = [ 0 ; 0 ; 0 ; 0 ; 0 ]; if(mostarJanela>0) tabplot(' 1 ',hFig,'top'); grid on end hold on; plot3(X-CompX/2,Y-0.5*CompY,Z); plot3(X-CompX/2,Y-0.5*CompY,Z+CompZ,'LineWidth',2.5); set(gca,'View',[-50,33]); for k=1:length(X)-1 plot3([X(k)-CompX/2;X(k)-CompX/2],[Y(k)-0.5*CompY;Y(k)-0.5*CompY],[0;CompZ],'LineWidth',2.5); end % scatter3(CompX*2.4*35.*rand(300,1)/100-CompX/2,CompX*2.4*35.*rand(300,1)/100- 1.5*CompY,35.*rand(300,1)/100-0.125,'red'); axis([-max(CompX)-0.3 max(CompX)+0.3 -max(CompX)-0.3 max(CompX)+0.3 0 1]); if(mostarJanela>0) tabplot(' 2 ',hFig,'top'); axis([-max(CompX)-0.3 max(CompX)+0.3 -max(CompX)-0.3 max(CompX)+0.3 0 1]); grid on end grid on hold on nPhi = 256; nRho = 32; [X, Y, Z] = cylinder([linspace(0, CompX, nRho) CompX+0.1.*ones(1, nRho)], nPhi); Z(1:nRho,:) = 0; Z(nRho+1:end,:) = CompZ; surf(X,Y,Z, 'FaceColor', [0.97 0.97 0.97], 'FaceLighting', 'phong','EdgeColor', 'none'); hold on [X,Y,Z] = cylinder(linspace(0, CompX, nRho), nPhi); Z(:,:) = CompZ -0.03; surf(X, Y, Z, 'FaceColor', [0 0.5 1], 'FaceLighting', 'phong', 'FaceAlpha',0.5, 'EdgeColor', 'none'); camlight; hold off if(mostarJanela>0) tabplot(' 3 ',hFig,'top'); grid on axis([-max(CompX)-0.3 max(CompX)+0.3 -max(CompX)-0.3 max(CompX)+0.3 0 1]); hold off hold on; X = [ 0 ; CompX ; CompX ; 0 ; 0 ]; Y = [ 0 ; 0 ; CompY ; CompY ; 0 ]; Z = [ 0 ; 0 ; 0 ; 0 ; 0 ]; plot3(X-CompX/2,Y-0.5*CompY,Z); plot3(X-CompX/2,Y-0.5*CompY,Z+CompZ,'LineWidth',2.5); set(gca,'View',[-28,35]); for k=1:length(X)-1 plot3([X(k)-CompX/2;X(k)-CompX/2],[Y(k)-0.5*CompY;Y(k)-0.5*CompY],[0;CompZ],'LineWidth',2.5); end scatter3(7*35.*rand(300,1)/100-CompX/2,7*35.*rand(300,1)/100-3*CompY,35.*rand(300,1)/100,'g'); nPhi = 256; nRho = 32; [X, Y, Z] = cylinder([linspace(0, CompX, nRho) CompX+0.1.*ones(1, nRho)], nPhi); Z(1:nRho,:) = 0; Z(nRho+1:end,:) = CompZ; surf(X,Y,Z, 'FaceColor', [0.97 0.97 0.97], 'FaceLighting', 'phong','EdgeColor', 'none'); hold on [X,Y,Z] = cylinder(linspace(0, CompX, nRho), nPhi); Z(:,:) = CompZ -0.03; surf(X, Y, Z, 'FaceColor', [0 0.5 1], 'FaceLighting', 'phong', 'FaceAlpha',0.5, 'EdgeColor', 'none'); camlight; hold off end function listbox2_Callback (hObject, ~, handles) global pAselecionado ... Arqselecionado2 ... PA_04_VZ ... PA_04_PLS ... PA_03_VZ_REP ... PA_03_PLS ... PA_02_VZ ... PA_02_PLS ... PA_01_VZ ... PA_01_PLS_1MIN ... PA_01_H2O_PLS_2MIN ... PA_01_H2O_PLS_1MIN ... pA01_H20_PLS ... pA02_H20_PLS ... pA03_H20_PLS ... pA04_H20_PLS ... pA01_H20_PLS_2MIN ... pA02_H20_PLS_2MIN ... pA03_H20_PLS_2MIN ... pA04_H20_PLS_2MIN ... TETA ... tab4 ... tabgp... IAR... Q; hold off tabgp.SelectedTab = tab4; contents = cellstr(get(hObject,'String')); Arqselecionado2= contents{get(hObject,'Value')}; opc1 ='Intensidade do Porta Amostra Vazio'; opc2 ='Intensidade do Filme'; opc3 ='Intensidade da H20 1Min'; opc4 ='Intensidade do Ar'; mostarJanela= get(handles.PlotarEmNovaJanela,'Value'); axes('Parent',tab4); if(strcmp(Arqselecionado2,opc1)) set(handles.text14,'String',opc1); subplot(4,1,1) cla reset titlee=strcat(opc1,' - ',pAselecionado); if(strcmp(pAselecionado,'PA01')) dataTab = [TETA Q PA_01_VZ]; set(handles.tabela2,'Data',dataTab); plotGraficoFacil(Q,PA_01_VZ,' ',titlee); axis([min(Q(:)) max(Q(:)) min(PA_01_VZ) max(PA_01_VZ)]); if(mostarJanela>0) figure plotGraficoFacil(Q,PA_01_VZ,'Intensidades obtidas para PA01 Vazio','PA01 Vazio'); end end if(strcmp(pAselecionado,'PA02')) dataTab = [TETA Q PA_02_VZ]; set(handles.tabela2,'Data',dataTab); plotGraficoFacil(Q,PA_02_VZ,' ',titlee); axis([min(Q(:)) max(Q(:)) min(PA_02_VZ) max(PA_02_VZ)]); if(mostarJanela>0) figure plotGraficoFacil(Q,PA_02_VZ,'Intensidades obtidas para PA02 Vazio','PA02 Vazio'); end end if(strcmp(pAselecionado,'PA03')) dataTab = [TETA Q PA_03_VZ_REP]; set(handles.tabela2,'Data',dataTab); plotGraficoFacil(Q,PA_03_VZ_REP,' ',titlee); axis([min(Q(:)) max(Q(:)) min(PA_03_VZ_REP) max(PA_03_VZ_REP)]); if(mostarJanela>0) figure plotGraficoFacil(Q,PA_03_VZ_REP,'Intensidades obtidas para PA03 Vazio','PA03 Vazio'); end end if(strcmp(pAselecionado,'PA04')) dataTab = [TETA Q PA_04_VZ]; set(handles.tabela2,'Data',dataTab); plotGraficoFacil(Q,PA_04_VZ,' ',titlee); axis([min(Q(:)) max(Q(:)) min(PA_04_VZ) max(PA_04_VZ)]); if(mostarJanela>0) figure plotGraficoFacil(Q,PA_04_VZ,'Intensidades obtidas para PA04 Vazio','PA04 Vazio'); end end end if(strcmp(Arqselecionado2,opc2)) subplot(4,1,2) cla reset titlee=strcat(opc2,' - ',pAselecionado); set(handles.text14,'String',opc2); if(strcmp(pAselecionado,'PA01')) dataTab = [TETA Q PA_01_PLS_1MIN]; set(handles.tabela2,'Data',dataTab); plotGraficoFacil(Q,PA_01_PLS_1MIN,' ',titlee); axis([min(Q(:)) max(Q(:)) min(PA_01_PLS_1MIN) max(PA_01_PLS_1MIN)]); if(mostarJanela>0) figure plotGraficoFacil(Q,PA_01_PLS_1MIN,'Intensidades obtidas para PA01 com Plástico','PA01 Plástico'); end end if(strcmp(pAselecionado,'PA02')) dataTab = [TETA Q PA_02_PLS]; set(handles.tabela2,'Data',dataTab); plotGraficoFacil(Q,PA_02_PLS,' ',titlee); axis([min(Q(:)) max(Q(:)) min(PA_02_PLS) max(PA_02_PLS)]); if(mostarJanela>0) figure plotGraficoFacil(Q,PA_02_PLS,'Intensidades obtidas para PA02 com Plástico','PA02 Plástico'); end end if(strcmp(pAselecionado,'PA03')) dataTab = [TETA Q PA_03_PLS]; set(handles.tabela2,'Data',dataTab); plotGraficoFacil(Q,PA_03_PLS,' ',titlee); axis([min(Q(:)) max(Q(:)) min(PA_03_PLS) max(PA_03_PLS)]); if(mostarJanela>0) figure plotGraficoFacil(Q,PA_03_PLS,'Intensidades obtidas para PA03 com Plástico','PA03 Plástico'); end end if(strcmp(pAselecionado,'PA04')) dataTab = [TETA Q PA_04_PLS]; set(handles.tabela2,'Data',dataTab); plotGraficoFacil(Q,PA_04_PLS,' ',titlee); axis([min(Q(:)) max(Q(:)) min(PA_04_PLS) max(PA_04_PLS)]); if(mostarJanela>0) figure plotGraficoFacil(Q,PA_04_PLS,'Intensidades obtidas para PA04 com Plástico','PA04 Plástico'); end end end if(strcmp(Arqselecionado2,opc3)) subplot(4,1,3) cla reset titlee=strcat(opc3,' - ',pAselecionado); set(handles.text14,'String',opc3); dataTab = [TETA Q PA_01_H2O_PLS_1MIN]; set(handles.tabela2,'Data',dataTab); plotGraficoFacil(Q,PA_01_H2O_PLS_1MIN,' ',titlee); axis([min(Q(:)) max(Q(:)) min(PA_01_H2O_PLS_1MIN) max(PA_01_H2O_PLS_1MIN)]); if(mostarJanela>0) figure plotGraficoFacil(Q,PA_01_H2O_PLS_1MIN,'Intensidades obtidas para PA01 com H20 1MIN','PA01 H20 1MIN'); end end if(strcmp(Arqselecionado2,opc4)) subplot(4,1,4) cla reset titlee=strcat(opc4); set(handles.text14,'String',opc4); dataTab = [TETA Q IAR]; set(handles.tabela2,'Data',dataTab); plotGraficoFacil(Q,IAR,' ',titlee); % axis([min(Q(:)) max(Q(:)) min(IAR) max(IAR)]); axis tight if(mostarJanela>0) figure plotGraficoFacil(Q,IAR,'Intensidades obtidas para PA01 com H20 2MIN','PA01 H20 2MIN'); end end function miu_Callback (~, ~, ~) function rho_Callback (~, ~, ~) function paraOnde_Callback (~, ~, ~) function console_Callback (~, ~, ~) function T4_Callback (~, ~, ~) function T1_Callback (~, ~, ~) function T3_Callback (~, ~, ~) function T2_Callback (~, ~, ~) function edit14_Callback (~, ~, ~) function edit15_Callback (~, ~, ~) function edit16_Callback (~, ~, ~) function PlotarEmNovaJanela_Callback(~, ~, ~) %############################################################################## %############################################################################## %############################################################################## %############################################################################## function PlotarEmNovaJanela_CreateFcn(~, ~, ~) function classifica1_CreateFcn (~, ~, ~) function console_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function slider3_CreateFcn (hObject, ~, ~) if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function p1_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p2_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p3_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p4_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p11_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p12_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p13_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p21_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p22_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p23_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p31_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p32_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p33_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p41_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p42_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p43_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function p11_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p11,'BackgroundColor','g'); else set(handles.p11,'BackgroundColor','r'); end function p12_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p12,'BackgroundColor','g'); else set(handles.p12,'BackgroundColor','r'); end function p13_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p13,'BackgroundColor','g'); else set(handles.p13,'BackgroundColor','r'); end function p21_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p21,'BackgroundColor','g'); else set(handles.p21,'BackgroundColor','r'); end function p22_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p22,'BackgroundColor','g'); else set(handles.p22,'BackgroundColor','r'); end function p23_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p23,'BackgroundColor','g'); else set(handles.p23,'BackgroundColor','r'); end function p31_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p31,'BackgroundColor','g'); else set(handles.p31,'BackgroundColor','r'); end function p32_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p32,'BackgroundColor','g'); else set(handles.p32,'BackgroundColor','r'); end function p33_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p33,'BackgroundColor','g'); else set(handles.p33,'BackgroundColor','r'); end function p41_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p41,'BackgroundColor','g'); else set(handles.p41,'BackgroundColor','r'); end function p42_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p42,'BackgroundColor','g'); else set(handles.p42,'BackgroundColor','r'); end function p43_Callback(hObject, ~, handles) if(~isnan(str2double(get(hObject,'String')))) set(handles.p43,'BackgroundColor','g'); else set(handles.p43,'BackgroundColor','r') end function energia_Callback(~, ~, ~) function aa_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function hhh_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function bb_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function listbox2_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function paraOnde_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function selecionaCaso_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function popupmenu2_CreateFcn (hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function uipanel7_CreateFcn(~, ~, ~) global tabgp ... f ... tab1 ... tab2 ... tab3 ... tab4 ... tab5 ... tab3_2... tab3_3... tab3_4... ; f = gcf; tabgp = uitabgroup(f,'Position',[0.58 .01 .4 0.90]); tab1 = uitab(tabgp,'Title','Análise da amostra'); tab2 = uitab(tabgp,'Title','Pós - Análise'); tab3 = uitab(tabgp,'Title','Pós - Análise II'); tab3_3 = uitab(tabgp,'Title','Perfis da agua'); tab3_4 = uitab(tabgp,'Title','Perfis Tecidos'); tab4 = uitab(tabgp,'Title','Dados iniciais '); tab5 = uitab(tabgp,'Title','PA'); tab3_2 = uitab(tabgp,'Title','Pós - Análise III'); assignin('base','tab3_2',tab3_2) uicontrol(tab3,'Style', 'pushbutton', 'String', 'Iterar','Callback', @iterar); uicontrol(tab5,'Style', 'pushbutton', 'String', 'Anima' ,'Callback', @anima ); function iterar(ax,bx) global Q ... plotFinal ... tab3_2 ... tabgp ... mostarJanela ... TETA; tabgp.SelectedTab = tab3_2; cla reset x = TETA; hold off if(mostarJanela>0) figure(77) else axes('Parent', tab3_2) end plotCorrigidoAux1 = plotFinal.*(-1); plotCorrigidoAux2 = plotFinal; % tam = length(plotCorrigidoAux2 ); [pks,locs] = findpeaks(plotCorrigidoAux1,Q,'MinPeakDistance',2); if(plotCorrigidoAux2(1)> plotCorrigidoAux2(5)) plotCorrigidoAux2(1:locs(3),1)= (-1).*pks(1); end % % subplot(3,1,1) % plot(Q,plotCorrigidoAux2) subplot(3,1,1) Pos = x; Hgt = plotCorrigidoAux2; cla reset okay=false; cont=0; entrada=0; inicio = 1; PeakSig=plotCorrigidoAux2; % okay=400000; % % % Hgt = plotCorrigidoAux2; inicio = 50; okay2=1E-26; for yy=1:2 cla reset Wdt = Q/inicio; inicio = inicio*10; for n = 1:length(x) Gauss(n,:) = Hgt(n)*exp(-((x - Pos(n))/Wdt(n)).^2); PeakSig=sum(Gauss); % plot(Q(1:n),PeakSig(1:n),'-.') if(okay==false & cont >2) plot(Q,Gauss(n,:)) axis tight hold on okay=true; cont=0; else okay=false; cont=cont+1; end pause(0.00005) end okay2=max(sum(Gauss)); % % end hold all plot(Q,PeakSig,'-.'); % % grid on axis tight entrada=0; x = Q; %FIANAL DO PRIMEIRO SUBPLOT for i=1:2 if i ==1 fator = 100 else fator = 1000; end Wdt = x/fator; subplot(3,1,2) if(i<2) cla reset; end Pos = x; Hgt = plotCorrigidoAux2; okay=false; cont=0; for n = 1:length(x) Gauss(n,:) = Hgt(n)*exp(-((x - Pos(n))/Wdt(n)).^2); end PeakSig = sum(Gauss); hold all plot(x,Gauss,'.-',x,PeakSig,'-'); axis tight % end hold on [psor,lsor] = findpeaks(PeakSig,x,'SortStr','descend'); if(i==1) PKS1=lsor; [k, d] = dsearchn(lsor(1),Q(:,1)); pico2 = min(d); [i,j]=ind2sub(size(d), find(d==pico2)); pk2=Q(i,1); x2=Q(i,1); end hold off grid on subplot(3,1,3) % if(entrada==0 ) cla reset entrada=1; end % axis([min(Q(:)) max(Q(:)) min(plotCorrigido) max(plotCorrigido)]); findpeaks(PeakSig,x,'MinPeakDistance',5,'WidthReference','halfheight'); end pico1 = max(plotCorrigidoAux2); [i,j]=ind2sub(size(plotCorrigidoAux2), find(plotCorrigidoAux2==pico1)); pk1=Q(i,1); x1=Q(i,1); y1=max(plotCorrigidoAux2); hold all [k, d] = dsearchn(pk1,PKS1); if( d(1) < 3) pk2 = PKS1(2); x2 = pk2; end % index = find(Q==pk2); y2 = plotCorrigidoAux2(index); % plot((x1).*ones(length(x),1),plotCorrigidoAux2,'-.','LineWidth',2); plot( x1,y1+1E-25,'v',... 'LineWidth',1,... 'MarkerEdgeColor','k',... 'MarkerFaceColor',[.49 1 .63],... 'MarkerSize',10) plot((x2).*ones(length(x),1),plotCorrigidoAux2,'-.','LineWidth',2); plot( x2,y2+1E-25,'v',... 'LineWidth',1,... 'MarkerEdgeColor','k',... 'MarkerFaceColor',[.49 1 .63],... 'MarkerSize',10) str1 = ['[ ',num2str(x1),' , ',num2str(y1),' ]']; str2 = ['[ ',num2str(x2),' , ',num2str(y2),' ]']; text(x1+2,y1+1E-25,str1,'HorizontalAlignment','right'); text(x2,0,str2,'VerticalAlignment','baseline','HorizontalAlignment','left'); xlim([min(Q) max(Q)]) ylim([0 y1+2E-25]) % axis([min(Q(:)) max(Q(:)) min(plotCorrigido) max(plotCorrigido)+5E-25]) % hold off function anima (~,~) global tab5 ... okay=0; if(okay==1) fa=0.2; SPHERE_RES = 50; % resolution for your spheres SPHERE_RAD = fa; % radius of spheres v = randn(200,3); v(:,1)=v(:,1)*0.4; v(:,2)=v(:,2)*0.5; v(:,3)=v(:,3)*0.05; % Make base sphere data [xb, yb, zb] = sphere(SPHERE_RES); % % h = 0.5*[xb, yb, zb] % Make a figure xb = 8*30.*xb/100; yb = 6*30.*yb/100; zb = zb; hold on; % Plot spheres for i=1:1:length(v) if(i<150) surf(SPHERE_RAD*xb+v(i,1), SPHERE_RAD*yb+v(i,2), SPHERE_RAD*zb+v(i,3), 'facecolor', 'y', 'edgealpha', 0); % surf(SPHERE_RAD*xb+v(i,1)-0.21, SPHERE_RAD*yb+v(i,2)-0.21, SPHERE_RAD*zb+v(i,3), 'facecolor', 'y', 'edgealpha', 0); % surf(SPHERE_RAD*xb+v(i,1)+0.21, SPHERE_RAD*yb+v(i,2)+0.21, SPHERE_RAD*zb+v(i,3), 'facecolor', 'y', 'edgealpha', 0); else surf(SPHERE_RAD*xb+v(i,1), SPHERE_RAD*yb+v(i,2), SPHERE_RAD*zb+v(i,3), 'facecolor', 'black', 'edgealpha', 0); end end light; lighting gouraud; end function T3_CreateFcn(hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function T1_CreateFcn(hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function T4_CreateFcn(hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function T2_CreateFcn(hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit14_CreateFcn(hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit15_CreateFcn(hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit16_CreateFcn(hObject, ~, ~) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function thetaText_Callback (~, ~, ~) function qtext_Callback (~, ~, ~) function transfere_CreateFcn(~, ~, ~) function nda1_CreateFcn (~, ~, ~) function nda2_CreateFcn (~, ~, ~) function nda3_CreateFcn (~, ~, ~) function text12_CreateFcn (~, ~, ~) function setOFFeddits (handles) set(handles.edit16,'String',8.04); set(handles.p1,'Visible','off'); set(handles.p2,'Visible','off'); set(handles.p3,'Visible','off'); set(handles.p4,'Visible','off'); set(handles.pp1,'Visible','on'); set(handles.pp2,'Visible','on'); set(handles.pp3,'Visible','on'); set(handles.pp4,'Visible','on'); set(handles.p12,'String',''); set(handles.p22,'String',''); set(handles.p32,'String',''); set(handles.p42,'String',''); set(handles.p11,'String',''); set(handles.p21,'String',''); set(handles.p31,'String',''); set(handles.p41,'String',''); set(handles.edit16,'BackgroundColor',[0.83 0.82 0.78]); set(handles.p12,'BackgroundColor' ,[0.83 0.82 0.78]); set(handles.p22,'BackgroundColor' ,[0.83 0.82 0.78]); set(handles.p32,'BackgroundColor' ,[0.83 0.82 0.78]); set(handles.p42,'BackgroundColor' ,[0.83 0.82 0.78]); set(handles.p11,'BackgroundColor' ,[0.83 0.82 0.78]); set(handles.p21,'BackgroundColor' ,[0.83 0.82 0.78]); set(handles.p31,'BackgroundColor' ,[0.83 0.82 0.78]); set(handles.p41,'BackgroundColor' ,[0.83 0.82 0.78]); function setONeddits (handles) set(handles.p1,'Visible','on'); set(handles.p2,'Visible','on'); set(handles.p3,'Visible','on'); set(handles.p4,'Visible','on'); set(handles.p4,'Visible','on'); set(handles.pp1,'Visible','off'); set(handles.pp2,'Visible','off'); set(handles.pp3,'Visible','off'); set(handles.pp4,'Visible','off'); set(handles.edit16,'String',8,'BackgroundColor','white'); set(handles.p12,'String','','BackgroundColor','white'); set(handles.p22,'String','','BackgroundColor','white'); set(handles.p32,'String','','BackgroundColor','white'); set(handles.p42,'String','','BackgroundColor','white'); set(handles.p11,'String','','BackgroundColor','white'); set(handles.p21,'String','','BackgroundColor','white'); set(handles.p31,'String','','BackgroundColor','white'); set(handles.p41,'String','','BackgroundColor','white'); set(handles.p13,'String','','BackgroundColor','white'); set(handles.p23,'String','','BackgroundColor','white'); set(handles.p33,'String','','BackgroundColor','white'); set(handles.p43,'String','','BackgroundColor','white'); set(handles.aa, 'String','','BackgroundColor','white'); set(handles.bb, 'String','','BackgroundColor','white'); set(handles.hhh,'String','','BackgroundColor','white'); function atualiza(handles) global caminhoDosArquivosDeTexto; nomeDensidade = {'Air, Dry (near sea level)' 'Polyvinyl Chloride' 'Water, Liquid' 'Polylactic acid'}; cont =1; valorEnergia = str2double(get(handles.edit16,'String')); for x=1:4 aux = strcat( nomeDensidade{x},'.txt'); txtSelect = strcat(caminhoDosArquivosDeTexto,'AttCoefficients\',aux); txtDensidade = strcat(caminhoDosArquivosDeTexto,'densidades.txt'); fid = fopen(txtSelect); tline = fgetl(fid); j=0; while ischar(tline) convertePataFloat = strread(tline,'%f','delimiter','K'); j=j+1; [tam, ~] =size(convertePataFloat); if(tam>3) dadosSelecionados(j,:) = convertePataFloat(2:4)'; else dadosSelecionados(j,:) = convertePataFloat'; end tline = fgetl(fid); end fclose(fid); fid = fopen(txtDensidade); dadosSelecionados(:,1)= dadosSelecionados(:,1).*1000; tline = fgetl(fid); while ischar(tline) convertePataFloat = textscan(tline,'%s %s','delimiter','|'); convertePataFloat2 = textscan(char(convertePataFloat{2}),'%f %f %f','delimiter','//'); densidade = convertePataFloat2{3}; if(isequal(nomeDensidade{x},char(convertePataFloat{1})) && cont < 5); if(cont==1) densidadeSelecionada=densidade; set(handles.p12,'String',densidade); set(handles.pp1,'String',nomeDensidade{x}); end if(cont==2) densidadeSelecionada=densidade; set(handles.p22,'String',densidade); set(handles.pp2,'String',nomeDensidade{x}); end if(cont==3) densidadeSelecionada=densidade; set(handles.p32,'String',densidade); set(handles.pp3,'String',nomeDensidade{x}); end if(cont==4) densidadeSelecionada=densidade; set(handles.p42,'String',densidade); set(handles.pp4,'String',nomeDensidade{x}); end end tline = fgetl(fid); end fclose(fid); for i=1:size(dadosSelecionados) if(isequal(round(dadosSelecionados(i,1)),round(valorEnergia)) && cont < 5) if(cont==1) miu=dadosSelecionados(i,2)*densidadeSelecionada; set(handles.p11,'String',miu); end if(cont==2) miu=dadosSelecionados(i,2)*densidadeSelecionada; set(handles.p21,'String',miu); end if(cont==3) miu=dadosSelecionados(i,2)*densidadeSelecionada; set(handles.p31,'String',miu); end if(cont==4) miu=dadosSelecionados(i,2)*densidadeSelecionada; set(handles.p41,'String',miu); end end end cont = cont+1; end set(handles.p13,'String',20.00); set(handles.p23,'String',0.15E-3); set(handles.p33,'String',0.38); set(handles.p43,'String',0.2); set(handles.aa,'String',0.35); set(handles.bb ,'String',1.9); set(handles.hhh,'String',0.4); set(handles.p13,'BackgroundColor',[0.83 0.82 0.78]); set(handles.p23,'BackgroundColor',[0.83 0.82 0.78]); set(handles.p33,'BackgroundColor',[0.83 0.82 0.78]); set(handles.p43,'BackgroundColor',[0.83 0.82 0.78]); set(handles.aa,'BackgroundColor' ,[0.83 0.82 0.78]); set(handles.bb,'BackgroundColor' ,[0.83 0.82 0.78]); set(handles.hhh,'BackgroundColor',[0.83 0.82 0.78]); %############################################################################## % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) global newData ... caminhoDosArquivosDeTexto ... m; % d = dialog('Position',[400 400 250 150],'Name','Fechando ... '); % txt = uicontrol('Parent',d,... % 'Style','text',... % 'Position',[20 80 210 40],... % 'String','Limpando buffers, auguarde o fechar do programa ...'); % % hostname = char( getHostName( java.net.InetAddress.getLocalHost ) ); % newData = [ {strcat('hostname >> [ ',hostname,' ]')}; get(handles.console,'Data')]; % set(handles.console,'Data',newData); % ip = char( getHostAddress( java.net.InetAddress.getLocalHost ) ); % newData = [ {strcat('IP >> [ ',ip,' ]')} ; get(handles.console,'Data')]; % set(handles.console,'Data',newData); % user = getenv('UserName'); % newData = [ {strcat('user >> [ ',user,' ]')} ;get(handles.console,'Data')]; % set(handles.console,'Data',newData); % % new_data = strrep(datestr(datetime('now')), ':', '.'); % Ta = strcat('logdata [',new_data,'].txt'); % writetable(cell2table(newData),Ta); % % pause(0.05) % caminhoLog =strcat(caminhoDosArquivosDeTexto,Ta); % % try % sendmail(m,'MATLAB code utilization','O codigo do seu programa foi usado. Log em anexo:',{caminhoLog}); % % catch exception % close (d) % delete(hObject); % % end % close (d) % delete(hObject); function negv_Callback(hObject, eventdata, handles) % --- Executes on button press in Abbas. function Abbas_Callback(hObject, eventdata, handles) % hObject handle to Abbas (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Abbas global tabgp; espandis = get(hObject,'Value'); if(espandis <1) set(tabgp,'Position',[0.58 .01 .4 0.90]); else set(tabgp,'Position',[0.001 .03 .99 0.90]); end function detm_Callback(hObject, eventdata, handles) function smoothPlot_Callback(hObject, eventdata, handles) % hObject handle to smoothPlot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of smoothPlot function iterarAte_Callback(hObject, eventdata, handles) % hObject handle to iterarAte (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of iterarAte as text % str2double(get(hObject,'String')) returns contents of iterarAte as a double % --- Executes during object creation, after setting all properties. function iterarAte_CreateFcn(hObject, eventdata, handles) % hObject handle to iterarAte (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function aAte_Callback(hObject, eventdata, handles) % hObject handle to aAte (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of aAte as text % str2double(get(hObject,'String')) returns contents of aAte as a double % --- Executes during object creation, after setting all properties. function aAte_CreateFcn(hObject, eventdata, handles) % hObject handle to aAte (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton24. function pushbutton24_Callback(hObject, eventdata, handles) % hObject handle to pushbutton24 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton25. function pushbutton25_Callback(hObject, eventdata, handles) % hObject handle to pushbutton25 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in altr. function altr_Callback(hObject, eventdata, handles) % hObject handle to altr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of altr usar=get(hObject,'Value'); if(usar>0) set(handles.aAte,'String',100) else set(handles.aAte,'String',50) end function normalr_Callback(hObject, eventdata, handles) % hObject handle to normalr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of normalr as text % str2double(get(hObject,'String')) returns contents of normalr as a double % --- Executes during object creation, after setting all properties. function normalr_CreateFcn(hObject, eventdata, handles) % hObject handle to normalr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end
github
lob-epfl/sofitool-master
sofiCumulants.m
.m
sofitool-master/GUI/codeSofi/SOFI/sofiCumulants.m
7,034
utf_8
29b26a76924276e6cd03cafc2c759001
%[sofi,grid]=sofiCumulants(stack,first,frames,region,orders,gpu) %--------------------------------------------------------------- % %Raw cross-cumulant images from image stack. % %Inputs: % stack Image stack % or TIFF file name % first First image index {1} % frames Number of images {all} % region Image region [pixel] {{[1 width],[1 height]}} % orders Cross-cumulant orders {1:4} % gpu Force or forbid CUDA usage {auto} % %Outputs: % sofi Raw cross-cumulants % grid Partitions and pixels %Copyright ? 2012 Marcel Leutenegger et al, ?cole Polytechnique F?d?rale de Lausanne, %Laboratoire d'Optique Biom?dicale, BM 5.142, Station 17, 1015 Lausanne, Switzerland. % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>. % function [sofi,grid]=sofiCumulants(stack,first,frames,region,orders,gpu) file=ischar(stack); if file tif=Tiff(stack,'r'); X=tif.getTag('ImageLength'); % reading tiff info(s) image dimensions Y=tif.getTag('ImageWidth'); else tif.close=[]; tif.lastDirectory=false; tif.nextDirectory=[]; [X,Y,F]=size(stack); end try fig=statusbar('Initialization...'); if nargin < 2 || isempty(first) first=1; end if nargin < 3 || isempty(frames) % number of images if file try tif.setDirectory(65536); % supported frames catch end frames=tif.currentDirectory; else frames=F; end frames=frames + 1-first; end if file tif.setDirectory(first); end roi=nargin > 3 && ~isempty(region); % region defined? if roi x=max(1,min(region{1},X)); y=max(1,min(region{2},Y)); x=int16(x(1):x(2)); y=int16(y(1):y(2)); roi=numel(x) < X || numel(y) < Y; X=numel(x); Y=numel(y); end if any([X Y frames] < 4) error('sofi:dimensions','The image stack is too small.'); end if nargin < 5 || isempty(orders) orders=1:4; end fig=statusbar(1/3,fig); grid=sofiGrids(orders,file); % partitions and pixels if ~file if roi stack=stack(x,y,first:first+frames-1); elseif frames < F stack=stack(:,:,first:first+frames-1); end avg=sum(stack(:,:,:),3)/frames; % average for zero means end fig=statusbar(2/3,fig); p=grid(1).pixels; % corner pixel coordinates m=cell(size(p)); n=cell(size(p)); F=int16(1:size(p,1)); for f=F % indices limited to image size m{f}=int16(min(X,1+p(f,1):p(f,1)+X)); n{f}=int16(min(Y,1+p(f,2):p(f,2)+Y)); end t=grid(1).terms; % terms pixel coordinates P=int16(1:numel(t)); facts=cell(size(m)); % factors storage if nargin < 6 || isempty(gpu) gpu=X*Y >= 65536 && cudaAvailable; end gpus={@gpu1 @gpu2 @gpu3 @gpu4 @gpu5 @gpu6 @gpu7 @gpu8}; if gpu if ~file avg=gpuArray(avg); % store arrays on GPU end for f=F m{f}=gpuArray(int32(m{f})); % use native data type n{f}=gpuArray(int32(n{f})); end terms={gpuArray(0)}; else terms={0}; end terms=terms(ones(size(t))); % terms storage fig=statusbar('Partial products...',fig); for frame=1:frames if file img=tif.read; % read image if roi img=img(x,y); end else img=stack(:,:,frame); end if gpu img=gpuArray(img); end img=double(img); if ~file img=img - avg; end for f=F facts{f}=img(m{f},n{f}); % all factors end if gpu for p=P terms{p}=arrayfun(gpus{numel(t{p})},terms{p},facts{t{p}}); end else for p=P terms{p}=feval(gpus{numel(t{p})},terms{p},facts{t{p}}); end end fig=statusbar(frame/frames,fig); if isempty(fig) || tif.lastDirectory break; end tif.nextDirectory; end catch msg tif.close; delete(fig); rethrow(msg); end if file tif.close; sofi=cumulants(grid,orders,frame,terms,fig,gpu); elseif frame < frames error('sofi:abort','User abort resulted in non-zero means.'); else sofi=cumulants(grid,orders(orders > 1),frame,terms,fig,gpu); if any(orders == 1) sofi{1}=gather(avg(2:end-2,2:end-2)); end end %Check for CUDA-1.3-capable or newer graphics card. % function gpu=cudaAvailable try gpu=parallel.gpu.GPUDevice.current(); gpu=gpu.DeviceSupported; catch msg gpu=false; end %Cross-cumulant images from partial product terms. % % grid Partitions and pixels % orders Cumulant orders % frames Number of images % terms Partial products % fig Statusbar handle % % sofi Cross-cumulant images % function sofi=cumulants(grid,orders,frames,terms,fig,gpu) fig=statusbar('Cross cumulants...',fig); fact=cumprod([1 -1:-1:1-max(orders(:))]/frames); sofi=cell(size(grid)); % cell array of empty matrices (size(grid)) s=size(terms{1}) - 3; % first order size x=cell(4,1); y=cell(4,1); for f=1:4 x{f}=int16(f:f+s(1)-1); % all shift indices y{f}=int16(f:f+s(2)-1); end if gpu fact=gpuArray(fact); end cur=0; num=sum(cellfun(@numel,{grid(orders).parts})) + numel(orders); for order=orders(:).' pixels={0}; pixels=pixels(ones(order)); % cumulant groups P=int16(1:numel(pixels)); parts=grid(order).parts; shifts=grid(order).shifts; for p=1:numel(parts) dx=x(shifts{p}(:,:,1)); % shift indices dy=y(shifts{p}(:,:,2)); part=parts{p}; % term indices n=size(part,2); F=int16(1:n); for m=P term=fact(n); % partition for n=F term=term.*terms{part(m,n)}(dx{m,n},dy{m,n}); end pixels{m}=pixels{m} + term; % cumulant end cur=cur + 1; fig=statusbar(cur/num,fig); if isempty(fig) return; end end term=zeros(s*order); % full image for m=1:order for n=1:order term(m:order:end,n:order:end)=gather(pixels{m,n}); end end sofi{order}=term(1:1+end-order,1:1+end-order); cur=cur + 1; fig=statusbar(cur/num,fig); if isempty(fig) return; end end delete(fig);
github
lob-epfl/sofitool-master
nvcc.m
.m
sofitool-master/GUI/codeSofi/SOFI/private/nvcc.m
7,590
utf_8
d1942566971b573b025b45d49e8d4945
function nvcc(varargin) % This function NVCC is a wraper for the NVIDIA Cuda compiler NVCC.exe % in combination with a Visual Studio compiler. After this Cuda % files can be compiled into kernels % % If you call the code the first time, or with "nvcc -config": % 1) It will try to locate the "The NVIDIA GPU Computing Toolkit", which % can be downloaded from www.nvidia.com/object/cuda_get.html % Typical Location : % C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v3.2\bin % 2) It will try to locate the visual studio compiler % Typical Location : % C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\ % 3) It creates a file nvccbat.bat with the compiler information. % % After this configuration procedure, you can compile files with: % % % nvcc(filename); % % or % % nvcc(options,filename) % % filename : A string with the filename, for example 'example.cu' % options : NVCC Compiler options for example, % nvcc(option1, option2, option3,filename) % % For help on NVCC config options type, "nvcc --help" % % % Note! % If the NVCC fails to locate the compiler you can try to % write your own "nvccbat.bat" file in a text-editor, for example: % echo off % set PATH=C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\;%PATH% % set PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v3.2\bin;%PATH% % call vcvars32.bat % nvcc %1 %2 %3 %4 %5 %6 %7 %8 %9 % % % % 1 Example, Configuration % % Locate Cuda and VS compiler % nvcc -config % % % Show the NVCC compiler options % nvcc --help % % % Test some input options % nvcc --dryrun -ptx example.cu % % 2 Example, % % % Locate Cuda and VS compiler % nvcc -config % % Compile the code % nvcc('example.cu'); % % It the same as : % % nvcc -ptx example.cu % % % Make the kernel % Kernel = parallel.gpu.CUDAKernel('example.ptx', 'example.cu'); % % % We want to execute this kernel 100 times % Kernel.ThreadBlockSize=100; % % % We make an array with 100 random files % Data=rand(100, 1, 'single'); % DataCuda= gpuArray(Data); % % % We will add the value 1 % OneCuda = parallel.gpu.GPUArray.ones(1,1); % % % Execute the kernel % DataOneCuda = feval(Kernel, DataCuda, OneCuda); % % % Get the data back % DataOne=gather(DataOneCuda); % % % Show the result % figure, hold on; % plot(Data,'b'); % plot(DataOne,'r'); % % Function is written by D.Kroon University of Twente (December 2010) if(nargin<1) error('nvcc:inputs','Need at least one input'); end % Copy configuration file to current folder functionname='nvcc.m'; functiondir=which(functionname); functiondir=functiondir(1:end-length(functionname)); afilename=[cd '\nvccbat.bat']; cfilename=[functiondir '\nvccbat.bat']; if(~exist(afilename,'file')) if(exist(cfilename,'file')) fid = fopen(cfilename, 'r'); fiw = fopen('nvccbat.bat', 'w'); fwrite(fiw,fread(fid, inf, 'uint8=>uint8')); fclose(fiw); fclose(fid); else % If configuration file doesn't exist, go to config mode varargin{1}='-config'; end end if(strcmp(varargin{1},'-config')) % Configuration Mode % Locate the Cuda Toolkit filenametoolkit=toolkit_selection; disp('.'); disp(['Toolkit Path: ' filenametoolkit]); % Locate the microsoft compiler [filenamecompiler,filenamecompilerbat]=compiler_selection(); disp('.'); disp(['VS Compiler: ' filenamecompiler]); % Create a bat file which will excecute the nvcc compiler createbatfile(filenamecompiler,filenametoolkit, filenamecompilerbat,cfilename); else % Compile a .cu file using the nvcc.exe compiler % If no input options compile as .ptx kernel file if(nargin<2), str=['-ptx ' varargin{1}]; else % Add all input options str=''; for i=1:nargin, str=[str varargin{i} ' ']; end if(nargin>9) warning('nvcc:inputs','Only 8 input options allowed'); end end % Excecute the bat file to compile a .cu file [status,result] = system(['nvccbat ' str]); disp(result); end function createbatfile(filenamecompiler,filenametoolkit, filenamecompilerbat,cfilename) fid = fopen(cfilename,'w'); fprintf(fid,'echo off\r\n'); fprintf(fid,'%s\r\n',['set PATH=' filenamecompiler ';%PATH%']); fprintf(fid,'%s\r\n',['set PATH=' filenametoolkit ';%PATH%']); fprintf(fid,['call ' filenamecompilerbat '\r\n']); fprintf(fid,'nvcc %%1 %%2 %%3 %%4 %%5 %%6 %%7 %%8 %%9 \r\n'); fclose(fid); % This function will try to locate the installed NVIDIA toolkits function filenametoolkit=toolkit_selection() str=getenv('ProgramFiles'); str=[str '\NVIDIA GPU Computing Toolkit\CUDA']; if(~isdir(str)) str=getenv('ProgramW6432'); str=[str '\NVIDIA GPU Computing Toolkit\CUDA']; if(~isdir(str)) str=getenv('ProgramFiles(x86)'); str=[str '\NVIDIA GPU Computing Toolkit\CUDA']; else error('nvcc:notfound','The NVIDIA GPU Computing Toolkit is not found, please make sure you have downloaded and installed the toolkit'); end end files=dir([str '\*']); filenametoolkitlist=cell(1,10); n=0; for i=1:length(files) if((files(i).name(1)~='.')&&files(i).isdir) filenametoolkit=[str '\' files(i).name '\bin']; if(exist(filenametoolkit,'dir')), n=n+1; filenametoolkitlist{n}=filenametoolkit; end end end if(n==0) error('nvcc:notfound','The NVIDIA GPU Computing Toolkit is not found, please make sure you have downloaded and installed the toolkit'); end disp('Cuda Toolkits Found : ') disp('------------------------------------------------------------------') for i=1:n disp(['[' num2str(i) '] ' filenametoolkitlist{i}]) end disp('------------------------------------------------------------------') p=input('Select the Cuda Toolkit you want to use : '); filenametoolkit=filenametoolkitlist{p}; % This function will try to locate all installed Microsoft Visual Compilers function [filenamecompiler, filenamecompilerbat]=compiler_selection() compilerfilenames=cell(1,10); compilerfilenamesbat=cell(1,10); n=0; for j=1:3 switch(j) case 1 str=getenv('ProgramFiles'); case 2 str=getenv('ProgramW6432'); case 3 str=getenv('ProgramFiles(x86)'); end if(~isempty(str)) a=dir([str '\Microsoft Visual*']); for i=1:length(a) filename=[str '\' a(i).name '\VC\bin\amd64\']; filenamebat=[filename 'vcvarsamd64.bat']; if(exist(filenamebat,'file')) n=n+1; compilerfilenames{n}=filename; compilerfilenamesbat{n}='vcvarsamd64.bat'; end filename=[str '\' a(i).name '\VC\bin\']; filenamebat=[filename 'vcvars32.bat']; if(exist(filenamebat,'file')) n=n+1; compilerfilenames{n}=filename; compilerfilenamesbat{n}='vcvars32.bat'; end end end end if(n==0) error('nvcc:notfound','No visual studio compilers found, please make sure the compilers are installed'); end disp('Visual studio compilers Found : ') disp('------------------------------------------------------------------') for i=1:n disp(['[' num2str(i) '] ' compilerfilenames{i}]) end disp('------------------------------------------------------------------') p=input('Select the visual studio compiler you want to use : '); filenamecompiler=compilerfilenames{p}; filenamecompilerbat=compilerfilenamesbat{p};
github
lob-epfl/sofitool-master
simulation_gen.m
.m
sofitool-master/GUI/codeStorm/FALCON2D/functions/simulation_gen.m
3,703
utf_8
eda1970cea6cf8f15efc9597464629e1
%% **************************************************************************************************** %% Simulated image generation %% %% Input: img_size : size of CCD image %% num_frame : number of images %% boundary_offset : boundary doesn't have any molecule %% num_mol : number of activated molecule in each frame %% mol_mu : mean value of emitted photons %% mol_sigma : standard deviation of emitted photons %% Gsigma1 & 2 : widths of Gaussian fuctions for PSF %% Gsimga_ratio : ratio for two Gaussian functions for PSF: PSF = Gsimga_ratio*F_sigma1 + (1-Gsimga_ratio)*F_sigma2 %% background : background fluorescent signal %% baseline : uniform offset for final image. %% EM : EM-gain option %% %% Output: CCD_imgs : blurred low resolution image + noise [short exposure multiple shots] %% true_pos : 2D coordinate of molecules' position (in px) %% true_photon : Number of emitted photons %% %% **************************************************************************************************** function [CCD_imgs,true_pos,true_photon] = simulation_gen(img_size,num_frame,boundary_offset,num_mol,mol_mu,mol_sigma,Gsigma1,Gsigma2,Gsigma_ratio,background,readout_rms,baseline,EM) % CCD images CCD_imgs = zeros(img_size,img_size,num_frame); % photon emission stat followed by log-normal distribution. m = log((mol_mu^2)/sqrt(mol_sigma^2+mol_mu^2)); % mean for log-normal function s = sqrt(log(mol_sigma^2/(mol_mu^2)+1)); % sigma for log-normal function true_photon = lognrnd(m,s,num_mol,num_frame); true_pos = zeros(num_mol,2,num_frame); % low-resolution grid ind_low = linspace(0.5,img_size-0.5,img_size); [x_grid_low, y_grid_low] = meshgrid(ind_low,ind_low); % boundary true_s = ind_low(boundary_offset)+0.5; true_e = ind_low(end-boundary_offset)+0.5; for t = 1:num_frame % random distribution true_pos(:,1,t) = true_s+(true_e-true_s).*rand(num_mol,1); true_pos(:,2,t) = true_s+(true_e-true_s).*rand(num_mol,1); % % Synthetic ring % radius = 2; % theta = 2*pi*rand(num_mol,1); % true_pos(:,1,t) = img_size/2 + radius*cos(theta); % true_pos(:,2,t) = img_size/2 + radius*sin(theta); % generate CCD image and SR images for ii = 1:num_mol low_kernel = Gsigma_ratio*Gauss_kernel(x_grid_low,y_grid_low,true_pos(ii,1,t),true_pos(ii,2,t),Gsigma1)... +(1-Gsigma_ratio)*Gauss_kernel(x_grid_low,y_grid_low,true_pos(ii,1,t),true_pos(ii,2,t),Gsigma2); low_kernel = low_kernel/sum(low_kernel(:)); CCD_imgs(:,:,t) = CCD_imgs(:,:,t) + true_photon(ii,t)*low_kernel; end end CCD_imgs = CCD_imgs + background; % add background fluorescent light if EM>0 CCD_imgs = CCD_imgs + 1.4*(poissrnd(CCD_imgs)-CCD_imgs); % shot-noise with excess noise factor of EM gain else CCD_imgs = poissrnd(CCD_imgs); % shot-noise with excess noise without EM gain end CCD_imgs = CCD_imgs + readout_rms*randn(size(CCD_imgs)); % readout noise followed by Gaussian stat if EM>0 CCD_imgs = CCD_imgs*EM; end CCD_imgs = CCD_imgs + baseline; % add offset baseline CCD_imgs = round(CCD_imgs); % discretization CCD_imgs(CCD_imgs<0) = 0; end
github
lob-epfl/sofitool-master
handover.m
.m
sofitool-master/GUI/codeStorm/FALCON2D/functions/handover.m
2,552
utf_8
ae20c2aadbee1edbd1eeb467dd4ae0a1
%% rearrange particles having high displacement values function [est_c_new,delta_x_new,delta_y_new,delta_z_new] = handover(est_c,delta_x,delta_y,delta_z) % find indices of particles which are close to adjacent grid points. ind_arrange = find((abs(delta_x)>0.99)|(abs(delta_y)>0.99)); est_c_new = est_c; delta_x_new = delta_x; delta_y_new = delta_y; delta_z_new = delta_z; % move the particles to the closest grid points % and adjust displacement terms. if ~isempty(ind_arrange) [Ny,Nx,Nz] = size(est_c); est_c_new(ind_arrange)=0; delta_x_new(ind_arrange)=0; delta_y_new(ind_arrange)=0; delta_z_new(ind_arrange)=0; weight = est_c_new>0; [pos_y,pos_x,pos_z] = ind2sub(size(est_c),ind_arrange); pos_y_new = min(max(pos_y + delta_y(ind_arrange),0.51),Ny+0.49); pos_x_new = min(max(pos_x + delta_x(ind_arrange),0.51),Nx+0.49); ind_new = sub2ind([Ny,Nx,Nz],round(pos_y_new),round(pos_x_new),pos_z); [ind_new2,ia] = unique(gather(ind_new)); delta_x_new_temp = pos_x_new - round(pos_x_new); delta_y_new_temp = pos_y_new - round(pos_y_new); delta_z_new_temp = delta_z(ind_arrange); photon_temp = est_c(ind_arrange); delta_x_new(ind_new2) = delta_x_new(ind_new2) + delta_x_new_temp(ia); delta_y_new(ind_new2) = delta_y_new(ind_new2) + delta_y_new_temp(ia); delta_z_new(ind_new2) = delta_z_new(ind_new2) + delta_z_new_temp(ia); est_c_new(ind_new2) = est_c_new(ind_new2)+photon_temp(ia); weight(ind_new2) = weight(ind_new2)+1; % In case that two particles are merged into the same grid bin if length(ind_new2)<length(ind_new) ind_new(ia) = 0; ind_temp = ind_new>0; delta_x_new_temp = delta_x_new_temp(ind_temp); delta_y_new_temp = delta_y_new_temp(ind_temp); delta_z_new_temp = delta_z_new_temp(ind_temp); photon_temp = photon_temp(ind_temp); [ind_new3,ia] = unique(gather(ind_new(ind_temp))); delta_x_new(ind_new3) = delta_x_new(ind_new3) + delta_x_new_temp(ia); delta_y_new(ind_new3) = delta_y_new(ind_new3) + delta_y_new_temp(ia); delta_z_new(ind_new3) = delta_z_new(ind_new3) + delta_z_new_temp(ia); est_c_new(ind_new3) = est_c_new(ind_new3)+photon_temp(ia); weight(ind_new3) = weight(ind_new3)+1; end % normalization delta_x_new(ind_new2) = delta_x_new(ind_new2)./weight(ind_new2); delta_y_new(ind_new2) = delta_y_new(ind_new2)./weight(ind_new2); delta_z_new(ind_new2) = delta_z_new(ind_new2)./weight(ind_new2); end end
github
lob-epfl/sofitool-master
Gen_kernels.m
.m
sofitool-master/GUI/codeStorm/FALCON2D/functions/Gen_kernels.m
3,818
utf_8
7ef51303f140e7c50d3c3c439993e97b
%% Point spread function and its derivatives generation. function [fPSF_decon,fPSF_refine,fPSF_dev_x,fPSF_dev_y,fPSF_dev_z] = ... Gen_kernels(x_dim,y_dim,up_decon,up_refine,Gsigma1,Gsigma2,Gsigma_ratio,delta_sigma) %% PSF for deconvolution steps 1&2 Gsigma1_decon = Gsigma1*up_decon; Gsigma2_decon = Gsigma2*up_decon; % generation sub-grid ind_s= 1/(2); ind_x = linspace(ind_s,(x_dim)*up_decon-ind_s,(x_dim)*up_decon); ind_y = linspace(ind_s,(y_dim)*up_decon-ind_s,(y_dim)*up_decon); [x_kernel_grid, y_kernel_grid] = meshgrid(ind_x,ind_y); ind_cx = ind_x(round(length(ind_x)/2+0.5)); ind_cy = ind_y(round(length(ind_y)/2+0.5)); scaling = up_decon^2; % PSF PSF = (Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy ,Gsigma1_decon)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy ,Gsigma2_decon)); PSF = PSF/sum(PSF(:))*scaling; % Fourier coefficients of PSF fPSF_decon= single(fft2(ifftshift(PSF))); %% PSF for refinement step Gsigma1_refine = Gsigma1*up_refine; Gsigma2_refine = Gsigma2*up_refine; scaling = up_refine^2; delta_eps = 0.5; % generation sub-grid ind_x = linspace(ind_s,(x_dim)*up_refine-ind_s,(x_dim)*up_refine); ind_y = linspace(ind_s,(y_dim)*up_refine-ind_s,(y_dim)*up_refine); [x_kernel_grid, y_kernel_grid] = meshgrid(ind_x,ind_y); ind_cx = ind_x(round(length(ind_x)/2+0.5)); ind_cy = ind_x(round(length(ind_y)/2+0.5)); % PSF PSF = (Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy ,Gsigma1_refine)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy ,Gsigma2_refine)); PSF = PSF/sum(PSF(:))*scaling; % Derivative of PSF in x axis. PSF_temp1 = (Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx + delta_eps*0.5 ,ind_cy ,Gsigma1_refine)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx + delta_eps*0.5,ind_cy ,Gsigma2_refine)); PSF_temp1 = PSF_temp1/sum(PSF_temp1(:))*scaling; PSF_temp2 = (Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx - delta_eps*0.5 ,ind_cy ,Gsigma1_refine)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx - delta_eps*0.5,ind_cy ,Gsigma2_refine)); PSF_temp2 = PSF_temp2/sum(PSF_temp2(:))*scaling; PSF_dev_x = ((PSF_temp2-PSF_temp1))/delta_eps; % Derivative of PSF in y axis. PSF_temp1 = (Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy+ delta_eps*0.5 ,Gsigma1_refine)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy + delta_eps*0.5,Gsigma2_refine)); PSF_temp1 = PSF_temp1/sum(PSF_temp1(:))*scaling; PSF_temp2 = (Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy - delta_eps*0.5 ,Gsigma1_refine)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy - delta_eps*0.5,Gsigma2_refine)); PSF_temp2 = PSF_temp2/sum(PSF_temp2(:))*scaling; PSF_dev_y = ((PSF_temp2-PSF_temp1))/delta_eps; % Derivative of PSF with respect to width PSF_temp1 = (Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx,ind_cy ,Gsigma1_refine*(1+delta_sigma/2))... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx,ind_cy ,Gsigma2_refine*(1+delta_sigma/2))); PSF_temp1 = PSF_temp1/sum(PSF_temp1(:))*scaling; PSF_temp2 = (Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx,ind_cy ,Gsigma1_refine*(1-delta_sigma/2))... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx,ind_cy ,Gsigma2_refine*(1-delta_sigma/2))); PSF_temp2 = PSF_temp2/sum(PSF_temp2(:))*scaling; PSF_dev_z = ((PSF_temp2-PSF_temp1)/delta_sigma); % Fourier coefficients of PSF,PSF_dev_x,PSF_dev_y,PSF_dev_z fPSF_refine= single(fft2(ifftshift(PSF))); fPSF_dev_x= single(fft2(ifftshift(PSF_dev_x))); fPSF_dev_y= single(fft2(ifftshift(PSF_dev_y))); fPSF_dev_z= single(fft2(ifftshift(PSF_dev_z))); end
github
lob-epfl/sofitool-master
simul_eval.m
.m
sofitool-master/GUI/codeStorm/FALCON2D/functions/simul_eval.m
1,737
utf_8
bfa63a35225e00195e9aef18e28c2663
%% **************************************************************************************************** %% calculation of localization error in x,y direction. %% each localized particle is matched to the closest true particle within a radius %% **************************************************************************************************** function [num_idens,num_clusters,errors_x,errors_y] = simul_eval(Results,true_poses,pitch,num_frame,radius) num_idens = zeros(num_frame,1); num_clusters = zeros(num_frame,1); errors_x = []; errors_y = []; for tt = 1:num_frame ind = find(Results(:,1) == tt); est_pos = Results(ind,2:3); true_pos = true_poses(:,:,tt); num_cluster = size(est_pos,1); if num_cluster num_iden_temp = zeros(1,size(true_pos,1)); error_x = zeros(num_cluster,1); error_y = zeros(num_cluster,1); num_cluster_temp = zeros(num_cluster,1); for ii = 1: num_cluster % find the closest true location distance = sqrt((true_pos(:,1)-est_pos(ii,1)).^2 + (true_pos(:,2)-est_pos(ii,2)).^2); [error_2D,index] = min(distance*pitch); if abs(error_2D) < radius num_iden_temp(index) = 1; num_cluster_temp(ii) = 1; error_x(ii) = (true_pos(index,1)-est_pos(ii,1))*pitch; error_y(ii) = (true_pos(index,2)-est_pos(ii,2))*pitch; end end ind = find(num_cluster_temp>0); num_idens(tt) = sum(num_iden_temp(:)); num_clusters(tt) = num_cluster; error_x = error_x(ind); error_y = error_y(ind); errors_x = [errors_x(:); error_x(:)]; errors_y = [errors_y(:); error_y(:)]; end end
github
lob-epfl/sofitool-master
Gauss_kernel.m
.m
sofitool-master/GUI/codeStorm/FALCON2D/functions/Gauss_kernel.m
646
utf_8
df3fea6cbfa7cebbba874149c2fce428
%% **************************************************************************************************** %% Return 2D guassian kernel %% %% Input: x_inx,y_inx : meshgrid of x and y %% x_pos,y_pos : center_position %% Gsigma : standard deviation of gaussian function %% %% Output: img_kernel : 2D Guassian kernel %% **************************************************************************************************** function img_kernel = Gauss_kernel(x_inx,y_inx,x_pos,y_pos,Gsigma) img_kernel = exp(-((x_inx-x_pos).^2+(y_inx-y_pos).^2)/(2*Gsigma^2))/(2*pi*Gsigma^2) ; end
github
lob-epfl/sofitool-master
LS_fitting.m
.m
sofitool-master/GUI/codeStorm/FALCON2D/functions/LS_fitting.m
5,630
utf_8
d625f417f4987484703fb8736f79d5e6
%% % Output % Results = [frame, amplitude, sigma1,sigma2,sigma_ratio,xPos,yPos,background,resnorm/sum(ccd_image(:))] % %% function [Results] = LS_fitting(filename,num_frame,dummy_frame,ADU,baseline,thresh,debug) Results = []; num_frame = min(num_frame,length(imfinfo(filename))); fprintf('running \n'); parfor ii = 1:num_frame fprintf('running... %d frame \n',ii); low_img = imread(filename,ii+dummy_frame); low_img = double(ADU*(low_img-baseline)); if debug > 0 figure(1); imagesc(low_img); colormap(hot); axis image; colorbar; end [LS_result]= Gaussfit(low_img,thresh); if~isempty(LS_result) Result_temp = zeros(size(LS_result,1),9); Result_temp(:,1) = ii; Result_temp(:,2:3) = LS_result(:,5:6)-0.5; Result_temp(:,4) = LS_result(:,1); Result_temp(:,5) = LS_result(:,2); Result_temp(:,6) = LS_result(:,3); Result_temp(:,7) = LS_result(:,4); Result_temp(:,8) = LS_result(:,7); Result_temp(:,9) = LS_result(:,8); Results = [Results;Result_temp]; end end % fitting the data by sum of two gaussians. function [fitresults]= Gaussfit(image,threshold) epsilon1 = 10^-3; epsilon2 = 10^-3; maxIter = 50; curvefitoptions = optimset( 'lsqcurvefit'); curvefitoptions = optimset( curvefitoptions,'Jacobian' ,'off','Display', 'off', 'TolX', epsilon2, 'TolFun', epsilon1,'MaxPCGIter',1,'MaxIter',maxIter); fitresults=[]; temp= calcstorm(image,threshold,curvefitoptions); % do the storm fit %MATLAB VERSION fitresults=[fitresults;temp]; function fitresults = calcstorm(image,threshold,curvefitoptions) % do the storm calculation windowSize= 3; [sizey sizex] = size(image); points = findpeaksMod(image, threshold); if isempty(points)==0 nrspots=length(points(:,1)); fitresults=zeros(nrspots,8); for i=1:nrspots, X0=points(i,1); Y0=points(i,2); %round X0, Y0 to use as matrix locations X0_int = round(X0); Y0_int = round(Y0); xstart = X0_int-windowSize; xfinish = X0_int+windowSize; ystart = Y0_int-windowSize; yfinish = Y0_int+windowSize; if (xstart>1) && (xfinish < sizex) && (ystart>1) && (yfinish < sizey) X_POSim = X0-xstart+1; Y_POSim = Y0-ystart+1; img=double(image(ystart:yfinish,xstart:xfinish)); background= min(img(:)); brightness = sum(img(:)-background); widthStart = 1.5; sRatioStart = 2; initguess=double([brightness,1,widthStart,sRatioStart,X_POSim,Y_POSim, background]); xLim = [0 sizex]; yLim = [0 sizey]; sigma1Lim = [0.5 3]; [fitParams,res] = doubleGauss2d_Fit(img,initguess ,xLim,yLim, sigma1Lim,curvefitoptions);%MATLAB ONLY % assign the data xPos = fitParams(5)+xstart-1; yPos = fitParams(6)+ystart-1; sigma1 = fitParams(3); sigma2 = fitParams(3)*fitParams(4); background = fitParams(7); amplitude = fitParams(1); sigma_ratio = fitParams(2); fitresults(i,:)=[amplitude, sigma1,sigma2,sigma_ratio,xPos,yPos,background,res/sum(img(:))]; end end fitresults = fitresults(all(fitresults,2) >0,:); else fitresults=[]; end %---------------------------------------------------------------------------------------------- function [fitParam,res] = doubleGauss2d_Fit(inputIm,initguess ,xLim,yLim, sigmaLim,curvefitoptions) Astart = initguess(1); ARstart = initguess(2); widthStart = initguess(3); sRatioStart = initguess(4); xStart = initguess(5); yStart = initguess(6); BGstart = initguess(7); xMin = xLim(1); xMax = xLim(2); yMin = yLim(1); yMax = yLim(2); sigmaMin = sigmaLim(1); sigmaMax = sigmaLim(2); sRatioMin = 2; sRatioMax = 4; [sizey sizex] = size(inputIm); [X,Y]= meshgrid(1:sizex,1:sizey); grid = [X Y]; initGuess7Vector = [Astart ARstart widthStart sRatioStart xStart yStart BGstart]; lb = [ 1 0.5 sigmaMin sRatioMin xMin yMin 0 ]; ub = [65535 1 sigmaMax sRatioMax xMax yMax 65535]; try [fitParam, res] = ... lsqcurvefit(@(x, xdata) doubleGauss2d(x, xdata), ... initGuess7Vector ,grid ,inputIm ,... lb,ub,curvefitoptions); catch ME if strcmp(ME.identifier,'optim:snls:InvalidUserFunction') fitParam = [0 0 0 0 0 0 0]; res = 0; else rethrow(ME); end end if fitParam(1)< 0 fitParam = [0 0 0 0 0 0 0]; end function F = doubleGauss2d(a, data) % sum of two symmetric Gaussian functions % a(1) - A % a(2) - Ar % a(3) - sigma % a(4) - sigma_ratio ex) sigma2 = sigma1*sigma_ratio % a(5) - Xpos % a(6) - Ypos % a(7) - B [sizey sizex] = size(data); sizex = sizex/2; X = data(:,1:sizex); Y = data(:,sizex+1:end); expPart1 = exp(-( (X-a(5)).^2 + (Y-a(6)).^2) /(2*(a(3))^2)); expPart2 = exp(-( (X-a(5)).^2 + (Y-a(6)).^2 )/(2*(a(3)*a(4))^2)); expPart = a(1)*a(2)*expPart1/(2*pi*a(3)^2) + a(1)*(1-a(2))*expPart2/(2*pi*a(4)^2); F = expPart + a(7); %% % below functions are related to local peak detection %----------------------------------------------------------------------------------- function peaks = findpeaksMod(im, threshold) wavelet_level = 5; background = background_estimation(im,1,wavelet_level,'db6',5); g = fspecial('gaussian',11,1); im2 = imfilter(im-background,g,'symmetric','conv'); [peaks] = Peakdet2D(im2,threshold,2); %-----------------------------------------------------------------------------------
github
lob-epfl/sofitool-master
Gen_Gauss_kernels.m
.m
sofitool-master/GUI/codeStorm/FALCON2D/functions/Gen_Gauss_kernels.m
3,918
utf_8
0a7d4ef7852ae69564737e36f33b7b60
%% Point spread function and its derivatives generation. function [fPSF_decon,fPSF_refine,fPSF_dev_x,fPSF_dev_y,fPSF_dev_z] = ... Gen_Gauss_kernels(x_dim,y_dim,up_decon,up_refine,zero_pad,Gsigma1,Gsigma2,Gsigma_ratio,delta_sigma) %% PSF for deconvolution steps Gsigma1_decon = Gsigma1*up_decon; Gsigma2_decon = Gsigma2*up_decon; % generation sub-grid ind_s= 1/(2); ind_x = linspace(ind_s,(x_dim+zero_pad)*up_decon-ind_s,(x_dim+zero_pad)*up_decon); ind_y = linspace(ind_s,(y_dim+zero_pad)*up_decon-ind_s,(y_dim+zero_pad)*up_decon); [x_kernel_grid, y_kernel_grid] = meshgrid(ind_x,ind_y); ind_cx = ind_x(round(length(ind_x)/2+0.5)); ind_cy = ind_y(round(length(ind_y)/2+0.5)); scale = up_decon^2; % PSF PSF = single(Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy ,Gsigma1_decon)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy ,Gsigma2_decon)); PSF = PSF/sum(PSF(:))*scale; % Fourier coefficients of PSF fPSF_decon= (fft2(ifftshift(PSF))); %% PSF for refinement step Gsigma1_refine = Gsigma1*up_refine; Gsigma2_refine = Gsigma2*up_refine; scale = up_refine^2; delta_eps = 0.5; % generation sub-grid ind_x = linspace(ind_s,(x_dim+zero_pad)*up_refine-ind_s,(x_dim+zero_pad)*up_refine); ind_y = linspace(ind_s,(y_dim+zero_pad)*up_refine-ind_s,(y_dim+zero_pad)*up_refine); [x_kernel_grid, y_kernel_grid] = meshgrid(ind_x,ind_y); ind_cx = ind_x(round(length(ind_x)/2+0.5)); ind_cy = ind_x(round(length(ind_y)/2+0.5)); % PSF PSF = single(Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy ,Gsigma1_refine)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy ,Gsigma2_refine)); PSF = PSF/sum(PSF(:))*scale; % Derivative of PSF in x axis. PSF_temp1 = single(Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx + delta_eps*0.5 ,ind_cy ,Gsigma1_refine)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx + delta_eps*0.5,ind_cy ,Gsigma2_refine)); PSF_temp1 = PSF_temp1/sum(PSF_temp1(:))*scale; PSF_temp2 = single(Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx - delta_eps*0.5 ,ind_cy ,Gsigma1_refine)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx - delta_eps*0.5,ind_cy ,Gsigma2_refine)); PSF_temp2 = PSF_temp2/sum(PSF_temp2(:))*scale; PSF_dev_x = single((PSF_temp2-PSF_temp1))/delta_eps; % Derivative of PSF in y axis. PSF_temp1 = single(Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy+ delta_eps*0.5 ,Gsigma1_refine)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy + delta_eps*0.5,Gsigma2_refine)); PSF_temp1 = PSF_temp1/sum(PSF_temp1(:))*scale; PSF_temp2 = single(Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy - delta_eps*0.5 ,Gsigma1_refine)... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx ,ind_cy - delta_eps*0.5,Gsigma2_refine)); PSF_temp2 = PSF_temp2/sum(PSF_temp2(:))*scale; PSF_dev_y = single((PSF_temp2-PSF_temp1))/delta_eps; % Derivative of PSF with respect to width PSF_temp1 = single(Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx,ind_cy ,Gsigma1_refine*(1+delta_sigma/2))... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx,ind_cy ,Gsigma2_refine*(1+delta_sigma/2))); PSF_temp1 = PSF_temp1/sum(PSF_temp1(:))*scale; PSF_temp2 = single(Gsigma_ratio*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx,ind_cy ,Gsigma1_refine*(1-delta_sigma/2))... + (1-Gsigma_ratio)*Gauss_kernel(x_kernel_grid,y_kernel_grid,ind_cx,ind_cy ,Gsigma2_refine*(1-delta_sigma/2))); PSF_temp2 = PSF_temp2/sum(PSF_temp2(:))*scale; PSF_dev_z = single((PSF_temp2-PSF_temp1)/delta_sigma); % Fourier coefficients of PSF,PSF_dev_x,PSF_dev_y,PSF_dev_z fPSF_refine= (fft2(ifftshift(PSF))); fPSF_dev_x= (fft2(ifftshift(PSF_dev_x))); fPSF_dev_y= (fft2(ifftshift(PSF_dev_y))); fPSF_dev_z= (fft2(ifftshift(PSF_dev_z))); end
github
lob-epfl/sofitool-master
background_estimation.m
.m
sofitool-master/GUI/codeStorm/FALCON2D/functions/background_estimation.m
1,032
utf_8
34368ccbaebf0b8e7298017c84ecaf4d
%% background estimation using iterative wavelet transform function est_bg = background_estimation(imgs,th,dlevel,wavename,iter) est_bg = zeros(size(imgs),'single'); imgs = max(imgs,0); for N = 1: size(imgs,3) X = imgs(:,:,N); X_filt = X; for ii = 1:iter % wavelet transform [c,s] = wavedec2(X_filt,dlevel,wavename); cc = zeros(size(c)); cc(1:s(1)*s(1)*1) = c(1:s(1)*s(1)*1); % inverse wavelet transform by only using low-freq components X_new = waverec2(cc,s,wavename); if th > 0 % cut off values over current estimated background level. eps = sqrt(abs(X_filt))/2; ind = X>(X_new+eps); X_filt(ind) = X_new(ind)+eps(ind); % re-estimate background [c,s] = wavedec2(X_filt,dlevel,wavename); cc = zeros(size(c)); cc(1:s(1)*s(1)*1) = c(1:s(1)*s(1)*1); X_new = waverec2(cc,s,wavename); end end est_bg(:,:,N) = X_new; end end
github
lob-epfl/sofitool-master
super_render.m
.m
sofitool-master/GUI/codeStorm/FALCON2D/functions/super_render.m
2,426
utf_8
07cf8db3f2aa9c7d4f3bd85809d7282d
%% Generating super-resolution images %% %% Input: Nx : length of image in x axis (px) %% Ny : length of image in x axis (px) %% est_photon : estimated photons %% est_pos : estimated positions %% up_ren : upsampling factor for SR images %% width : FWHM of Gaussian functions for rendering %% %% Output: sr_img : super-resolution image rendered by normalized Gaussian functions %% sr_img_scale : super-resolution image rendered by weighted Gaussian functions by estimated photons %% sr_img_bin : super-resolution image as 2D histogram function [sr_img,sr_img_scale,sr_img_bin] = super_render(Nx,Ny,est_photon,est_pos,up_ren,width) %% initailize sr_img= zeros(Nx*up_ren,Ny*up_ren); sr_img_scale = zeros(Nx*up_ren,Ny*up_ren); kernel_size = 3; Gsigma_sr = width/up_ren/2.3458; ss= 1/(2*up_ren); ind_sr = linspace(ss,kernel_size-ss,kernel_size*up_ren); if mod(length(ind_sr),2) == 0 ind_sr = ind_sr(1:end-1); end s = floor(length(ind_sr)/2+1); ind_c = mean(ind_sr); % mesggrid for super-resolution image [x_grid_sr, y_grid_sr] = meshgrid(ind_sr,ind_sr); % discard locations near boundary ind = find( (est_pos(:,1)>ceil(kernel_size/2)).*(est_pos(:,2)>ceil(kernel_size/2))... .*(est_pos(:,1)< (Ny-ceil(kernel_size/2))).* (est_pos(:,2)< (Nx-ceil(kernel_size/2)))); est_pos = est_pos(ind,:); est_photon = est_photon(ind); %% generate low_res image and high_res images for ii = 1:length(est_photon) pos_bin = round(est_pos(ii,:)*up_ren); pos_delta = (est_pos(ii,:)*up_ren-pos_bin)/up_ren; high_kernel = Gauss_kernel(x_grid_sr,y_grid_sr,ind_c+pos_delta(1),ind_c+pos_delta(2),Gsigma_sr); high_kernel = high_kernel/sum(high_kernel(:)); sr_img(pos_bin(2)-s+(1:length(ind_sr)),pos_bin(1)-s+(1:length(ind_sr))) = ... sr_img(pos_bin(2)-s+(1:length(ind_sr)),pos_bin(1)-s+(1:length(ind_sr))) + high_kernel; sr_img_scale(pos_bin(2)-s+(1:length(ind_sr)),pos_bin(1)-s+(1:length(ind_sr))) = ... sr_img_scale(pos_bin(2)-s+(1:length(ind_sr)),pos_bin(1)-s+(1:length(ind_sr))) + est_photon(ii)*high_kernel; end xLims = linspace(0,Nx*up_ren,Nx*up_ren); yLims = linspace(0,Ny*up_ren,Ny*up_ren); sr_img_bin = hist3(est_pos*up_ren-0.5,{yLims, xLims}); sr_img_bin = rot90(flipud(sr_img_bin),3); end
github
lob-epfl/sofitool-master
Peakdets.m
.m
sofitool-master/GUI/codeStorm/FALCON2D/functions/Peakdets.m
1,253
utf_8
b1f877a43cf8325c0161b316cbf183ea
%% find local peaks and get initial localizations by center of mass function [est_c_new,delta_x,delta_y] = Peakdets(est_c,thresh) [Ny,Nx,Nt] = size(est_c); img = zeros(Ny,Nx,'single'); est_c_new = zeros(size(est_c),'single'); delta_x = zeros(size(est_c),'single'); delta_y = zeros(size(est_c),'single'); c_mask = ones(3); x_mask = [-1 0 1;-1 0 1;-1 0 1]; x_mask = x_mask(:); y_mask = [-1 -1 -1; 0 0 0; 1 1 1]; y_mask = y_mask(:); est_c_copy = est_c; est_c_copy(est_c<thresh) = 0; for tt = 1: Nt img(2:end-1,2:end-1) = est_c_copy(2:end-1,2:end-1,tt); [I,J,~] = find(img>0); for ii = 1:length(I) xx = J(ii); yy = I(ii); img_temp = est_c(yy-1:yy+1,xx-1:xx+1,tt); % for local maxima if est_c(yy,xx,tt) >= max(img_temp(:)) % center of mass img_temp2 = c_mask(:).*img_temp(:); photon = sum(img_temp2); dx = sum(x_mask.*img_temp2)/photon; dy = sum(y_mask.*img_temp2)/photon; pos_y = yy+round(dy); pos_x = xx+round(dx); est_c_new(pos_y,pos_x,tt) = photon; delta_x(pos_y,pos_x,tt) = dx-round(dx); delta_y(pos_y,pos_x,tt) = dy-round(dy); end end end end
github
tgen/lumosVar2-master
printNormalMetrics_byChr.m
.m
lumosVar2-master/src/printNormalMetrics_byChr.m
6,471
utf_8
02a10bcf33373cd0dddf611ec5eca06c
function printNormalMetrics_byChr_v2(configFile,step) %printNormalMetrics - gets mean read depths and %position quality scores for a set of normal bams %calls parsePileupData.packed.pl to parse samtools output %writes a bgziped tabix index table for each chromosome %prerequisite for running TumorOnlyWrapper.m % % Syntax: printNormalMetrics(configFile) % % Inputs: % configFile - contains input parameters in yaml format % % Outputs: % writes one table per chromosome. Each table is bgziped and tabix indexed. % tables have columns: 1-'Chr',2-'Pos',3-'ControlRD', 4-'PosMapQC', % 5-'perReadPass',6-'abFrac' % % Other m-files required: calculateNormalMetrics.m % Other requirements: parsePileupData.packed.pl, indexControlMetrics.sh, % samtools, htslib % Subfunctions: none % MAT-files required: none % % See also: TumorOnlyWrapper % Author: Rebecca F. Halperin, PhD % Translational Genomics Research Institute % email: [email protected] % Website: https://github.com/tgen % Last revision: 3-June-2016 %------------- BEGIN CODE -------------- %%% read in parameters inputParam=readInputs(configFile); regionsFile=inputParam.regionsFile; outfile=inputParam.outfile; blockSize=inputParam.blockSize; priorMapError=inputParam.priorMapError; chrIdx=str2num(step); step chrIdx sexChr=regexp(inputParam.sexChr,',','split'); chrList=[cellstr(num2str(inputParam.autosomes','%-d')); sexChr'] [lia,locb]=ismember(chrList(chrIdx),sexChr); sexList=regexp(inputParam.sexList,',','split'); ploidyList=nan(size(sexList)); if lia mIdx=strcmp('M',sexList); ploidyList(mIdx)=inputParam.M(locb); fIdx=strcmp('F',sexList); ploidyList(fIdx)=inputParam.F(locb); else ploidyList=2*ones(size(sexList)) end %%% read in bedfile regTable=readtable(regionsFile,'FileType','text','Delimiter','\t','ReadVariableNames',false); [lia,locb]=ismember(regTable{:,1},chrList); Regions=[locb(lia) regTable{lia,2:3}]; % size(regTable) % if ~isnumeric(regTable{:,1}) % chr=cellfun(@str2num,regTable{:,1},'UniformOutput',0); % size(chr) % pos=~cellfun(@isempty,chr); % sum(pos) % Regions=[cell2mat(chr(pos)) regTable{pos,2:3}]; % else % Regions=regTable{:,1:3}; % end %for chrIdx=1:length(chrList) %%% open output files if(~exist([outfile '_' chrList{chrIdx} '.txt.gz'],'file')) if(exist([outfile '_' chrList{chrIdx} '.txt'],'file')) fout=fopen([outfile '_' chrList{chrIdx} '.txt'],'a+'); ferror=fopen([outfile '_' chrList{chrIdx} '.errorLog.txt'],'a+'); [q,w] = system(['tail -n 1 ' outfile '_' chrList{chrIdx} '.txt']); data=str2double(regexp(w,'\t','split')); currRegion=double(Regions(Regions(:,1)==chrIdx,:)); size(currRegion) if(size(data,2)==6) idx=getPosInRegions([chrIdx data(2)],currRegion); currRegion(idx,:); currRegion=currRegion(idx:end,:); currRegion(1,2)=data(2); end else fout=fopen([outfile '_' chrList{chrIdx} '.txt'],'w'); ferror=fopen([outfile '_' chrList{chrIdx} '.errorLog.txt'],'w'); currRegion=double(Regions(Regions(:,1)==chrIdx,:)); end largeIdx=find(currRegion(:,3)-currRegion(:,2)>blockSize); subCount=ceil((currRegion(largeIdx,3)-currRegion(largeIdx,2))./blockSize); newSize=(currRegion(largeIdx,3)-currRegion(largeIdx,2))./subCount; newRegions=nan(sum(subCount),3); if ~isempty(subCount) newRegions(1:subCount(1),:)=[chrIdx*ones(subCount(1),1) round([currRegion(largeIdx(1),2):newSize(1):currRegion(largeIdx(1),3)-newSize(1)]') round([currRegion(largeIdx(1),2)+newSize(1)-1:newSize(1):currRegion(largeIdx(1),3)]')]; for i=2:length(largeIdx) newRegions(sum(subCount(1:i-1))+1:sum(subCount(1:i)),:)=[chrIdx*ones(subCount(i),1) round([currRegion(largeIdx(i),2):newSize(i):currRegion(largeIdx(i),3)-newSize(i)]') round([currRegion(largeIdx(i),2)+newSize(i)-1:newSize(i):currRegion(largeIdx(i),3)]')]; end currRegion=[currRegion(currRegion(:,3)-currRegion(:,2)<=blockSize,:); newRegions]; currRegion=sortrows(currRegion,2); end startIdx=1; endIdx=1; %%% split up regions greater than block size %%% analyze by region while(endIdx<size(currRegion,1)) %currRegion [startIdx endIdx] endIdx=find(cumsum(currRegion(startIdx:end,3)-currRegion(startIdx:end,2))>blockSize,1)+startIdx-1; if isempty(endIdx) endIdx=size(currRegion,1); end %%% bet pileup data block=[chrList{chrIdx} ':' num2str(currRegion(startIdx,2)) '-' num2str(currRegion(endIdx,3))] output=strsplit(perl('parsePileupData.packed.pl',configFile,block,'0'),'\n'); idx=~cellfun('isempty',regexp(output,'^\d')); NormalData=str2num(char(regexprep(output(idx),chrList{chrIdx},num2str(chrIdx))')); fprintf(ferror,'%s\n',output{~idx}); if(isempty(NormalData)) fprintf(ferror,'%s\n',['Normal Data not found in ' block]); for i=1:length(output) fprintf(ferror,'%s\n',output{i}); end startIdx=endIdx+1; continue; end %%% calculate normal metrics output={}; sampleIds=unique(NormalData(:,1)); allPos=[currRegion(startIdx,2):currRegion(endIdx,3)]'; idx=getPosInRegions([chrIdx.*ones(currRegion(endIdx,3)-currRegion(startIdx,2)+1,1) allPos],currRegion(startIdx:endIdx,:)); outPos=allPos(~isnan(idx)); normalMetrics=nan(length(outPos),6,length(sampleIds)); for i=1:length(sampleIds) sampleData=NormalData(NormalData(:,1)==sampleIds(i),:); [Lia,Locb]=ismember(outPos,sampleData(:,3)); currData=[chrIdx.*ones(size(outPos)) outPos nan(length(outPos),size(NormalData,2)-3)]; currData(Lia,:)=sampleData(Locb(Lia),2:end); normalMetrics(:,:,sampleIds(i))=calculateNormalMetrics(currData,priorMapError,ploidyList(i)); end %%% find mean across samples and print to file meanNormalMetrics=nanmean(normalMetrics,3); fprintf(fout,'%d\t%d\t%f\t%f\t%f\t%f\n',meanNormalMetrics'); startIdx=endIdx+1; end fclose(fout); %%% bgzip and tabix index output file [status,cmdout]=system(['sh indexControlMetrics.sh ' outfile '_' chrList{chrIdx} '.txt ' inputParam.tabixPath],'-echo'); fprintf(ferror,'%s\n',cmdout); else status=0; end exit(status);